1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BranchProbabilityInfo.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/MemoryLocation.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/Analysis/VectorUtils.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/FunctionLoweringInfo.h" 40 #include "llvm/CodeGen/GCMetadata.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineJumpTableInfo.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RuntimeLibcalls.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 56 #include "llvm/CodeGen/StackMaps.h" 57 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 58 #include "llvm/CodeGen/TargetFrameLowering.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/CodeGen/WinEHFuncInfo.h" 66 #include "llvm/IR/Argument.h" 67 #include "llvm/IR/Attributes.h" 68 #include "llvm/IR/BasicBlock.h" 69 #include "llvm/IR/CFG.h" 70 #include "llvm/IR/CallSite.h" 71 #include "llvm/IR/CallingConv.h" 72 #include "llvm/IR/Constant.h" 73 #include "llvm/IR/ConstantRange.h" 74 #include "llvm/IR/Constants.h" 75 #include "llvm/IR/DataLayout.h" 76 #include "llvm/IR/DebugInfoMetadata.h" 77 #include "llvm/IR/DebugLoc.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/InlineAsm.h" 82 #include "llvm/IR/InstrTypes.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/Intrinsics.h" 87 #include "llvm/IR/LLVMContext.h" 88 #include "llvm/IR/Metadata.h" 89 #include "llvm/IR/Module.h" 90 #include "llvm/IR/Operator.h" 91 #include "llvm/IR/PatternMatch.h" 92 #include "llvm/IR/Statepoint.h" 93 #include "llvm/IR/Type.h" 94 #include "llvm/IR/User.h" 95 #include "llvm/IR/Value.h" 96 #include "llvm/MC/MCContext.h" 97 #include "llvm/MC/MCSymbol.h" 98 #include "llvm/Support/AtomicOrdering.h" 99 #include "llvm/Support/BranchProbability.h" 100 #include "llvm/Support/Casting.h" 101 #include "llvm/Support/CodeGen.h" 102 #include "llvm/Support/CommandLine.h" 103 #include "llvm/Support/Compiler.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/ErrorHandling.h" 106 #include "llvm/Support/MachineValueType.h" 107 #include "llvm/Support/MathExtras.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include "llvm/Target/TargetIntrinsicInfo.h" 110 #include "llvm/Target/TargetMachine.h" 111 #include "llvm/Target/TargetOptions.h" 112 #include "llvm/Transforms/Utils/Local.h" 113 #include <algorithm> 114 #include <cassert> 115 #include <cstddef> 116 #include <cstdint> 117 #include <cstring> 118 #include <iterator> 119 #include <limits> 120 #include <numeric> 121 #include <tuple> 122 #include <utility> 123 #include <vector> 124 125 using namespace llvm; 126 using namespace PatternMatch; 127 using namespace SwitchCG; 128 129 #define DEBUG_TYPE "isel" 130 131 /// LimitFloatPrecision - Generate low-precision inline sequences for 132 /// some float libcalls (6, 8 or 12 bits). 133 static unsigned LimitFloatPrecision; 134 135 static cl::opt<unsigned, true> 136 LimitFPPrecision("limit-float-precision", 137 cl::desc("Generate low-precision inline sequences " 138 "for some float libcalls"), 139 cl::location(LimitFloatPrecision), cl::Hidden, 140 cl::init(0)); 141 142 static cl::opt<unsigned> SwitchPeelThreshold( 143 "switch-peel-threshold", cl::Hidden, cl::init(66), 144 cl::desc("Set the case probability threshold for peeling the case from a " 145 "switch statement. A value greater than 100 will void this " 146 "optimization")); 147 148 // Limit the width of DAG chains. This is important in general to prevent 149 // DAG-based analysis from blowing up. For example, alias analysis and 150 // load clustering may not complete in reasonable time. It is difficult to 151 // recognize and avoid this situation within each individual analysis, and 152 // future analyses are likely to have the same behavior. Limiting DAG width is 153 // the safe approach and will be especially important with global DAGs. 154 // 155 // MaxParallelChains default is arbitrarily high to avoid affecting 156 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 157 // sequence over this should have been converted to llvm.memcpy by the 158 // frontend. It is easy to induce this behavior with .ll code such as: 159 // %buffer = alloca [4096 x i8] 160 // %data = load [4096 x i8]* %argPtr 161 // store [4096 x i8] %data, [4096 x i8]* %buffer 162 static const unsigned MaxParallelChains = 64; 163 164 // Return the calling convention if the Value passed requires ABI mangling as it 165 // is a parameter to a function or a return value from a function which is not 166 // an intrinsic. 167 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 168 if (auto *R = dyn_cast<ReturnInst>(V)) 169 return R->getParent()->getParent()->getCallingConv(); 170 171 if (auto *CI = dyn_cast<CallInst>(V)) { 172 const bool IsInlineAsm = CI->isInlineAsm(); 173 const bool IsIndirectFunctionCall = 174 !IsInlineAsm && !CI->getCalledFunction(); 175 176 // It is possible that the call instruction is an inline asm statement or an 177 // indirect function call in which case the return value of 178 // getCalledFunction() would be nullptr. 179 const bool IsInstrinsicCall = 180 !IsInlineAsm && !IsIndirectFunctionCall && 181 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 182 183 if (!IsInlineAsm && !IsInstrinsicCall) 184 return CI->getCallingConv(); 185 } 186 187 return None; 188 } 189 190 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 191 const SDValue *Parts, unsigned NumParts, 192 MVT PartVT, EVT ValueVT, const Value *V, 193 Optional<CallingConv::ID> CC); 194 195 /// getCopyFromParts - Create a value that contains the specified legal parts 196 /// combined into the value they represent. If the parts combine to a type 197 /// larger than ValueVT then AssertOp can be used to specify whether the extra 198 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 199 /// (ISD::AssertSext). 200 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 201 const SDValue *Parts, unsigned NumParts, 202 MVT PartVT, EVT ValueVT, const Value *V, 203 Optional<CallingConv::ID> CC = None, 204 Optional<ISD::NodeType> AssertOp = None) { 205 if (ValueVT.isVector()) 206 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 207 CC); 208 209 assert(NumParts > 0 && "No parts to assemble!"); 210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 211 SDValue Val = Parts[0]; 212 213 if (NumParts > 1) { 214 // Assemble the value from multiple parts. 215 if (ValueVT.isInteger()) { 216 unsigned PartBits = PartVT.getSizeInBits(); 217 unsigned ValueBits = ValueVT.getSizeInBits(); 218 219 // Assemble the power of 2 part. 220 unsigned RoundParts = 221 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 222 unsigned RoundBits = PartBits * RoundParts; 223 EVT RoundVT = RoundBits == ValueBits ? 224 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 225 SDValue Lo, Hi; 226 227 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 228 229 if (RoundParts > 2) { 230 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 231 PartVT, HalfVT, V); 232 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 233 RoundParts / 2, PartVT, HalfVT, V); 234 } else { 235 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 236 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 237 } 238 239 if (DAG.getDataLayout().isBigEndian()) 240 std::swap(Lo, Hi); 241 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 243 244 if (RoundParts < NumParts) { 245 // Assemble the trailing non-power-of-2 part. 246 unsigned OddParts = NumParts - RoundParts; 247 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 248 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 249 OddVT, V, CC); 250 251 // Combine the round and odd parts. 252 Lo = Val; 253 if (DAG.getDataLayout().isBigEndian()) 254 std::swap(Lo, Hi); 255 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 256 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 257 Hi = 258 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 259 DAG.getConstant(Lo.getValueSizeInBits(), DL, 260 TLI.getPointerTy(DAG.getDataLayout()))); 261 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 262 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 263 } 264 } else if (PartVT.isFloatingPoint()) { 265 // FP split into multiple FP parts (for ppcf128) 266 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 267 "Unexpected split"); 268 SDValue Lo, Hi; 269 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 270 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 271 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 272 std::swap(Lo, Hi); 273 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 274 } else { 275 // FP split into integer parts (soft fp) 276 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 277 !PartVT.isVector() && "Unexpected split"); 278 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 279 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 280 } 281 } 282 283 // There is now one part, held in Val. Correct it to match ValueVT. 284 // PartEVT is the type of the register class that holds the value. 285 // ValueVT is the type of the inline asm operation. 286 EVT PartEVT = Val.getValueType(); 287 288 if (PartEVT == ValueVT) 289 return Val; 290 291 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 292 ValueVT.bitsLT(PartEVT)) { 293 // For an FP value in an integer part, we need to truncate to the right 294 // width first. 295 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 296 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 297 } 298 299 // Handle types that have the same size. 300 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 301 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 302 303 // Handle types with different sizes. 304 if (PartEVT.isInteger() && ValueVT.isInteger()) { 305 if (ValueVT.bitsLT(PartEVT)) { 306 // For a truncate, see if we have any information to 307 // indicate whether the truncated bits will always be 308 // zero or sign-extension. 309 if (AssertOp.hasValue()) 310 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 311 DAG.getValueType(ValueVT)); 312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 313 } 314 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 315 } 316 317 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 318 // FP_ROUND's are always exact here. 319 if (ValueVT.bitsLT(Val.getValueType())) 320 return DAG.getNode( 321 ISD::FP_ROUND, DL, ValueVT, Val, 322 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 323 324 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 325 } 326 327 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 328 // then truncating. 329 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 330 ValueVT.bitsLT(PartEVT)) { 331 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 332 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 333 } 334 335 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 336 } 337 338 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 339 const Twine &ErrMsg) { 340 const Instruction *I = dyn_cast_or_null<Instruction>(V); 341 if (!V) 342 return Ctx.emitError(ErrMsg); 343 344 const char *AsmError = ", possible invalid constraint for vector type"; 345 if (const CallInst *CI = dyn_cast<CallInst>(I)) 346 if (isa<InlineAsm>(CI->getCalledValue())) 347 return Ctx.emitError(I, ErrMsg + AsmError); 348 349 return Ctx.emitError(I, ErrMsg); 350 } 351 352 /// getCopyFromPartsVector - Create a value that contains the specified legal 353 /// parts combined into the value they represent. If the parts combine to a 354 /// type larger than ValueVT then AssertOp can be used to specify whether the 355 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 356 /// ValueVT (ISD::AssertSext). 357 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 358 const SDValue *Parts, unsigned NumParts, 359 MVT PartVT, EVT ValueVT, const Value *V, 360 Optional<CallingConv::ID> CallConv) { 361 assert(ValueVT.isVector() && "Not a vector value"); 362 assert(NumParts > 0 && "No parts to assemble!"); 363 const bool IsABIRegCopy = CallConv.hasValue(); 364 365 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 366 SDValue Val = Parts[0]; 367 368 // Handle a multi-element vector. 369 if (NumParts > 1) { 370 EVT IntermediateVT; 371 MVT RegisterVT; 372 unsigned NumIntermediates; 373 unsigned NumRegs; 374 375 if (IsABIRegCopy) { 376 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 377 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 378 NumIntermediates, RegisterVT); 379 } else { 380 NumRegs = 381 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 382 NumIntermediates, RegisterVT); 383 } 384 385 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 386 NumParts = NumRegs; // Silence a compiler warning. 387 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 388 assert(RegisterVT.getSizeInBits() == 389 Parts[0].getSimpleValueType().getSizeInBits() && 390 "Part type sizes don't match!"); 391 392 // Assemble the parts into intermediate operands. 393 SmallVector<SDValue, 8> Ops(NumIntermediates); 394 if (NumIntermediates == NumParts) { 395 // If the register was not expanded, truncate or copy the value, 396 // as appropriate. 397 for (unsigned i = 0; i != NumParts; ++i) 398 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 399 PartVT, IntermediateVT, V); 400 } else if (NumParts > 0) { 401 // If the intermediate type was expanded, build the intermediate 402 // operands from the parts. 403 assert(NumParts % NumIntermediates == 0 && 404 "Must expand into a divisible number of parts!"); 405 unsigned Factor = NumParts / NumIntermediates; 406 for (unsigned i = 0; i != NumIntermediates; ++i) 407 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 408 PartVT, IntermediateVT, V); 409 } 410 411 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 412 // intermediate operands. 413 EVT BuiltVectorTy = 414 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 415 (IntermediateVT.isVector() 416 ? IntermediateVT.getVectorNumElements() * NumParts 417 : NumIntermediates)); 418 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 419 : ISD::BUILD_VECTOR, 420 DL, BuiltVectorTy, Ops); 421 } 422 423 // There is now one part, held in Val. Correct it to match ValueVT. 424 EVT PartEVT = Val.getValueType(); 425 426 if (PartEVT == ValueVT) 427 return Val; 428 429 if (PartEVT.isVector()) { 430 // If the element type of the source/dest vectors are the same, but the 431 // parts vector has more elements than the value vector, then we have a 432 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 433 // elements we want. 434 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 435 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 436 "Cannot narrow, it would be a lossy transformation"); 437 return DAG.getNode( 438 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 439 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 440 } 441 442 // Vector/Vector bitcast. 443 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 444 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 445 446 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 447 "Cannot handle this kind of promotion"); 448 // Promoted vector extract 449 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 450 451 } 452 453 // Trivial bitcast if the types are the same size and the destination 454 // vector type is legal. 455 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 456 TLI.isTypeLegal(ValueVT)) 457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 458 459 if (ValueVT.getVectorNumElements() != 1) { 460 // Certain ABIs require that vectors are passed as integers. For vectors 461 // are the same size, this is an obvious bitcast. 462 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 463 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 464 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 465 // Bitcast Val back the original type and extract the corresponding 466 // vector we want. 467 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 468 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 469 ValueVT.getVectorElementType(), Elts); 470 Val = DAG.getBitcast(WiderVecType, Val); 471 return DAG.getNode( 472 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 473 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 474 } 475 476 diagnosePossiblyInvalidConstraint( 477 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 478 return DAG.getUNDEF(ValueVT); 479 } 480 481 // Handle cases such as i8 -> <1 x i1> 482 EVT ValueSVT = ValueVT.getVectorElementType(); 483 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 484 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 485 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 486 487 return DAG.getBuildVector(ValueVT, DL, Val); 488 } 489 490 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 491 SDValue Val, SDValue *Parts, unsigned NumParts, 492 MVT PartVT, const Value *V, 493 Optional<CallingConv::ID> CallConv); 494 495 /// getCopyToParts - Create a series of nodes that contain the specified value 496 /// split into legal parts. If the parts contain more bits than Val, then, for 497 /// integers, ExtendKind can be used to specify how to generate the extra bits. 498 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 499 SDValue *Parts, unsigned NumParts, MVT PartVT, 500 const Value *V, 501 Optional<CallingConv::ID> CallConv = None, 502 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 503 EVT ValueVT = Val.getValueType(); 504 505 // Handle the vector case separately. 506 if (ValueVT.isVector()) 507 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 508 CallConv); 509 510 unsigned PartBits = PartVT.getSizeInBits(); 511 unsigned OrigNumParts = NumParts; 512 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 513 "Copying to an illegal type!"); 514 515 if (NumParts == 0) 516 return; 517 518 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 519 EVT PartEVT = PartVT; 520 if (PartEVT == ValueVT) { 521 assert(NumParts == 1 && "No-op copy with multiple parts!"); 522 Parts[0] = Val; 523 return; 524 } 525 526 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 527 // If the parts cover more bits than the value has, promote the value. 528 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 529 assert(NumParts == 1 && "Do not know what to promote to!"); 530 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 531 } else { 532 if (ValueVT.isFloatingPoint()) { 533 // FP values need to be bitcast, then extended if they are being put 534 // into a larger container. 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 536 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 537 } 538 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 539 ValueVT.isInteger() && 540 "Unknown mismatch!"); 541 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 542 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 543 if (PartVT == MVT::x86mmx) 544 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 545 } 546 } else if (PartBits == ValueVT.getSizeInBits()) { 547 // Different types of the same size. 548 assert(NumParts == 1 && PartEVT != ValueVT); 549 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 550 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 551 // If the parts cover less bits than value has, truncate the value. 552 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 553 ValueVT.isInteger() && 554 "Unknown mismatch!"); 555 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 556 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 557 if (PartVT == MVT::x86mmx) 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } 560 561 // The value may have changed - recompute ValueVT. 562 ValueVT = Val.getValueType(); 563 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 564 "Failed to tile the value with PartVT!"); 565 566 if (NumParts == 1) { 567 if (PartEVT != ValueVT) { 568 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 569 "scalar-to-vector conversion failed"); 570 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 571 } 572 573 Parts[0] = Val; 574 return; 575 } 576 577 // Expand the value into multiple parts. 578 if (NumParts & (NumParts - 1)) { 579 // The number of parts is not a power of 2. Split off and copy the tail. 580 assert(PartVT.isInteger() && ValueVT.isInteger() && 581 "Do not know what to expand to!"); 582 unsigned RoundParts = 1 << Log2_32(NumParts); 583 unsigned RoundBits = RoundParts * PartBits; 584 unsigned OddParts = NumParts - RoundParts; 585 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 586 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 587 588 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 589 CallConv); 590 591 if (DAG.getDataLayout().isBigEndian()) 592 // The odd parts were reversed by getCopyToParts - unreverse them. 593 std::reverse(Parts + RoundParts, Parts + NumParts); 594 595 NumParts = RoundParts; 596 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 597 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 598 } 599 600 // The number of parts is a power of 2. Repeatedly bisect the value using 601 // EXTRACT_ELEMENT. 602 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 603 EVT::getIntegerVT(*DAG.getContext(), 604 ValueVT.getSizeInBits()), 605 Val); 606 607 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 608 for (unsigned i = 0; i < NumParts; i += StepSize) { 609 unsigned ThisBits = StepSize * PartBits / 2; 610 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 611 SDValue &Part0 = Parts[i]; 612 SDValue &Part1 = Parts[i+StepSize/2]; 613 614 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 615 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 616 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 617 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 618 619 if (ThisBits == PartBits && ThisVT != PartVT) { 620 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 621 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 622 } 623 } 624 } 625 626 if (DAG.getDataLayout().isBigEndian()) 627 std::reverse(Parts, Parts + OrigNumParts); 628 } 629 630 static SDValue widenVectorToPartType(SelectionDAG &DAG, 631 SDValue Val, const SDLoc &DL, EVT PartVT) { 632 if (!PartVT.isVector()) 633 return SDValue(); 634 635 EVT ValueVT = Val.getValueType(); 636 unsigned PartNumElts = PartVT.getVectorNumElements(); 637 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 638 if (PartNumElts > ValueNumElts && 639 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 640 EVT ElementVT = PartVT.getVectorElementType(); 641 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 642 // undef elements. 643 SmallVector<SDValue, 16> Ops; 644 DAG.ExtractVectorElements(Val, Ops); 645 SDValue EltUndef = DAG.getUNDEF(ElementVT); 646 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 647 Ops.push_back(EltUndef); 648 649 // FIXME: Use CONCAT for 2x -> 4x. 650 return DAG.getBuildVector(PartVT, DL, Ops); 651 } 652 653 return SDValue(); 654 } 655 656 /// getCopyToPartsVector - Create a series of nodes that contain the specified 657 /// value split into legal parts. 658 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 659 SDValue Val, SDValue *Parts, unsigned NumParts, 660 MVT PartVT, const Value *V, 661 Optional<CallingConv::ID> CallConv) { 662 EVT ValueVT = Val.getValueType(); 663 assert(ValueVT.isVector() && "Not a vector"); 664 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 665 const bool IsABIRegCopy = CallConv.hasValue(); 666 667 if (NumParts == 1) { 668 EVT PartEVT = PartVT; 669 if (PartEVT == ValueVT) { 670 // Nothing to do. 671 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 672 // Bitconvert vector->vector case. 673 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 674 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 675 Val = Widened; 676 } else if (PartVT.isVector() && 677 PartEVT.getVectorElementType().bitsGE( 678 ValueVT.getVectorElementType()) && 679 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 680 681 // Promoted vector extract 682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 683 } else { 684 if (ValueVT.getVectorNumElements() == 1) { 685 Val = DAG.getNode( 686 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 687 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 688 } else { 689 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 690 "lossy conversion of vector to scalar type"); 691 EVT IntermediateType = 692 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 693 Val = DAG.getBitcast(IntermediateType, Val); 694 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 695 } 696 } 697 698 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 699 Parts[0] = Val; 700 return; 701 } 702 703 // Handle a multi-element vector. 704 EVT IntermediateVT; 705 MVT RegisterVT; 706 unsigned NumIntermediates; 707 unsigned NumRegs; 708 if (IsABIRegCopy) { 709 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 710 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 711 NumIntermediates, RegisterVT); 712 } else { 713 NumRegs = 714 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 715 NumIntermediates, RegisterVT); 716 } 717 718 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 719 NumParts = NumRegs; // Silence a compiler warning. 720 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 721 722 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 723 IntermediateVT.getVectorNumElements() : 1; 724 725 // Convert the vector to the appropiate type if necessary. 726 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 727 728 EVT BuiltVectorTy = EVT::getVectorVT( 729 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 730 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 731 if (ValueVT != BuiltVectorTy) { 732 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 733 Val = Widened; 734 735 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 736 } 737 738 // Split the vector into intermediate operands. 739 SmallVector<SDValue, 8> Ops(NumIntermediates); 740 for (unsigned i = 0; i != NumIntermediates; ++i) { 741 if (IntermediateVT.isVector()) { 742 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 743 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 744 } else { 745 Ops[i] = DAG.getNode( 746 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 747 DAG.getConstant(i, DL, IdxVT)); 748 } 749 } 750 751 // Split the intermediate operands into legal parts. 752 if (NumParts == NumIntermediates) { 753 // If the register was not expanded, promote or copy the value, 754 // as appropriate. 755 for (unsigned i = 0; i != NumParts; ++i) 756 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 757 } else if (NumParts > 0) { 758 // If the intermediate type was expanded, split each the value into 759 // legal parts. 760 assert(NumIntermediates != 0 && "division by zero"); 761 assert(NumParts % NumIntermediates == 0 && 762 "Must expand into a divisible number of parts!"); 763 unsigned Factor = NumParts / NumIntermediates; 764 for (unsigned i = 0; i != NumIntermediates; ++i) 765 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 766 CallConv); 767 } 768 } 769 770 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 771 EVT valuevt, Optional<CallingConv::ID> CC) 772 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 773 RegCount(1, regs.size()), CallConv(CC) {} 774 775 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 776 const DataLayout &DL, unsigned Reg, Type *Ty, 777 Optional<CallingConv::ID> CC) { 778 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 779 780 CallConv = CC; 781 782 for (EVT ValueVT : ValueVTs) { 783 unsigned NumRegs = 784 isABIMangled() 785 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 786 : TLI.getNumRegisters(Context, ValueVT); 787 MVT RegisterVT = 788 isABIMangled() 789 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 790 : TLI.getRegisterType(Context, ValueVT); 791 for (unsigned i = 0; i != NumRegs; ++i) 792 Regs.push_back(Reg + i); 793 RegVTs.push_back(RegisterVT); 794 RegCount.push_back(NumRegs); 795 Reg += NumRegs; 796 } 797 } 798 799 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 800 FunctionLoweringInfo &FuncInfo, 801 const SDLoc &dl, SDValue &Chain, 802 SDValue *Flag, const Value *V) const { 803 // A Value with type {} or [0 x %t] needs no registers. 804 if (ValueVTs.empty()) 805 return SDValue(); 806 807 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 808 809 // Assemble the legal parts into the final values. 810 SmallVector<SDValue, 4> Values(ValueVTs.size()); 811 SmallVector<SDValue, 8> Parts; 812 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 813 // Copy the legal parts from the registers. 814 EVT ValueVT = ValueVTs[Value]; 815 unsigned NumRegs = RegCount[Value]; 816 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 817 *DAG.getContext(), 818 CallConv.getValue(), RegVTs[Value]) 819 : RegVTs[Value]; 820 821 Parts.resize(NumRegs); 822 for (unsigned i = 0; i != NumRegs; ++i) { 823 SDValue P; 824 if (!Flag) { 825 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 826 } else { 827 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 828 *Flag = P.getValue(2); 829 } 830 831 Chain = P.getValue(1); 832 Parts[i] = P; 833 834 // If the source register was virtual and if we know something about it, 835 // add an assert node. 836 if (!Register::isVirtualRegister(Regs[Part + i]) || 837 !RegisterVT.isInteger()) 838 continue; 839 840 const FunctionLoweringInfo::LiveOutInfo *LOI = 841 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 842 if (!LOI) 843 continue; 844 845 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 846 unsigned NumSignBits = LOI->NumSignBits; 847 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 848 849 if (NumZeroBits == RegSize) { 850 // The current value is a zero. 851 // Explicitly express that as it would be easier for 852 // optimizations to kick in. 853 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 854 continue; 855 } 856 857 // FIXME: We capture more information than the dag can represent. For 858 // now, just use the tightest assertzext/assertsext possible. 859 bool isSExt; 860 EVT FromVT(MVT::Other); 861 if (NumZeroBits) { 862 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 863 isSExt = false; 864 } else if (NumSignBits > 1) { 865 FromVT = 866 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 867 isSExt = true; 868 } else { 869 continue; 870 } 871 // Add an assertion node. 872 assert(FromVT != MVT::Other); 873 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 874 RegisterVT, P, DAG.getValueType(FromVT)); 875 } 876 877 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 878 RegisterVT, ValueVT, V, CallConv); 879 Part += NumRegs; 880 Parts.clear(); 881 } 882 883 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 884 } 885 886 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 887 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 888 const Value *V, 889 ISD::NodeType PreferredExtendType) const { 890 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 891 ISD::NodeType ExtendKind = PreferredExtendType; 892 893 // Get the list of the values's legal parts. 894 unsigned NumRegs = Regs.size(); 895 SmallVector<SDValue, 8> Parts(NumRegs); 896 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 897 unsigned NumParts = RegCount[Value]; 898 899 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 900 *DAG.getContext(), 901 CallConv.getValue(), RegVTs[Value]) 902 : RegVTs[Value]; 903 904 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 905 ExtendKind = ISD::ZERO_EXTEND; 906 907 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 908 NumParts, RegisterVT, V, CallConv, ExtendKind); 909 Part += NumParts; 910 } 911 912 // Copy the parts into the registers. 913 SmallVector<SDValue, 8> Chains(NumRegs); 914 for (unsigned i = 0; i != NumRegs; ++i) { 915 SDValue Part; 916 if (!Flag) { 917 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 918 } else { 919 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 920 *Flag = Part.getValue(1); 921 } 922 923 Chains[i] = Part.getValue(0); 924 } 925 926 if (NumRegs == 1 || Flag) 927 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 928 // flagged to it. That is the CopyToReg nodes and the user are considered 929 // a single scheduling unit. If we create a TokenFactor and return it as 930 // chain, then the TokenFactor is both a predecessor (operand) of the 931 // user as well as a successor (the TF operands are flagged to the user). 932 // c1, f1 = CopyToReg 933 // c2, f2 = CopyToReg 934 // c3 = TokenFactor c1, c2 935 // ... 936 // = op c3, ..., f2 937 Chain = Chains[NumRegs-1]; 938 else 939 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 940 } 941 942 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 943 unsigned MatchingIdx, const SDLoc &dl, 944 SelectionDAG &DAG, 945 std::vector<SDValue> &Ops) const { 946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 947 948 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 949 if (HasMatching) 950 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 951 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 952 // Put the register class of the virtual registers in the flag word. That 953 // way, later passes can recompute register class constraints for inline 954 // assembly as well as normal instructions. 955 // Don't do this for tied operands that can use the regclass information 956 // from the def. 957 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 958 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 959 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 960 } 961 962 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 963 Ops.push_back(Res); 964 965 if (Code == InlineAsm::Kind_Clobber) { 966 // Clobbers should always have a 1:1 mapping with registers, and may 967 // reference registers that have illegal (e.g. vector) types. Hence, we 968 // shouldn't try to apply any sort of splitting logic to them. 969 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 970 "No 1:1 mapping from clobbers to regs?"); 971 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 972 (void)SP; 973 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 974 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 975 assert( 976 (Regs[I] != SP || 977 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 978 "If we clobbered the stack pointer, MFI should know about it."); 979 } 980 return; 981 } 982 983 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 984 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 985 MVT RegisterVT = RegVTs[Value]; 986 for (unsigned i = 0; i != NumRegs; ++i) { 987 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 988 unsigned TheReg = Regs[Reg++]; 989 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 990 } 991 } 992 } 993 994 SmallVector<std::pair<unsigned, unsigned>, 4> 995 RegsForValue::getRegsAndSizes() const { 996 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 997 unsigned I = 0; 998 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 999 unsigned RegCount = std::get<0>(CountAndVT); 1000 MVT RegisterVT = std::get<1>(CountAndVT); 1001 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1002 for (unsigned E = I + RegCount; I != E; ++I) 1003 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1004 } 1005 return OutVec; 1006 } 1007 1008 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1009 const TargetLibraryInfo *li) { 1010 AA = aa; 1011 GFI = gfi; 1012 LibInfo = li; 1013 DL = &DAG.getDataLayout(); 1014 Context = DAG.getContext(); 1015 LPadToCallSiteMap.clear(); 1016 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1017 } 1018 1019 void SelectionDAGBuilder::clear() { 1020 NodeMap.clear(); 1021 UnusedArgNodeMap.clear(); 1022 PendingLoads.clear(); 1023 PendingExports.clear(); 1024 CurInst = nullptr; 1025 HasTailCall = false; 1026 SDNodeOrder = LowestSDNodeOrder; 1027 StatepointLowering.clear(); 1028 } 1029 1030 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1031 DanglingDebugInfoMap.clear(); 1032 } 1033 1034 SDValue SelectionDAGBuilder::getRoot() { 1035 if (PendingLoads.empty()) 1036 return DAG.getRoot(); 1037 1038 if (PendingLoads.size() == 1) { 1039 SDValue Root = PendingLoads[0]; 1040 DAG.setRoot(Root); 1041 PendingLoads.clear(); 1042 return Root; 1043 } 1044 1045 // Otherwise, we have to make a token factor node. 1046 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1047 PendingLoads.clear(); 1048 DAG.setRoot(Root); 1049 return Root; 1050 } 1051 1052 SDValue SelectionDAGBuilder::getControlRoot() { 1053 SDValue Root = DAG.getRoot(); 1054 1055 if (PendingExports.empty()) 1056 return Root; 1057 1058 // Turn all of the CopyToReg chains into one factored node. 1059 if (Root.getOpcode() != ISD::EntryToken) { 1060 unsigned i = 0, e = PendingExports.size(); 1061 for (; i != e; ++i) { 1062 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1063 if (PendingExports[i].getNode()->getOperand(0) == Root) 1064 break; // Don't add the root if we already indirectly depend on it. 1065 } 1066 1067 if (i == e) 1068 PendingExports.push_back(Root); 1069 } 1070 1071 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1072 PendingExports); 1073 PendingExports.clear(); 1074 DAG.setRoot(Root); 1075 return Root; 1076 } 1077 1078 void SelectionDAGBuilder::visit(const Instruction &I) { 1079 // Set up outgoing PHI node register values before emitting the terminator. 1080 if (I.isTerminator()) { 1081 HandlePHINodesInSuccessorBlocks(I.getParent()); 1082 } 1083 1084 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1085 if (!isa<DbgInfoIntrinsic>(I)) 1086 ++SDNodeOrder; 1087 1088 CurInst = &I; 1089 1090 visit(I.getOpcode(), I); 1091 1092 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1093 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1094 // maps to this instruction. 1095 // TODO: We could handle all flags (nsw, etc) here. 1096 // TODO: If an IR instruction maps to >1 node, only the final node will have 1097 // flags set. 1098 if (SDNode *Node = getNodeForIRValue(&I)) { 1099 SDNodeFlags IncomingFlags; 1100 IncomingFlags.copyFMF(*FPMO); 1101 if (!Node->getFlags().isDefined()) 1102 Node->setFlags(IncomingFlags); 1103 else 1104 Node->intersectFlagsWith(IncomingFlags); 1105 } 1106 } 1107 1108 if (!I.isTerminator() && !HasTailCall && 1109 !isStatepoint(&I)) // statepoints handle their exports internally 1110 CopyToExportRegsIfNeeded(&I); 1111 1112 CurInst = nullptr; 1113 } 1114 1115 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1116 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1117 } 1118 1119 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1120 // Note: this doesn't use InstVisitor, because it has to work with 1121 // ConstantExpr's in addition to instructions. 1122 switch (Opcode) { 1123 default: llvm_unreachable("Unknown instruction type encountered!"); 1124 // Build the switch statement using the Instruction.def file. 1125 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1126 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1127 #include "llvm/IR/Instruction.def" 1128 } 1129 } 1130 1131 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1132 const DIExpression *Expr) { 1133 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1134 const DbgValueInst *DI = DDI.getDI(); 1135 DIVariable *DanglingVariable = DI->getVariable(); 1136 DIExpression *DanglingExpr = DI->getExpression(); 1137 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1138 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1139 return true; 1140 } 1141 return false; 1142 }; 1143 1144 for (auto &DDIMI : DanglingDebugInfoMap) { 1145 DanglingDebugInfoVector &DDIV = DDIMI.second; 1146 1147 // If debug info is to be dropped, run it through final checks to see 1148 // whether it can be salvaged. 1149 for (auto &DDI : DDIV) 1150 if (isMatchingDbgValue(DDI)) 1151 salvageUnresolvedDbgValue(DDI); 1152 1153 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1154 } 1155 } 1156 1157 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1158 // generate the debug data structures now that we've seen its definition. 1159 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1160 SDValue Val) { 1161 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1162 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1163 return; 1164 1165 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1166 for (auto &DDI : DDIV) { 1167 const DbgValueInst *DI = DDI.getDI(); 1168 assert(DI && "Ill-formed DanglingDebugInfo"); 1169 DebugLoc dl = DDI.getdl(); 1170 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1171 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1172 DILocalVariable *Variable = DI->getVariable(); 1173 DIExpression *Expr = DI->getExpression(); 1174 assert(Variable->isValidLocationForIntrinsic(dl) && 1175 "Expected inlined-at fields to agree"); 1176 SDDbgValue *SDV; 1177 if (Val.getNode()) { 1178 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1179 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1180 // we couldn't resolve it directly when examining the DbgValue intrinsic 1181 // in the first place we should not be more successful here). Unless we 1182 // have some test case that prove this to be correct we should avoid 1183 // calling EmitFuncArgumentDbgValue here. 1184 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1185 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1186 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1187 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1188 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1189 // inserted after the definition of Val when emitting the instructions 1190 // after ISel. An alternative could be to teach 1191 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1192 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1193 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1194 << ValSDNodeOrder << "\n"); 1195 SDV = getDbgValue(Val, Variable, Expr, dl, 1196 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1197 DAG.AddDbgValue(SDV, Val.getNode(), false); 1198 } else 1199 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1200 << "in EmitFuncArgumentDbgValue\n"); 1201 } else { 1202 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1203 auto Undef = 1204 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1205 auto SDV = 1206 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1207 DAG.AddDbgValue(SDV, nullptr, false); 1208 } 1209 } 1210 DDIV.clear(); 1211 } 1212 1213 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1214 Value *V = DDI.getDI()->getValue(); 1215 DILocalVariable *Var = DDI.getDI()->getVariable(); 1216 DIExpression *Expr = DDI.getDI()->getExpression(); 1217 DebugLoc DL = DDI.getdl(); 1218 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1219 unsigned SDOrder = DDI.getSDNodeOrder(); 1220 1221 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1222 // that DW_OP_stack_value is desired. 1223 assert(isa<DbgValueInst>(DDI.getDI())); 1224 bool StackValue = true; 1225 1226 // Can this Value can be encoded without any further work? 1227 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1228 return; 1229 1230 // Attempt to salvage back through as many instructions as possible. Bail if 1231 // a non-instruction is seen, such as a constant expression or global 1232 // variable. FIXME: Further work could recover those too. 1233 while (isa<Instruction>(V)) { 1234 Instruction &VAsInst = *cast<Instruction>(V); 1235 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1236 1237 // If we cannot salvage any further, and haven't yet found a suitable debug 1238 // expression, bail out. 1239 if (!NewExpr) 1240 break; 1241 1242 // New value and expr now represent this debuginfo. 1243 V = VAsInst.getOperand(0); 1244 Expr = NewExpr; 1245 1246 // Some kind of simplification occurred: check whether the operand of the 1247 // salvaged debug expression can be encoded in this DAG. 1248 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1249 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1250 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1251 return; 1252 } 1253 } 1254 1255 // This was the final opportunity to salvage this debug information, and it 1256 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1257 // any earlier variable location. 1258 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1259 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1260 DAG.AddDbgValue(SDV, nullptr, false); 1261 1262 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1263 << "\n"); 1264 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1265 << "\n"); 1266 } 1267 1268 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1269 DIExpression *Expr, DebugLoc dl, 1270 DebugLoc InstDL, unsigned Order) { 1271 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1272 SDDbgValue *SDV; 1273 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1274 isa<ConstantPointerNull>(V)) { 1275 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1276 DAG.AddDbgValue(SDV, nullptr, false); 1277 return true; 1278 } 1279 1280 // If the Value is a frame index, we can create a FrameIndex debug value 1281 // without relying on the DAG at all. 1282 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1283 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1284 if (SI != FuncInfo.StaticAllocaMap.end()) { 1285 auto SDV = 1286 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1287 /*IsIndirect*/ false, dl, SDNodeOrder); 1288 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1289 // is still available even if the SDNode gets optimized out. 1290 DAG.AddDbgValue(SDV, nullptr, false); 1291 return true; 1292 } 1293 } 1294 1295 // Do not use getValue() in here; we don't want to generate code at 1296 // this point if it hasn't been done yet. 1297 SDValue N = NodeMap[V]; 1298 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1299 N = UnusedArgNodeMap[V]; 1300 if (N.getNode()) { 1301 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1302 return true; 1303 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1304 DAG.AddDbgValue(SDV, N.getNode(), false); 1305 return true; 1306 } 1307 1308 // Special rules apply for the first dbg.values of parameter variables in a 1309 // function. Identify them by the fact they reference Argument Values, that 1310 // they're parameters, and they are parameters of the current function. We 1311 // need to let them dangle until they get an SDNode. 1312 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1313 !InstDL.getInlinedAt(); 1314 if (!IsParamOfFunc) { 1315 // The value is not used in this block yet (or it would have an SDNode). 1316 // We still want the value to appear for the user if possible -- if it has 1317 // an associated VReg, we can refer to that instead. 1318 auto VMI = FuncInfo.ValueMap.find(V); 1319 if (VMI != FuncInfo.ValueMap.end()) { 1320 unsigned Reg = VMI->second; 1321 // If this is a PHI node, it may be split up into several MI PHI nodes 1322 // (in FunctionLoweringInfo::set). 1323 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1324 V->getType(), None); 1325 if (RFV.occupiesMultipleRegs()) { 1326 unsigned Offset = 0; 1327 unsigned BitsToDescribe = 0; 1328 if (auto VarSize = Var->getSizeInBits()) 1329 BitsToDescribe = *VarSize; 1330 if (auto Fragment = Expr->getFragmentInfo()) 1331 BitsToDescribe = Fragment->SizeInBits; 1332 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1333 unsigned RegisterSize = RegAndSize.second; 1334 // Bail out if all bits are described already. 1335 if (Offset >= BitsToDescribe) 1336 break; 1337 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1338 ? BitsToDescribe - Offset 1339 : RegisterSize; 1340 auto FragmentExpr = DIExpression::createFragmentExpression( 1341 Expr, Offset, FragmentSize); 1342 if (!FragmentExpr) 1343 continue; 1344 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1345 false, dl, SDNodeOrder); 1346 DAG.AddDbgValue(SDV, nullptr, false); 1347 Offset += RegisterSize; 1348 } 1349 } else { 1350 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1351 DAG.AddDbgValue(SDV, nullptr, false); 1352 } 1353 return true; 1354 } 1355 } 1356 1357 return false; 1358 } 1359 1360 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1361 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1362 for (auto &Pair : DanglingDebugInfoMap) 1363 for (auto &DDI : Pair.second) 1364 salvageUnresolvedDbgValue(DDI); 1365 clearDanglingDebugInfo(); 1366 } 1367 1368 /// getCopyFromRegs - If there was virtual register allocated for the value V 1369 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1370 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1371 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1372 SDValue Result; 1373 1374 if (It != FuncInfo.ValueMap.end()) { 1375 unsigned InReg = It->second; 1376 1377 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1378 DAG.getDataLayout(), InReg, Ty, 1379 None); // This is not an ABI copy. 1380 SDValue Chain = DAG.getEntryNode(); 1381 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1382 V); 1383 resolveDanglingDebugInfo(V, Result); 1384 } 1385 1386 return Result; 1387 } 1388 1389 /// getValue - Return an SDValue for the given Value. 1390 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1391 // If we already have an SDValue for this value, use it. It's important 1392 // to do this first, so that we don't create a CopyFromReg if we already 1393 // have a regular SDValue. 1394 SDValue &N = NodeMap[V]; 1395 if (N.getNode()) return N; 1396 1397 // If there's a virtual register allocated and initialized for this 1398 // value, use it. 1399 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1400 return copyFromReg; 1401 1402 // Otherwise create a new SDValue and remember it. 1403 SDValue Val = getValueImpl(V); 1404 NodeMap[V] = Val; 1405 resolveDanglingDebugInfo(V, Val); 1406 return Val; 1407 } 1408 1409 // Return true if SDValue exists for the given Value 1410 bool SelectionDAGBuilder::findValue(const Value *V) const { 1411 return (NodeMap.find(V) != NodeMap.end()) || 1412 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1413 } 1414 1415 /// getNonRegisterValue - Return an SDValue for the given Value, but 1416 /// don't look in FuncInfo.ValueMap for a virtual register. 1417 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1418 // If we already have an SDValue for this value, use it. 1419 SDValue &N = NodeMap[V]; 1420 if (N.getNode()) { 1421 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1422 // Remove the debug location from the node as the node is about to be used 1423 // in a location which may differ from the original debug location. This 1424 // is relevant to Constant and ConstantFP nodes because they can appear 1425 // as constant expressions inside PHI nodes. 1426 N->setDebugLoc(DebugLoc()); 1427 } 1428 return N; 1429 } 1430 1431 // Otherwise create a new SDValue and remember it. 1432 SDValue Val = getValueImpl(V); 1433 NodeMap[V] = Val; 1434 resolveDanglingDebugInfo(V, Val); 1435 return Val; 1436 } 1437 1438 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1439 /// Create an SDValue for the given value. 1440 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1441 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1442 1443 if (const Constant *C = dyn_cast<Constant>(V)) { 1444 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1445 1446 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1447 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1448 1449 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1450 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1451 1452 if (isa<ConstantPointerNull>(C)) { 1453 unsigned AS = V->getType()->getPointerAddressSpace(); 1454 return DAG.getConstant(0, getCurSDLoc(), 1455 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1456 } 1457 1458 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1459 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1460 1461 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1462 return DAG.getUNDEF(VT); 1463 1464 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1465 visit(CE->getOpcode(), *CE); 1466 SDValue N1 = NodeMap[V]; 1467 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1468 return N1; 1469 } 1470 1471 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1472 SmallVector<SDValue, 4> Constants; 1473 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1474 OI != OE; ++OI) { 1475 SDNode *Val = getValue(*OI).getNode(); 1476 // If the operand is an empty aggregate, there are no values. 1477 if (!Val) continue; 1478 // Add each leaf value from the operand to the Constants list 1479 // to form a flattened list of all the values. 1480 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1481 Constants.push_back(SDValue(Val, i)); 1482 } 1483 1484 return DAG.getMergeValues(Constants, getCurSDLoc()); 1485 } 1486 1487 if (const ConstantDataSequential *CDS = 1488 dyn_cast<ConstantDataSequential>(C)) { 1489 SmallVector<SDValue, 4> Ops; 1490 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1491 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1492 // Add each leaf value from the operand to the Constants list 1493 // to form a flattened list of all the values. 1494 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1495 Ops.push_back(SDValue(Val, i)); 1496 } 1497 1498 if (isa<ArrayType>(CDS->getType())) 1499 return DAG.getMergeValues(Ops, getCurSDLoc()); 1500 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1501 } 1502 1503 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1504 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1505 "Unknown struct or array constant!"); 1506 1507 SmallVector<EVT, 4> ValueVTs; 1508 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1509 unsigned NumElts = ValueVTs.size(); 1510 if (NumElts == 0) 1511 return SDValue(); // empty struct 1512 SmallVector<SDValue, 4> Constants(NumElts); 1513 for (unsigned i = 0; i != NumElts; ++i) { 1514 EVT EltVT = ValueVTs[i]; 1515 if (isa<UndefValue>(C)) 1516 Constants[i] = DAG.getUNDEF(EltVT); 1517 else if (EltVT.isFloatingPoint()) 1518 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1519 else 1520 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1521 } 1522 1523 return DAG.getMergeValues(Constants, getCurSDLoc()); 1524 } 1525 1526 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1527 return DAG.getBlockAddress(BA, VT); 1528 1529 VectorType *VecTy = cast<VectorType>(V->getType()); 1530 unsigned NumElements = VecTy->getNumElements(); 1531 1532 // Now that we know the number and type of the elements, get that number of 1533 // elements into the Ops array based on what kind of constant it is. 1534 SmallVector<SDValue, 16> Ops; 1535 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1536 for (unsigned i = 0; i != NumElements; ++i) 1537 Ops.push_back(getValue(CV->getOperand(i))); 1538 } else { 1539 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1540 EVT EltVT = 1541 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1542 1543 SDValue Op; 1544 if (EltVT.isFloatingPoint()) 1545 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1546 else 1547 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1548 Ops.assign(NumElements, Op); 1549 } 1550 1551 // Create a BUILD_VECTOR node. 1552 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1553 } 1554 1555 // If this is a static alloca, generate it as the frameindex instead of 1556 // computation. 1557 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1558 DenseMap<const AllocaInst*, int>::iterator SI = 1559 FuncInfo.StaticAllocaMap.find(AI); 1560 if (SI != FuncInfo.StaticAllocaMap.end()) 1561 return DAG.getFrameIndex(SI->second, 1562 TLI.getFrameIndexTy(DAG.getDataLayout())); 1563 } 1564 1565 // If this is an instruction which fast-isel has deferred, select it now. 1566 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1567 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1568 1569 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1570 Inst->getType(), getABIRegCopyCC(V)); 1571 SDValue Chain = DAG.getEntryNode(); 1572 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1573 } 1574 1575 llvm_unreachable("Can't get register for value!"); 1576 } 1577 1578 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1579 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1580 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1581 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1582 bool IsSEH = isAsynchronousEHPersonality(Pers); 1583 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1584 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1585 if (!IsSEH) 1586 CatchPadMBB->setIsEHScopeEntry(); 1587 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1588 if (IsMSVCCXX || IsCoreCLR) 1589 CatchPadMBB->setIsEHFuncletEntry(); 1590 // Wasm does not need catchpads anymore 1591 if (!IsWasmCXX) 1592 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1593 getControlRoot())); 1594 } 1595 1596 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1597 // Update machine-CFG edge. 1598 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1599 FuncInfo.MBB->addSuccessor(TargetMBB); 1600 1601 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1602 bool IsSEH = isAsynchronousEHPersonality(Pers); 1603 if (IsSEH) { 1604 // If this is not a fall-through branch or optimizations are switched off, 1605 // emit the branch. 1606 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1607 TM.getOptLevel() == CodeGenOpt::None) 1608 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1609 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1610 return; 1611 } 1612 1613 // Figure out the funclet membership for the catchret's successor. 1614 // This will be used by the FuncletLayout pass to determine how to order the 1615 // BB's. 1616 // A 'catchret' returns to the outer scope's color. 1617 Value *ParentPad = I.getCatchSwitchParentPad(); 1618 const BasicBlock *SuccessorColor; 1619 if (isa<ConstantTokenNone>(ParentPad)) 1620 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1621 else 1622 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1623 assert(SuccessorColor && "No parent funclet for catchret!"); 1624 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1625 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1626 1627 // Create the terminator node. 1628 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1629 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1630 DAG.getBasicBlock(SuccessorColorMBB)); 1631 DAG.setRoot(Ret); 1632 } 1633 1634 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1635 // Don't emit any special code for the cleanuppad instruction. It just marks 1636 // the start of an EH scope/funclet. 1637 FuncInfo.MBB->setIsEHScopeEntry(); 1638 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1639 if (Pers != EHPersonality::Wasm_CXX) { 1640 FuncInfo.MBB->setIsEHFuncletEntry(); 1641 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1642 } 1643 } 1644 1645 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1646 // the control flow always stops at the single catch pad, as it does for a 1647 // cleanup pad. In case the exception caught is not of the types the catch pad 1648 // catches, it will be rethrown by a rethrow. 1649 static void findWasmUnwindDestinations( 1650 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1651 BranchProbability Prob, 1652 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1653 &UnwindDests) { 1654 while (EHPadBB) { 1655 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1656 if (isa<CleanupPadInst>(Pad)) { 1657 // Stop on cleanup pads. 1658 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1659 UnwindDests.back().first->setIsEHScopeEntry(); 1660 break; 1661 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1662 // Add the catchpad handlers to the possible destinations. We don't 1663 // continue to the unwind destination of the catchswitch for wasm. 1664 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1665 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1666 UnwindDests.back().first->setIsEHScopeEntry(); 1667 } 1668 break; 1669 } else { 1670 continue; 1671 } 1672 } 1673 } 1674 1675 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1676 /// many places it could ultimately go. In the IR, we have a single unwind 1677 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1678 /// This function skips over imaginary basic blocks that hold catchswitch 1679 /// instructions, and finds all the "real" machine 1680 /// basic block destinations. As those destinations may not be successors of 1681 /// EHPadBB, here we also calculate the edge probability to those destinations. 1682 /// The passed-in Prob is the edge probability to EHPadBB. 1683 static void findUnwindDestinations( 1684 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1685 BranchProbability Prob, 1686 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1687 &UnwindDests) { 1688 EHPersonality Personality = 1689 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1690 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1691 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1692 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1693 bool IsSEH = isAsynchronousEHPersonality(Personality); 1694 1695 if (IsWasmCXX) { 1696 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1697 assert(UnwindDests.size() <= 1 && 1698 "There should be at most one unwind destination for wasm"); 1699 return; 1700 } 1701 1702 while (EHPadBB) { 1703 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1704 BasicBlock *NewEHPadBB = nullptr; 1705 if (isa<LandingPadInst>(Pad)) { 1706 // Stop on landingpads. They are not funclets. 1707 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1708 break; 1709 } else if (isa<CleanupPadInst>(Pad)) { 1710 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1711 // personalities. 1712 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1713 UnwindDests.back().first->setIsEHScopeEntry(); 1714 UnwindDests.back().first->setIsEHFuncletEntry(); 1715 break; 1716 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1717 // Add the catchpad handlers to the possible destinations. 1718 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1719 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1720 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1721 if (IsMSVCCXX || IsCoreCLR) 1722 UnwindDests.back().first->setIsEHFuncletEntry(); 1723 if (!IsSEH) 1724 UnwindDests.back().first->setIsEHScopeEntry(); 1725 } 1726 NewEHPadBB = CatchSwitch->getUnwindDest(); 1727 } else { 1728 continue; 1729 } 1730 1731 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1732 if (BPI && NewEHPadBB) 1733 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1734 EHPadBB = NewEHPadBB; 1735 } 1736 } 1737 1738 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1739 // Update successor info. 1740 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1741 auto UnwindDest = I.getUnwindDest(); 1742 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1743 BranchProbability UnwindDestProb = 1744 (BPI && UnwindDest) 1745 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1746 : BranchProbability::getZero(); 1747 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1748 for (auto &UnwindDest : UnwindDests) { 1749 UnwindDest.first->setIsEHPad(); 1750 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1751 } 1752 FuncInfo.MBB->normalizeSuccProbs(); 1753 1754 // Create the terminator node. 1755 SDValue Ret = 1756 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1757 DAG.setRoot(Ret); 1758 } 1759 1760 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1761 report_fatal_error("visitCatchSwitch not yet implemented!"); 1762 } 1763 1764 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1765 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1766 auto &DL = DAG.getDataLayout(); 1767 SDValue Chain = getControlRoot(); 1768 SmallVector<ISD::OutputArg, 8> Outs; 1769 SmallVector<SDValue, 8> OutVals; 1770 1771 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1772 // lower 1773 // 1774 // %val = call <ty> @llvm.experimental.deoptimize() 1775 // ret <ty> %val 1776 // 1777 // differently. 1778 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1779 LowerDeoptimizingReturn(); 1780 return; 1781 } 1782 1783 if (!FuncInfo.CanLowerReturn) { 1784 unsigned DemoteReg = FuncInfo.DemoteRegister; 1785 const Function *F = I.getParent()->getParent(); 1786 1787 // Emit a store of the return value through the virtual register. 1788 // Leave Outs empty so that LowerReturn won't try to load return 1789 // registers the usual way. 1790 SmallVector<EVT, 1> PtrValueVTs; 1791 ComputeValueVTs(TLI, DL, 1792 F->getReturnType()->getPointerTo( 1793 DAG.getDataLayout().getAllocaAddrSpace()), 1794 PtrValueVTs); 1795 1796 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1797 DemoteReg, PtrValueVTs[0]); 1798 SDValue RetOp = getValue(I.getOperand(0)); 1799 1800 SmallVector<EVT, 4> ValueVTs, MemVTs; 1801 SmallVector<uint64_t, 4> Offsets; 1802 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1803 &Offsets); 1804 unsigned NumValues = ValueVTs.size(); 1805 1806 SmallVector<SDValue, 4> Chains(NumValues); 1807 for (unsigned i = 0; i != NumValues; ++i) { 1808 // An aggregate return value cannot wrap around the address space, so 1809 // offsets to its parts don't wrap either. 1810 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1811 1812 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1813 if (MemVTs[i] != ValueVTs[i]) 1814 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1815 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1816 // FIXME: better loc info would be nice. 1817 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1818 } 1819 1820 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1821 MVT::Other, Chains); 1822 } else if (I.getNumOperands() != 0) { 1823 SmallVector<EVT, 4> ValueVTs; 1824 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1825 unsigned NumValues = ValueVTs.size(); 1826 if (NumValues) { 1827 SDValue RetOp = getValue(I.getOperand(0)); 1828 1829 const Function *F = I.getParent()->getParent(); 1830 1831 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1832 I.getOperand(0)->getType(), F->getCallingConv(), 1833 /*IsVarArg*/ false); 1834 1835 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1836 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1837 Attribute::SExt)) 1838 ExtendKind = ISD::SIGN_EXTEND; 1839 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1840 Attribute::ZExt)) 1841 ExtendKind = ISD::ZERO_EXTEND; 1842 1843 LLVMContext &Context = F->getContext(); 1844 bool RetInReg = F->getAttributes().hasAttribute( 1845 AttributeList::ReturnIndex, Attribute::InReg); 1846 1847 for (unsigned j = 0; j != NumValues; ++j) { 1848 EVT VT = ValueVTs[j]; 1849 1850 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1851 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1852 1853 CallingConv::ID CC = F->getCallingConv(); 1854 1855 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1856 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1857 SmallVector<SDValue, 4> Parts(NumParts); 1858 getCopyToParts(DAG, getCurSDLoc(), 1859 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1860 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1861 1862 // 'inreg' on function refers to return value 1863 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1864 if (RetInReg) 1865 Flags.setInReg(); 1866 1867 if (I.getOperand(0)->getType()->isPointerTy()) { 1868 Flags.setPointer(); 1869 Flags.setPointerAddrSpace( 1870 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1871 } 1872 1873 if (NeedsRegBlock) { 1874 Flags.setInConsecutiveRegs(); 1875 if (j == NumValues - 1) 1876 Flags.setInConsecutiveRegsLast(); 1877 } 1878 1879 // Propagate extension type if any 1880 if (ExtendKind == ISD::SIGN_EXTEND) 1881 Flags.setSExt(); 1882 else if (ExtendKind == ISD::ZERO_EXTEND) 1883 Flags.setZExt(); 1884 1885 for (unsigned i = 0; i < NumParts; ++i) { 1886 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1887 VT, /*isfixed=*/true, 0, 0)); 1888 OutVals.push_back(Parts[i]); 1889 } 1890 } 1891 } 1892 } 1893 1894 // Push in swifterror virtual register as the last element of Outs. This makes 1895 // sure swifterror virtual register will be returned in the swifterror 1896 // physical register. 1897 const Function *F = I.getParent()->getParent(); 1898 if (TLI.supportSwiftError() && 1899 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1900 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1901 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1902 Flags.setSwiftError(); 1903 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1904 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1905 true /*isfixed*/, 1 /*origidx*/, 1906 0 /*partOffs*/)); 1907 // Create SDNode for the swifterror virtual register. 1908 OutVals.push_back( 1909 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1910 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1911 EVT(TLI.getPointerTy(DL)))); 1912 } 1913 1914 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1915 CallingConv::ID CallConv = 1916 DAG.getMachineFunction().getFunction().getCallingConv(); 1917 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1918 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1919 1920 // Verify that the target's LowerReturn behaved as expected. 1921 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1922 "LowerReturn didn't return a valid chain!"); 1923 1924 // Update the DAG with the new chain value resulting from return lowering. 1925 DAG.setRoot(Chain); 1926 } 1927 1928 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1929 /// created for it, emit nodes to copy the value into the virtual 1930 /// registers. 1931 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1932 // Skip empty types 1933 if (V->getType()->isEmptyTy()) 1934 return; 1935 1936 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1937 if (VMI != FuncInfo.ValueMap.end()) { 1938 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1939 CopyValueToVirtualRegister(V, VMI->second); 1940 } 1941 } 1942 1943 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1944 /// the current basic block, add it to ValueMap now so that we'll get a 1945 /// CopyTo/FromReg. 1946 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1947 // No need to export constants. 1948 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1949 1950 // Already exported? 1951 if (FuncInfo.isExportedInst(V)) return; 1952 1953 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1954 CopyValueToVirtualRegister(V, Reg); 1955 } 1956 1957 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1958 const BasicBlock *FromBB) { 1959 // The operands of the setcc have to be in this block. We don't know 1960 // how to export them from some other block. 1961 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1962 // Can export from current BB. 1963 if (VI->getParent() == FromBB) 1964 return true; 1965 1966 // Is already exported, noop. 1967 return FuncInfo.isExportedInst(V); 1968 } 1969 1970 // If this is an argument, we can export it if the BB is the entry block or 1971 // if it is already exported. 1972 if (isa<Argument>(V)) { 1973 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1974 return true; 1975 1976 // Otherwise, can only export this if it is already exported. 1977 return FuncInfo.isExportedInst(V); 1978 } 1979 1980 // Otherwise, constants can always be exported. 1981 return true; 1982 } 1983 1984 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1985 BranchProbability 1986 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1987 const MachineBasicBlock *Dst) const { 1988 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1989 const BasicBlock *SrcBB = Src->getBasicBlock(); 1990 const BasicBlock *DstBB = Dst->getBasicBlock(); 1991 if (!BPI) { 1992 // If BPI is not available, set the default probability as 1 / N, where N is 1993 // the number of successors. 1994 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1995 return BranchProbability(1, SuccSize); 1996 } 1997 return BPI->getEdgeProbability(SrcBB, DstBB); 1998 } 1999 2000 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2001 MachineBasicBlock *Dst, 2002 BranchProbability Prob) { 2003 if (!FuncInfo.BPI) 2004 Src->addSuccessorWithoutProb(Dst); 2005 else { 2006 if (Prob.isUnknown()) 2007 Prob = getEdgeProbability(Src, Dst); 2008 Src->addSuccessor(Dst, Prob); 2009 } 2010 } 2011 2012 static bool InBlock(const Value *V, const BasicBlock *BB) { 2013 if (const Instruction *I = dyn_cast<Instruction>(V)) 2014 return I->getParent() == BB; 2015 return true; 2016 } 2017 2018 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2019 /// This function emits a branch and is used at the leaves of an OR or an 2020 /// AND operator tree. 2021 void 2022 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2023 MachineBasicBlock *TBB, 2024 MachineBasicBlock *FBB, 2025 MachineBasicBlock *CurBB, 2026 MachineBasicBlock *SwitchBB, 2027 BranchProbability TProb, 2028 BranchProbability FProb, 2029 bool InvertCond) { 2030 const BasicBlock *BB = CurBB->getBasicBlock(); 2031 2032 // If the leaf of the tree is a comparison, merge the condition into 2033 // the caseblock. 2034 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2035 // The operands of the cmp have to be in this block. We don't know 2036 // how to export them from some other block. If this is the first block 2037 // of the sequence, no exporting is needed. 2038 if (CurBB == SwitchBB || 2039 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2040 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2041 ISD::CondCode Condition; 2042 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2043 ICmpInst::Predicate Pred = 2044 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2045 Condition = getICmpCondCode(Pred); 2046 } else { 2047 const FCmpInst *FC = cast<FCmpInst>(Cond); 2048 FCmpInst::Predicate Pred = 2049 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2050 Condition = getFCmpCondCode(Pred); 2051 if (TM.Options.NoNaNsFPMath) 2052 Condition = getFCmpCodeWithoutNaN(Condition); 2053 } 2054 2055 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2056 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2057 SL->SwitchCases.push_back(CB); 2058 return; 2059 } 2060 } 2061 2062 // Create a CaseBlock record representing this branch. 2063 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2064 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2065 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2066 SL->SwitchCases.push_back(CB); 2067 } 2068 2069 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2070 MachineBasicBlock *TBB, 2071 MachineBasicBlock *FBB, 2072 MachineBasicBlock *CurBB, 2073 MachineBasicBlock *SwitchBB, 2074 Instruction::BinaryOps Opc, 2075 BranchProbability TProb, 2076 BranchProbability FProb, 2077 bool InvertCond) { 2078 // Skip over not part of the tree and remember to invert op and operands at 2079 // next level. 2080 Value *NotCond; 2081 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2082 InBlock(NotCond, CurBB->getBasicBlock())) { 2083 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2084 !InvertCond); 2085 return; 2086 } 2087 2088 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2089 // Compute the effective opcode for Cond, taking into account whether it needs 2090 // to be inverted, e.g. 2091 // and (not (or A, B)), C 2092 // gets lowered as 2093 // and (and (not A, not B), C) 2094 unsigned BOpc = 0; 2095 if (BOp) { 2096 BOpc = BOp->getOpcode(); 2097 if (InvertCond) { 2098 if (BOpc == Instruction::And) 2099 BOpc = Instruction::Or; 2100 else if (BOpc == Instruction::Or) 2101 BOpc = Instruction::And; 2102 } 2103 } 2104 2105 // If this node is not part of the or/and tree, emit it as a branch. 2106 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2107 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2108 BOp->getParent() != CurBB->getBasicBlock() || 2109 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2110 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2111 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2112 TProb, FProb, InvertCond); 2113 return; 2114 } 2115 2116 // Create TmpBB after CurBB. 2117 MachineFunction::iterator BBI(CurBB); 2118 MachineFunction &MF = DAG.getMachineFunction(); 2119 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2120 CurBB->getParent()->insert(++BBI, TmpBB); 2121 2122 if (Opc == Instruction::Or) { 2123 // Codegen X | Y as: 2124 // BB1: 2125 // jmp_if_X TBB 2126 // jmp TmpBB 2127 // TmpBB: 2128 // jmp_if_Y TBB 2129 // jmp FBB 2130 // 2131 2132 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2133 // The requirement is that 2134 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2135 // = TrueProb for original BB. 2136 // Assuming the original probabilities are A and B, one choice is to set 2137 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2138 // A/(1+B) and 2B/(1+B). This choice assumes that 2139 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2140 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2141 // TmpBB, but the math is more complicated. 2142 2143 auto NewTrueProb = TProb / 2; 2144 auto NewFalseProb = TProb / 2 + FProb; 2145 // Emit the LHS condition. 2146 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2147 NewTrueProb, NewFalseProb, InvertCond); 2148 2149 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2150 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2151 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2152 // Emit the RHS condition into TmpBB. 2153 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2154 Probs[0], Probs[1], InvertCond); 2155 } else { 2156 assert(Opc == Instruction::And && "Unknown merge op!"); 2157 // Codegen X & Y as: 2158 // BB1: 2159 // jmp_if_X TmpBB 2160 // jmp FBB 2161 // TmpBB: 2162 // jmp_if_Y TBB 2163 // jmp FBB 2164 // 2165 // This requires creation of TmpBB after CurBB. 2166 2167 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2168 // The requirement is that 2169 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2170 // = FalseProb for original BB. 2171 // Assuming the original probabilities are A and B, one choice is to set 2172 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2173 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2174 // TrueProb for BB1 * FalseProb for TmpBB. 2175 2176 auto NewTrueProb = TProb + FProb / 2; 2177 auto NewFalseProb = FProb / 2; 2178 // Emit the LHS condition. 2179 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2180 NewTrueProb, NewFalseProb, InvertCond); 2181 2182 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2183 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2184 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2185 // Emit the RHS condition into TmpBB. 2186 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2187 Probs[0], Probs[1], InvertCond); 2188 } 2189 } 2190 2191 /// If the set of cases should be emitted as a series of branches, return true. 2192 /// If we should emit this as a bunch of and/or'd together conditions, return 2193 /// false. 2194 bool 2195 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2196 if (Cases.size() != 2) return true; 2197 2198 // If this is two comparisons of the same values or'd or and'd together, they 2199 // will get folded into a single comparison, so don't emit two blocks. 2200 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2201 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2202 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2203 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2204 return false; 2205 } 2206 2207 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2208 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2209 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2210 Cases[0].CC == Cases[1].CC && 2211 isa<Constant>(Cases[0].CmpRHS) && 2212 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2213 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2214 return false; 2215 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2216 return false; 2217 } 2218 2219 return true; 2220 } 2221 2222 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2223 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2224 2225 // Update machine-CFG edges. 2226 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2227 2228 if (I.isUnconditional()) { 2229 // Update machine-CFG edges. 2230 BrMBB->addSuccessor(Succ0MBB); 2231 2232 // If this is not a fall-through branch or optimizations are switched off, 2233 // emit the branch. 2234 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2235 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2236 MVT::Other, getControlRoot(), 2237 DAG.getBasicBlock(Succ0MBB))); 2238 2239 return; 2240 } 2241 2242 // If this condition is one of the special cases we handle, do special stuff 2243 // now. 2244 const Value *CondVal = I.getCondition(); 2245 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2246 2247 // If this is a series of conditions that are or'd or and'd together, emit 2248 // this as a sequence of branches instead of setcc's with and/or operations. 2249 // As long as jumps are not expensive, this should improve performance. 2250 // For example, instead of something like: 2251 // cmp A, B 2252 // C = seteq 2253 // cmp D, E 2254 // F = setle 2255 // or C, F 2256 // jnz foo 2257 // Emit: 2258 // cmp A, B 2259 // je foo 2260 // cmp D, E 2261 // jle foo 2262 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2263 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2264 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2265 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2266 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2267 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2268 Opcode, 2269 getEdgeProbability(BrMBB, Succ0MBB), 2270 getEdgeProbability(BrMBB, Succ1MBB), 2271 /*InvertCond=*/false); 2272 // If the compares in later blocks need to use values not currently 2273 // exported from this block, export them now. This block should always 2274 // be the first entry. 2275 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2276 2277 // Allow some cases to be rejected. 2278 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2279 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2280 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2281 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2282 } 2283 2284 // Emit the branch for this block. 2285 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2286 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2287 return; 2288 } 2289 2290 // Okay, we decided not to do this, remove any inserted MBB's and clear 2291 // SwitchCases. 2292 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2293 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2294 2295 SL->SwitchCases.clear(); 2296 } 2297 } 2298 2299 // Create a CaseBlock record representing this branch. 2300 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2301 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2302 2303 // Use visitSwitchCase to actually insert the fast branch sequence for this 2304 // cond branch. 2305 visitSwitchCase(CB, BrMBB); 2306 } 2307 2308 /// visitSwitchCase - Emits the necessary code to represent a single node in 2309 /// the binary search tree resulting from lowering a switch instruction. 2310 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2311 MachineBasicBlock *SwitchBB) { 2312 SDValue Cond; 2313 SDValue CondLHS = getValue(CB.CmpLHS); 2314 SDLoc dl = CB.DL; 2315 2316 if (CB.CC == ISD::SETTRUE) { 2317 // Branch or fall through to TrueBB. 2318 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2319 SwitchBB->normalizeSuccProbs(); 2320 if (CB.TrueBB != NextBlock(SwitchBB)) { 2321 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2322 DAG.getBasicBlock(CB.TrueBB))); 2323 } 2324 return; 2325 } 2326 2327 auto &TLI = DAG.getTargetLoweringInfo(); 2328 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2329 2330 // Build the setcc now. 2331 if (!CB.CmpMHS) { 2332 // Fold "(X == true)" to X and "(X == false)" to !X to 2333 // handle common cases produced by branch lowering. 2334 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2335 CB.CC == ISD::SETEQ) 2336 Cond = CondLHS; 2337 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2338 CB.CC == ISD::SETEQ) { 2339 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2340 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2341 } else { 2342 SDValue CondRHS = getValue(CB.CmpRHS); 2343 2344 // If a pointer's DAG type is larger than its memory type then the DAG 2345 // values are zero-extended. This breaks signed comparisons so truncate 2346 // back to the underlying type before doing the compare. 2347 if (CondLHS.getValueType() != MemVT) { 2348 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2349 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2350 } 2351 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2352 } 2353 } else { 2354 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2355 2356 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2357 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2358 2359 SDValue CmpOp = getValue(CB.CmpMHS); 2360 EVT VT = CmpOp.getValueType(); 2361 2362 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2363 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2364 ISD::SETLE); 2365 } else { 2366 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2367 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2368 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2369 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2370 } 2371 } 2372 2373 // Update successor info 2374 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2375 // TrueBB and FalseBB are always different unless the incoming IR is 2376 // degenerate. This only happens when running llc on weird IR. 2377 if (CB.TrueBB != CB.FalseBB) 2378 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2379 SwitchBB->normalizeSuccProbs(); 2380 2381 // If the lhs block is the next block, invert the condition so that we can 2382 // fall through to the lhs instead of the rhs block. 2383 if (CB.TrueBB == NextBlock(SwitchBB)) { 2384 std::swap(CB.TrueBB, CB.FalseBB); 2385 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2386 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2387 } 2388 2389 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2390 MVT::Other, getControlRoot(), Cond, 2391 DAG.getBasicBlock(CB.TrueBB)); 2392 2393 // Insert the false branch. Do this even if it's a fall through branch, 2394 // this makes it easier to do DAG optimizations which require inverting 2395 // the branch condition. 2396 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2397 DAG.getBasicBlock(CB.FalseBB)); 2398 2399 DAG.setRoot(BrCond); 2400 } 2401 2402 /// visitJumpTable - Emit JumpTable node in the current MBB 2403 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2404 // Emit the code for the jump table 2405 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2406 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2407 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2408 JT.Reg, PTy); 2409 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2410 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2411 MVT::Other, Index.getValue(1), 2412 Table, Index); 2413 DAG.setRoot(BrJumpTable); 2414 } 2415 2416 /// visitJumpTableHeader - This function emits necessary code to produce index 2417 /// in the JumpTable from switch case. 2418 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2419 JumpTableHeader &JTH, 2420 MachineBasicBlock *SwitchBB) { 2421 SDLoc dl = getCurSDLoc(); 2422 2423 // Subtract the lowest switch case value from the value being switched on. 2424 SDValue SwitchOp = getValue(JTH.SValue); 2425 EVT VT = SwitchOp.getValueType(); 2426 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2427 DAG.getConstant(JTH.First, dl, VT)); 2428 2429 // The SDNode we just created, which holds the value being switched on minus 2430 // the smallest case value, needs to be copied to a virtual register so it 2431 // can be used as an index into the jump table in a subsequent basic block. 2432 // This value may be smaller or larger than the target's pointer type, and 2433 // therefore require extension or truncating. 2434 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2435 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2436 2437 unsigned JumpTableReg = 2438 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2439 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2440 JumpTableReg, SwitchOp); 2441 JT.Reg = JumpTableReg; 2442 2443 if (!JTH.OmitRangeCheck) { 2444 // Emit the range check for the jump table, and branch to the default block 2445 // for the switch statement if the value being switched on exceeds the 2446 // largest case in the switch. 2447 SDValue CMP = DAG.getSetCC( 2448 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2449 Sub.getValueType()), 2450 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2451 2452 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2453 MVT::Other, CopyTo, CMP, 2454 DAG.getBasicBlock(JT.Default)); 2455 2456 // Avoid emitting unnecessary branches to the next block. 2457 if (JT.MBB != NextBlock(SwitchBB)) 2458 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2459 DAG.getBasicBlock(JT.MBB)); 2460 2461 DAG.setRoot(BrCond); 2462 } else { 2463 // Avoid emitting unnecessary branches to the next block. 2464 if (JT.MBB != NextBlock(SwitchBB)) 2465 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2466 DAG.getBasicBlock(JT.MBB))); 2467 else 2468 DAG.setRoot(CopyTo); 2469 } 2470 } 2471 2472 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2473 /// variable if there exists one. 2474 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2475 SDValue &Chain) { 2476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2477 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2478 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2479 MachineFunction &MF = DAG.getMachineFunction(); 2480 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2481 MachineSDNode *Node = 2482 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2483 if (Global) { 2484 MachinePointerInfo MPInfo(Global); 2485 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2486 MachineMemOperand::MODereferenceable; 2487 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2488 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2489 DAG.setNodeMemRefs(Node, {MemRef}); 2490 } 2491 if (PtrTy != PtrMemTy) 2492 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2493 return SDValue(Node, 0); 2494 } 2495 2496 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2497 /// tail spliced into a stack protector check success bb. 2498 /// 2499 /// For a high level explanation of how this fits into the stack protector 2500 /// generation see the comment on the declaration of class 2501 /// StackProtectorDescriptor. 2502 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2503 MachineBasicBlock *ParentBB) { 2504 2505 // First create the loads to the guard/stack slot for the comparison. 2506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2507 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2508 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2509 2510 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2511 int FI = MFI.getStackProtectorIndex(); 2512 2513 SDValue Guard; 2514 SDLoc dl = getCurSDLoc(); 2515 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2516 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2517 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2518 2519 // Generate code to load the content of the guard slot. 2520 SDValue GuardVal = DAG.getLoad( 2521 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2522 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2523 MachineMemOperand::MOVolatile); 2524 2525 if (TLI.useStackGuardXorFP()) 2526 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2527 2528 // Retrieve guard check function, nullptr if instrumentation is inlined. 2529 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2530 // The target provides a guard check function to validate the guard value. 2531 // Generate a call to that function with the content of the guard slot as 2532 // argument. 2533 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2534 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2535 2536 TargetLowering::ArgListTy Args; 2537 TargetLowering::ArgListEntry Entry; 2538 Entry.Node = GuardVal; 2539 Entry.Ty = FnTy->getParamType(0); 2540 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2541 Entry.IsInReg = true; 2542 Args.push_back(Entry); 2543 2544 TargetLowering::CallLoweringInfo CLI(DAG); 2545 CLI.setDebugLoc(getCurSDLoc()) 2546 .setChain(DAG.getEntryNode()) 2547 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2548 getValue(GuardCheckFn), std::move(Args)); 2549 2550 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2551 DAG.setRoot(Result.second); 2552 return; 2553 } 2554 2555 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2556 // Otherwise, emit a volatile load to retrieve the stack guard value. 2557 SDValue Chain = DAG.getEntryNode(); 2558 if (TLI.useLoadStackGuardNode()) { 2559 Guard = getLoadStackGuard(DAG, dl, Chain); 2560 } else { 2561 const Value *IRGuard = TLI.getSDagStackGuard(M); 2562 SDValue GuardPtr = getValue(IRGuard); 2563 2564 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2565 MachinePointerInfo(IRGuard, 0), Align, 2566 MachineMemOperand::MOVolatile); 2567 } 2568 2569 // Perform the comparison via a subtract/getsetcc. 2570 EVT VT = Guard.getValueType(); 2571 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2572 2573 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2574 *DAG.getContext(), 2575 Sub.getValueType()), 2576 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2577 2578 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2579 // branch to failure MBB. 2580 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2581 MVT::Other, GuardVal.getOperand(0), 2582 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2583 // Otherwise branch to success MBB. 2584 SDValue Br = DAG.getNode(ISD::BR, dl, 2585 MVT::Other, BrCond, 2586 DAG.getBasicBlock(SPD.getSuccessMBB())); 2587 2588 DAG.setRoot(Br); 2589 } 2590 2591 /// Codegen the failure basic block for a stack protector check. 2592 /// 2593 /// A failure stack protector machine basic block consists simply of a call to 2594 /// __stack_chk_fail(). 2595 /// 2596 /// For a high level explanation of how this fits into the stack protector 2597 /// generation see the comment on the declaration of class 2598 /// StackProtectorDescriptor. 2599 void 2600 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2602 TargetLowering::MakeLibCallOptions CallOptions; 2603 CallOptions.setDiscardResult(true); 2604 SDValue Chain = 2605 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2606 None, CallOptions, getCurSDLoc()).second; 2607 // On PS4, the "return address" must still be within the calling function, 2608 // even if it's at the very end, so emit an explicit TRAP here. 2609 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2610 if (TM.getTargetTriple().isPS4CPU()) 2611 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2612 2613 DAG.setRoot(Chain); 2614 } 2615 2616 /// visitBitTestHeader - This function emits necessary code to produce value 2617 /// suitable for "bit tests" 2618 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2619 MachineBasicBlock *SwitchBB) { 2620 SDLoc dl = getCurSDLoc(); 2621 2622 // Subtract the minimum value. 2623 SDValue SwitchOp = getValue(B.SValue); 2624 EVT VT = SwitchOp.getValueType(); 2625 SDValue RangeSub = 2626 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2627 2628 // Determine the type of the test operands. 2629 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2630 bool UsePtrType = false; 2631 if (!TLI.isTypeLegal(VT)) { 2632 UsePtrType = true; 2633 } else { 2634 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2635 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2636 // Switch table case range are encoded into series of masks. 2637 // Just use pointer type, it's guaranteed to fit. 2638 UsePtrType = true; 2639 break; 2640 } 2641 } 2642 SDValue Sub = RangeSub; 2643 if (UsePtrType) { 2644 VT = TLI.getPointerTy(DAG.getDataLayout()); 2645 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2646 } 2647 2648 B.RegVT = VT.getSimpleVT(); 2649 B.Reg = FuncInfo.CreateReg(B.RegVT); 2650 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2651 2652 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2653 2654 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2655 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2656 SwitchBB->normalizeSuccProbs(); 2657 2658 SDValue Root = CopyTo; 2659 if (!B.OmitRangeCheck) { 2660 // Conditional branch to the default block. 2661 SDValue RangeCmp = DAG.getSetCC(dl, 2662 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2663 RangeSub.getValueType()), 2664 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2665 ISD::SETUGT); 2666 2667 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2668 DAG.getBasicBlock(B.Default)); 2669 } 2670 2671 // Avoid emitting unnecessary branches to the next block. 2672 if (MBB != NextBlock(SwitchBB)) 2673 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2674 2675 DAG.setRoot(Root); 2676 } 2677 2678 /// visitBitTestCase - this function produces one "bit test" 2679 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2680 MachineBasicBlock* NextMBB, 2681 BranchProbability BranchProbToNext, 2682 unsigned Reg, 2683 BitTestCase &B, 2684 MachineBasicBlock *SwitchBB) { 2685 SDLoc dl = getCurSDLoc(); 2686 MVT VT = BB.RegVT; 2687 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2688 SDValue Cmp; 2689 unsigned PopCount = countPopulation(B.Mask); 2690 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2691 if (PopCount == 1) { 2692 // Testing for a single bit; just compare the shift count with what it 2693 // would need to be to shift a 1 bit in that position. 2694 Cmp = DAG.getSetCC( 2695 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2696 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2697 ISD::SETEQ); 2698 } else if (PopCount == BB.Range) { 2699 // There is only one zero bit in the range, test for it directly. 2700 Cmp = DAG.getSetCC( 2701 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2702 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2703 ISD::SETNE); 2704 } else { 2705 // Make desired shift 2706 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2707 DAG.getConstant(1, dl, VT), ShiftOp); 2708 2709 // Emit bit tests and jumps 2710 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2711 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2712 Cmp = DAG.getSetCC( 2713 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2714 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2715 } 2716 2717 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2718 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2719 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2720 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2721 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2722 // one as they are relative probabilities (and thus work more like weights), 2723 // and hence we need to normalize them to let the sum of them become one. 2724 SwitchBB->normalizeSuccProbs(); 2725 2726 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2727 MVT::Other, getControlRoot(), 2728 Cmp, DAG.getBasicBlock(B.TargetBB)); 2729 2730 // Avoid emitting unnecessary branches to the next block. 2731 if (NextMBB != NextBlock(SwitchBB)) 2732 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2733 DAG.getBasicBlock(NextMBB)); 2734 2735 DAG.setRoot(BrAnd); 2736 } 2737 2738 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2739 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2740 2741 // Retrieve successors. Look through artificial IR level blocks like 2742 // catchswitch for successors. 2743 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2744 const BasicBlock *EHPadBB = I.getSuccessor(1); 2745 2746 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2747 // have to do anything here to lower funclet bundles. 2748 assert(!I.hasOperandBundlesOtherThan( 2749 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2750 "Cannot lower invokes with arbitrary operand bundles yet!"); 2751 2752 const Value *Callee(I.getCalledValue()); 2753 const Function *Fn = dyn_cast<Function>(Callee); 2754 if (isa<InlineAsm>(Callee)) 2755 visitInlineAsm(&I); 2756 else if (Fn && Fn->isIntrinsic()) { 2757 switch (Fn->getIntrinsicID()) { 2758 default: 2759 llvm_unreachable("Cannot invoke this intrinsic"); 2760 case Intrinsic::donothing: 2761 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2762 break; 2763 case Intrinsic::experimental_patchpoint_void: 2764 case Intrinsic::experimental_patchpoint_i64: 2765 visitPatchpoint(&I, EHPadBB); 2766 break; 2767 case Intrinsic::experimental_gc_statepoint: 2768 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2769 break; 2770 case Intrinsic::wasm_rethrow_in_catch: { 2771 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2772 // special because it can be invoked, so we manually lower it to a DAG 2773 // node here. 2774 SmallVector<SDValue, 8> Ops; 2775 Ops.push_back(getRoot()); // inchain 2776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2777 Ops.push_back( 2778 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2779 TLI.getPointerTy(DAG.getDataLayout()))); 2780 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2781 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2782 break; 2783 } 2784 } 2785 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2786 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2787 // Eventually we will support lowering the @llvm.experimental.deoptimize 2788 // intrinsic, and right now there are no plans to support other intrinsics 2789 // with deopt state. 2790 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2791 } else { 2792 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2793 } 2794 2795 // If the value of the invoke is used outside of its defining block, make it 2796 // available as a virtual register. 2797 // We already took care of the exported value for the statepoint instruction 2798 // during call to the LowerStatepoint. 2799 if (!isStatepoint(I)) { 2800 CopyToExportRegsIfNeeded(&I); 2801 } 2802 2803 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2804 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2805 BranchProbability EHPadBBProb = 2806 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2807 : BranchProbability::getZero(); 2808 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2809 2810 // Update successor info. 2811 addSuccessorWithProb(InvokeMBB, Return); 2812 for (auto &UnwindDest : UnwindDests) { 2813 UnwindDest.first->setIsEHPad(); 2814 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2815 } 2816 InvokeMBB->normalizeSuccProbs(); 2817 2818 // Drop into normal successor. 2819 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2820 DAG.getBasicBlock(Return))); 2821 } 2822 2823 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2824 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2825 2826 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2827 // have to do anything here to lower funclet bundles. 2828 assert(!I.hasOperandBundlesOtherThan( 2829 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2830 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2831 2832 assert(isa<InlineAsm>(I.getCalledValue()) && 2833 "Only know how to handle inlineasm callbr"); 2834 visitInlineAsm(&I); 2835 2836 // Retrieve successors. 2837 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2838 2839 // Update successor info. 2840 addSuccessorWithProb(CallBrMBB, Return); 2841 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2842 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2843 addSuccessorWithProb(CallBrMBB, Target); 2844 } 2845 CallBrMBB->normalizeSuccProbs(); 2846 2847 // Drop into default successor. 2848 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2849 MVT::Other, getControlRoot(), 2850 DAG.getBasicBlock(Return))); 2851 } 2852 2853 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2854 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2855 } 2856 2857 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2858 assert(FuncInfo.MBB->isEHPad() && 2859 "Call to landingpad not in landing pad!"); 2860 2861 // If there aren't registers to copy the values into (e.g., during SjLj 2862 // exceptions), then don't bother to create these DAG nodes. 2863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2864 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2865 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2866 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2867 return; 2868 2869 // If landingpad's return type is token type, we don't create DAG nodes 2870 // for its exception pointer and selector value. The extraction of exception 2871 // pointer or selector value from token type landingpads is not currently 2872 // supported. 2873 if (LP.getType()->isTokenTy()) 2874 return; 2875 2876 SmallVector<EVT, 2> ValueVTs; 2877 SDLoc dl = getCurSDLoc(); 2878 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2879 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2880 2881 // Get the two live-in registers as SDValues. The physregs have already been 2882 // copied into virtual registers. 2883 SDValue Ops[2]; 2884 if (FuncInfo.ExceptionPointerVirtReg) { 2885 Ops[0] = DAG.getZExtOrTrunc( 2886 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2887 FuncInfo.ExceptionPointerVirtReg, 2888 TLI.getPointerTy(DAG.getDataLayout())), 2889 dl, ValueVTs[0]); 2890 } else { 2891 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2892 } 2893 Ops[1] = DAG.getZExtOrTrunc( 2894 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2895 FuncInfo.ExceptionSelectorVirtReg, 2896 TLI.getPointerTy(DAG.getDataLayout())), 2897 dl, ValueVTs[1]); 2898 2899 // Merge into one. 2900 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2901 DAG.getVTList(ValueVTs), Ops); 2902 setValue(&LP, Res); 2903 } 2904 2905 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2906 MachineBasicBlock *Last) { 2907 // Update JTCases. 2908 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2909 if (SL->JTCases[i].first.HeaderBB == First) 2910 SL->JTCases[i].first.HeaderBB = Last; 2911 2912 // Update BitTestCases. 2913 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2914 if (SL->BitTestCases[i].Parent == First) 2915 SL->BitTestCases[i].Parent = Last; 2916 } 2917 2918 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2919 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2920 2921 // Update machine-CFG edges with unique successors. 2922 SmallSet<BasicBlock*, 32> Done; 2923 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2924 BasicBlock *BB = I.getSuccessor(i); 2925 bool Inserted = Done.insert(BB).second; 2926 if (!Inserted) 2927 continue; 2928 2929 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2930 addSuccessorWithProb(IndirectBrMBB, Succ); 2931 } 2932 IndirectBrMBB->normalizeSuccProbs(); 2933 2934 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2935 MVT::Other, getControlRoot(), 2936 getValue(I.getAddress()))); 2937 } 2938 2939 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2940 if (!DAG.getTarget().Options.TrapUnreachable) 2941 return; 2942 2943 // We may be able to ignore unreachable behind a noreturn call. 2944 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2945 const BasicBlock &BB = *I.getParent(); 2946 if (&I != &BB.front()) { 2947 BasicBlock::const_iterator PredI = 2948 std::prev(BasicBlock::const_iterator(&I)); 2949 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2950 if (Call->doesNotReturn()) 2951 return; 2952 } 2953 } 2954 } 2955 2956 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2957 } 2958 2959 void SelectionDAGBuilder::visitFSub(const User &I) { 2960 // -0.0 - X --> fneg 2961 Type *Ty = I.getType(); 2962 if (isa<Constant>(I.getOperand(0)) && 2963 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2964 SDValue Op2 = getValue(I.getOperand(1)); 2965 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2966 Op2.getValueType(), Op2)); 2967 return; 2968 } 2969 2970 visitBinary(I, ISD::FSUB); 2971 } 2972 2973 /// Checks if the given instruction performs a vector reduction, in which case 2974 /// we have the freedom to alter the elements in the result as long as the 2975 /// reduction of them stays unchanged. 2976 static bool isVectorReductionOp(const User *I) { 2977 const Instruction *Inst = dyn_cast<Instruction>(I); 2978 if (!Inst || !Inst->getType()->isVectorTy()) 2979 return false; 2980 2981 auto OpCode = Inst->getOpcode(); 2982 switch (OpCode) { 2983 case Instruction::Add: 2984 case Instruction::Mul: 2985 case Instruction::And: 2986 case Instruction::Or: 2987 case Instruction::Xor: 2988 break; 2989 case Instruction::FAdd: 2990 case Instruction::FMul: 2991 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2992 if (FPOp->getFastMathFlags().isFast()) 2993 break; 2994 LLVM_FALLTHROUGH; 2995 default: 2996 return false; 2997 } 2998 2999 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3000 // Ensure the reduction size is a power of 2. 3001 if (!isPowerOf2_32(ElemNum)) 3002 return false; 3003 3004 unsigned ElemNumToReduce = ElemNum; 3005 3006 // Do DFS search on the def-use chain from the given instruction. We only 3007 // allow four kinds of operations during the search until we reach the 3008 // instruction that extracts the first element from the vector: 3009 // 3010 // 1. The reduction operation of the same opcode as the given instruction. 3011 // 3012 // 2. PHI node. 3013 // 3014 // 3. ShuffleVector instruction together with a reduction operation that 3015 // does a partial reduction. 3016 // 3017 // 4. ExtractElement that extracts the first element from the vector, and we 3018 // stop searching the def-use chain here. 3019 // 3020 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3021 // from 1-3 to the stack to continue the DFS. The given instruction is not 3022 // a reduction operation if we meet any other instructions other than those 3023 // listed above. 3024 3025 SmallVector<const User *, 16> UsersToVisit{Inst}; 3026 SmallPtrSet<const User *, 16> Visited; 3027 bool ReduxExtracted = false; 3028 3029 while (!UsersToVisit.empty()) { 3030 auto User = UsersToVisit.back(); 3031 UsersToVisit.pop_back(); 3032 if (!Visited.insert(User).second) 3033 continue; 3034 3035 for (const auto &U : User->users()) { 3036 auto Inst = dyn_cast<Instruction>(U); 3037 if (!Inst) 3038 return false; 3039 3040 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3041 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3042 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3043 return false; 3044 UsersToVisit.push_back(U); 3045 } else if (const ShuffleVectorInst *ShufInst = 3046 dyn_cast<ShuffleVectorInst>(U)) { 3047 // Detect the following pattern: A ShuffleVector instruction together 3048 // with a reduction that do partial reduction on the first and second 3049 // ElemNumToReduce / 2 elements, and store the result in 3050 // ElemNumToReduce / 2 elements in another vector. 3051 3052 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3053 if (ResultElements < ElemNum) 3054 return false; 3055 3056 if (ElemNumToReduce == 1) 3057 return false; 3058 if (!isa<UndefValue>(U->getOperand(1))) 3059 return false; 3060 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3061 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3062 return false; 3063 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3064 if (ShufInst->getMaskValue(i) != -1) 3065 return false; 3066 3067 // There is only one user of this ShuffleVector instruction, which 3068 // must be a reduction operation. 3069 if (!U->hasOneUse()) 3070 return false; 3071 3072 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3073 if (!U2 || U2->getOpcode() != OpCode) 3074 return false; 3075 3076 // Check operands of the reduction operation. 3077 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3078 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3079 UsersToVisit.push_back(U2); 3080 ElemNumToReduce /= 2; 3081 } else 3082 return false; 3083 } else if (isa<ExtractElementInst>(U)) { 3084 // At this moment we should have reduced all elements in the vector. 3085 if (ElemNumToReduce != 1) 3086 return false; 3087 3088 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3089 if (!Val || !Val->isZero()) 3090 return false; 3091 3092 ReduxExtracted = true; 3093 } else 3094 return false; 3095 } 3096 } 3097 return ReduxExtracted; 3098 } 3099 3100 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3101 SDNodeFlags Flags; 3102 3103 SDValue Op = getValue(I.getOperand(0)); 3104 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3105 Op, Flags); 3106 setValue(&I, UnNodeValue); 3107 } 3108 3109 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3110 SDNodeFlags Flags; 3111 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3112 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3113 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3114 } 3115 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3116 Flags.setExact(ExactOp->isExact()); 3117 } 3118 if (isVectorReductionOp(&I)) { 3119 Flags.setVectorReduction(true); 3120 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3121 } 3122 3123 SDValue Op1 = getValue(I.getOperand(0)); 3124 SDValue Op2 = getValue(I.getOperand(1)); 3125 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3126 Op1, Op2, Flags); 3127 setValue(&I, BinNodeValue); 3128 } 3129 3130 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3131 SDValue Op1 = getValue(I.getOperand(0)); 3132 SDValue Op2 = getValue(I.getOperand(1)); 3133 3134 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3135 Op1.getValueType(), DAG.getDataLayout()); 3136 3137 // Coerce the shift amount to the right type if we can. 3138 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3139 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3140 unsigned Op2Size = Op2.getValueSizeInBits(); 3141 SDLoc DL = getCurSDLoc(); 3142 3143 // If the operand is smaller than the shift count type, promote it. 3144 if (ShiftSize > Op2Size) 3145 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3146 3147 // If the operand is larger than the shift count type but the shift 3148 // count type has enough bits to represent any shift value, truncate 3149 // it now. This is a common case and it exposes the truncate to 3150 // optimization early. 3151 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3152 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3153 // Otherwise we'll need to temporarily settle for some other convenient 3154 // type. Type legalization will make adjustments once the shiftee is split. 3155 else 3156 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3157 } 3158 3159 bool nuw = false; 3160 bool nsw = false; 3161 bool exact = false; 3162 3163 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3164 3165 if (const OverflowingBinaryOperator *OFBinOp = 3166 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3167 nuw = OFBinOp->hasNoUnsignedWrap(); 3168 nsw = OFBinOp->hasNoSignedWrap(); 3169 } 3170 if (const PossiblyExactOperator *ExactOp = 3171 dyn_cast<const PossiblyExactOperator>(&I)) 3172 exact = ExactOp->isExact(); 3173 } 3174 SDNodeFlags Flags; 3175 Flags.setExact(exact); 3176 Flags.setNoSignedWrap(nsw); 3177 Flags.setNoUnsignedWrap(nuw); 3178 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3179 Flags); 3180 setValue(&I, Res); 3181 } 3182 3183 void SelectionDAGBuilder::visitSDiv(const User &I) { 3184 SDValue Op1 = getValue(I.getOperand(0)); 3185 SDValue Op2 = getValue(I.getOperand(1)); 3186 3187 SDNodeFlags Flags; 3188 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3189 cast<PossiblyExactOperator>(&I)->isExact()); 3190 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3191 Op2, Flags)); 3192 } 3193 3194 void SelectionDAGBuilder::visitICmp(const User &I) { 3195 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3196 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3197 predicate = IC->getPredicate(); 3198 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3199 predicate = ICmpInst::Predicate(IC->getPredicate()); 3200 SDValue Op1 = getValue(I.getOperand(0)); 3201 SDValue Op2 = getValue(I.getOperand(1)); 3202 ISD::CondCode Opcode = getICmpCondCode(predicate); 3203 3204 auto &TLI = DAG.getTargetLoweringInfo(); 3205 EVT MemVT = 3206 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3207 3208 // If a pointer's DAG type is larger than its memory type then the DAG values 3209 // are zero-extended. This breaks signed comparisons so truncate back to the 3210 // underlying type before doing the compare. 3211 if (Op1.getValueType() != MemVT) { 3212 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3213 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3214 } 3215 3216 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3217 I.getType()); 3218 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3219 } 3220 3221 void SelectionDAGBuilder::visitFCmp(const User &I) { 3222 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3223 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3224 predicate = FC->getPredicate(); 3225 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3226 predicate = FCmpInst::Predicate(FC->getPredicate()); 3227 SDValue Op1 = getValue(I.getOperand(0)); 3228 SDValue Op2 = getValue(I.getOperand(1)); 3229 3230 ISD::CondCode Condition = getFCmpCondCode(predicate); 3231 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3232 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3233 Condition = getFCmpCodeWithoutNaN(Condition); 3234 3235 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3236 I.getType()); 3237 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3238 } 3239 3240 // Check if the condition of the select has one use or two users that are both 3241 // selects with the same condition. 3242 static bool hasOnlySelectUsers(const Value *Cond) { 3243 return llvm::all_of(Cond->users(), [](const Value *V) { 3244 return isa<SelectInst>(V); 3245 }); 3246 } 3247 3248 void SelectionDAGBuilder::visitSelect(const User &I) { 3249 SmallVector<EVT, 4> ValueVTs; 3250 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3251 ValueVTs); 3252 unsigned NumValues = ValueVTs.size(); 3253 if (NumValues == 0) return; 3254 3255 SmallVector<SDValue, 4> Values(NumValues); 3256 SDValue Cond = getValue(I.getOperand(0)); 3257 SDValue LHSVal = getValue(I.getOperand(1)); 3258 SDValue RHSVal = getValue(I.getOperand(2)); 3259 auto BaseOps = {Cond}; 3260 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3261 ISD::VSELECT : ISD::SELECT; 3262 3263 bool IsUnaryAbs = false; 3264 3265 // Min/max matching is only viable if all output VTs are the same. 3266 if (is_splat(ValueVTs)) { 3267 EVT VT = ValueVTs[0]; 3268 LLVMContext &Ctx = *DAG.getContext(); 3269 auto &TLI = DAG.getTargetLoweringInfo(); 3270 3271 // We care about the legality of the operation after it has been type 3272 // legalized. 3273 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3274 VT = TLI.getTypeToTransformTo(Ctx, VT); 3275 3276 // If the vselect is legal, assume we want to leave this as a vector setcc + 3277 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3278 // min/max is legal on the scalar type. 3279 bool UseScalarMinMax = VT.isVector() && 3280 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3281 3282 Value *LHS, *RHS; 3283 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3284 ISD::NodeType Opc = ISD::DELETED_NODE; 3285 switch (SPR.Flavor) { 3286 case SPF_UMAX: Opc = ISD::UMAX; break; 3287 case SPF_UMIN: Opc = ISD::UMIN; break; 3288 case SPF_SMAX: Opc = ISD::SMAX; break; 3289 case SPF_SMIN: Opc = ISD::SMIN; break; 3290 case SPF_FMINNUM: 3291 switch (SPR.NaNBehavior) { 3292 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3293 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3294 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3295 case SPNB_RETURNS_ANY: { 3296 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3297 Opc = ISD::FMINNUM; 3298 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3299 Opc = ISD::FMINIMUM; 3300 else if (UseScalarMinMax) 3301 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3302 ISD::FMINNUM : ISD::FMINIMUM; 3303 break; 3304 } 3305 } 3306 break; 3307 case SPF_FMAXNUM: 3308 switch (SPR.NaNBehavior) { 3309 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3310 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3311 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3312 case SPNB_RETURNS_ANY: 3313 3314 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3315 Opc = ISD::FMAXNUM; 3316 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3317 Opc = ISD::FMAXIMUM; 3318 else if (UseScalarMinMax) 3319 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3320 ISD::FMAXNUM : ISD::FMAXIMUM; 3321 break; 3322 } 3323 break; 3324 case SPF_ABS: 3325 IsUnaryAbs = true; 3326 Opc = ISD::ABS; 3327 break; 3328 case SPF_NABS: 3329 // TODO: we need to produce sub(0, abs(X)). 3330 default: break; 3331 } 3332 3333 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3334 (TLI.isOperationLegalOrCustom(Opc, VT) || 3335 (UseScalarMinMax && 3336 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3337 // If the underlying comparison instruction is used by any other 3338 // instruction, the consumed instructions won't be destroyed, so it is 3339 // not profitable to convert to a min/max. 3340 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3341 OpCode = Opc; 3342 LHSVal = getValue(LHS); 3343 RHSVal = getValue(RHS); 3344 BaseOps = {}; 3345 } 3346 3347 if (IsUnaryAbs) { 3348 OpCode = Opc; 3349 LHSVal = getValue(LHS); 3350 BaseOps = {}; 3351 } 3352 } 3353 3354 if (IsUnaryAbs) { 3355 for (unsigned i = 0; i != NumValues; ++i) { 3356 Values[i] = 3357 DAG.getNode(OpCode, getCurSDLoc(), 3358 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3359 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3360 } 3361 } else { 3362 for (unsigned i = 0; i != NumValues; ++i) { 3363 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3364 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3365 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3366 Values[i] = DAG.getNode( 3367 OpCode, getCurSDLoc(), 3368 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3369 } 3370 } 3371 3372 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3373 DAG.getVTList(ValueVTs), Values)); 3374 } 3375 3376 void SelectionDAGBuilder::visitTrunc(const User &I) { 3377 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3378 SDValue N = getValue(I.getOperand(0)); 3379 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3380 I.getType()); 3381 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3382 } 3383 3384 void SelectionDAGBuilder::visitZExt(const User &I) { 3385 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3386 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3387 SDValue N = getValue(I.getOperand(0)); 3388 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3389 I.getType()); 3390 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3391 } 3392 3393 void SelectionDAGBuilder::visitSExt(const User &I) { 3394 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3395 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3396 SDValue N = getValue(I.getOperand(0)); 3397 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3398 I.getType()); 3399 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3400 } 3401 3402 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3403 // FPTrunc is never a no-op cast, no need to check 3404 SDValue N = getValue(I.getOperand(0)); 3405 SDLoc dl = getCurSDLoc(); 3406 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3407 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3408 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3409 DAG.getTargetConstant( 3410 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3411 } 3412 3413 void SelectionDAGBuilder::visitFPExt(const User &I) { 3414 // FPExt is never a no-op cast, no need to check 3415 SDValue N = getValue(I.getOperand(0)); 3416 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3417 I.getType()); 3418 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3419 } 3420 3421 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3422 // FPToUI is never a no-op cast, no need to check 3423 SDValue N = getValue(I.getOperand(0)); 3424 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3425 I.getType()); 3426 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3427 } 3428 3429 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3430 // FPToSI is never a no-op cast, no need to check 3431 SDValue N = getValue(I.getOperand(0)); 3432 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3433 I.getType()); 3434 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3435 } 3436 3437 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3438 // UIToFP is never a no-op cast, no need to check 3439 SDValue N = getValue(I.getOperand(0)); 3440 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3441 I.getType()); 3442 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3443 } 3444 3445 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3446 // SIToFP is never a no-op cast, no need to check 3447 SDValue N = getValue(I.getOperand(0)); 3448 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3449 I.getType()); 3450 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3451 } 3452 3453 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3454 // What to do depends on the size of the integer and the size of the pointer. 3455 // We can either truncate, zero extend, or no-op, accordingly. 3456 SDValue N = getValue(I.getOperand(0)); 3457 auto &TLI = DAG.getTargetLoweringInfo(); 3458 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3459 I.getType()); 3460 EVT PtrMemVT = 3461 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3462 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3463 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3464 setValue(&I, N); 3465 } 3466 3467 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3468 // What to do depends on the size of the integer and the size of the pointer. 3469 // We can either truncate, zero extend, or no-op, accordingly. 3470 SDValue N = getValue(I.getOperand(0)); 3471 auto &TLI = DAG.getTargetLoweringInfo(); 3472 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3473 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3474 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3475 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3476 setValue(&I, N); 3477 } 3478 3479 void SelectionDAGBuilder::visitBitCast(const User &I) { 3480 SDValue N = getValue(I.getOperand(0)); 3481 SDLoc dl = getCurSDLoc(); 3482 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3483 I.getType()); 3484 3485 // BitCast assures us that source and destination are the same size so this is 3486 // either a BITCAST or a no-op. 3487 if (DestVT != N.getValueType()) 3488 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3489 DestVT, N)); // convert types. 3490 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3491 // might fold any kind of constant expression to an integer constant and that 3492 // is not what we are looking for. Only recognize a bitcast of a genuine 3493 // constant integer as an opaque constant. 3494 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3495 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3496 /*isOpaque*/true)); 3497 else 3498 setValue(&I, N); // noop cast. 3499 } 3500 3501 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3502 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3503 const Value *SV = I.getOperand(0); 3504 SDValue N = getValue(SV); 3505 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3506 3507 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3508 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3509 3510 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3511 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3512 3513 setValue(&I, N); 3514 } 3515 3516 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3517 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3518 SDValue InVec = getValue(I.getOperand(0)); 3519 SDValue InVal = getValue(I.getOperand(1)); 3520 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3521 TLI.getVectorIdxTy(DAG.getDataLayout())); 3522 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3523 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3524 InVec, InVal, InIdx)); 3525 } 3526 3527 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3528 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3529 SDValue InVec = getValue(I.getOperand(0)); 3530 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3531 TLI.getVectorIdxTy(DAG.getDataLayout())); 3532 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3533 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3534 InVec, InIdx)); 3535 } 3536 3537 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3538 SDValue Src1 = getValue(I.getOperand(0)); 3539 SDValue Src2 = getValue(I.getOperand(1)); 3540 SDLoc DL = getCurSDLoc(); 3541 3542 SmallVector<int, 8> Mask; 3543 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3544 unsigned MaskNumElts = Mask.size(); 3545 3546 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3547 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3548 EVT SrcVT = Src1.getValueType(); 3549 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3550 3551 if (SrcNumElts == MaskNumElts) { 3552 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3553 return; 3554 } 3555 3556 // Normalize the shuffle vector since mask and vector length don't match. 3557 if (SrcNumElts < MaskNumElts) { 3558 // Mask is longer than the source vectors. We can use concatenate vector to 3559 // make the mask and vectors lengths match. 3560 3561 if (MaskNumElts % SrcNumElts == 0) { 3562 // Mask length is a multiple of the source vector length. 3563 // Check if the shuffle is some kind of concatenation of the input 3564 // vectors. 3565 unsigned NumConcat = MaskNumElts / SrcNumElts; 3566 bool IsConcat = true; 3567 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3568 for (unsigned i = 0; i != MaskNumElts; ++i) { 3569 int Idx = Mask[i]; 3570 if (Idx < 0) 3571 continue; 3572 // Ensure the indices in each SrcVT sized piece are sequential and that 3573 // the same source is used for the whole piece. 3574 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3575 (ConcatSrcs[i / SrcNumElts] >= 0 && 3576 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3577 IsConcat = false; 3578 break; 3579 } 3580 // Remember which source this index came from. 3581 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3582 } 3583 3584 // The shuffle is concatenating multiple vectors together. Just emit 3585 // a CONCAT_VECTORS operation. 3586 if (IsConcat) { 3587 SmallVector<SDValue, 8> ConcatOps; 3588 for (auto Src : ConcatSrcs) { 3589 if (Src < 0) 3590 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3591 else if (Src == 0) 3592 ConcatOps.push_back(Src1); 3593 else 3594 ConcatOps.push_back(Src2); 3595 } 3596 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3597 return; 3598 } 3599 } 3600 3601 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3602 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3603 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3604 PaddedMaskNumElts); 3605 3606 // Pad both vectors with undefs to make them the same length as the mask. 3607 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3608 3609 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3610 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3611 MOps1[0] = Src1; 3612 MOps2[0] = Src2; 3613 3614 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3615 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3616 3617 // Readjust mask for new input vector length. 3618 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3619 for (unsigned i = 0; i != MaskNumElts; ++i) { 3620 int Idx = Mask[i]; 3621 if (Idx >= (int)SrcNumElts) 3622 Idx -= SrcNumElts - PaddedMaskNumElts; 3623 MappedOps[i] = Idx; 3624 } 3625 3626 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3627 3628 // If the concatenated vector was padded, extract a subvector with the 3629 // correct number of elements. 3630 if (MaskNumElts != PaddedMaskNumElts) 3631 Result = DAG.getNode( 3632 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3633 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3634 3635 setValue(&I, Result); 3636 return; 3637 } 3638 3639 if (SrcNumElts > MaskNumElts) { 3640 // Analyze the access pattern of the vector to see if we can extract 3641 // two subvectors and do the shuffle. 3642 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3643 bool CanExtract = true; 3644 for (int Idx : Mask) { 3645 unsigned Input = 0; 3646 if (Idx < 0) 3647 continue; 3648 3649 if (Idx >= (int)SrcNumElts) { 3650 Input = 1; 3651 Idx -= SrcNumElts; 3652 } 3653 3654 // If all the indices come from the same MaskNumElts sized portion of 3655 // the sources we can use extract. Also make sure the extract wouldn't 3656 // extract past the end of the source. 3657 int NewStartIdx = alignDown(Idx, MaskNumElts); 3658 if (NewStartIdx + MaskNumElts > SrcNumElts || 3659 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3660 CanExtract = false; 3661 // Make sure we always update StartIdx as we use it to track if all 3662 // elements are undef. 3663 StartIdx[Input] = NewStartIdx; 3664 } 3665 3666 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3667 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3668 return; 3669 } 3670 if (CanExtract) { 3671 // Extract appropriate subvector and generate a vector shuffle 3672 for (unsigned Input = 0; Input < 2; ++Input) { 3673 SDValue &Src = Input == 0 ? Src1 : Src2; 3674 if (StartIdx[Input] < 0) 3675 Src = DAG.getUNDEF(VT); 3676 else { 3677 Src = DAG.getNode( 3678 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3679 DAG.getConstant(StartIdx[Input], DL, 3680 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3681 } 3682 } 3683 3684 // Calculate new mask. 3685 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3686 for (int &Idx : MappedOps) { 3687 if (Idx >= (int)SrcNumElts) 3688 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3689 else if (Idx >= 0) 3690 Idx -= StartIdx[0]; 3691 } 3692 3693 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3694 return; 3695 } 3696 } 3697 3698 // We can't use either concat vectors or extract subvectors so fall back to 3699 // replacing the shuffle with extract and build vector. 3700 // to insert and build vector. 3701 EVT EltVT = VT.getVectorElementType(); 3702 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3703 SmallVector<SDValue,8> Ops; 3704 for (int Idx : Mask) { 3705 SDValue Res; 3706 3707 if (Idx < 0) { 3708 Res = DAG.getUNDEF(EltVT); 3709 } else { 3710 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3711 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3712 3713 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3714 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3715 } 3716 3717 Ops.push_back(Res); 3718 } 3719 3720 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3721 } 3722 3723 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3724 ArrayRef<unsigned> Indices; 3725 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3726 Indices = IV->getIndices(); 3727 else 3728 Indices = cast<ConstantExpr>(&I)->getIndices(); 3729 3730 const Value *Op0 = I.getOperand(0); 3731 const Value *Op1 = I.getOperand(1); 3732 Type *AggTy = I.getType(); 3733 Type *ValTy = Op1->getType(); 3734 bool IntoUndef = isa<UndefValue>(Op0); 3735 bool FromUndef = isa<UndefValue>(Op1); 3736 3737 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3738 3739 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3740 SmallVector<EVT, 4> AggValueVTs; 3741 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3742 SmallVector<EVT, 4> ValValueVTs; 3743 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3744 3745 unsigned NumAggValues = AggValueVTs.size(); 3746 unsigned NumValValues = ValValueVTs.size(); 3747 SmallVector<SDValue, 4> Values(NumAggValues); 3748 3749 // Ignore an insertvalue that produces an empty object 3750 if (!NumAggValues) { 3751 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3752 return; 3753 } 3754 3755 SDValue Agg = getValue(Op0); 3756 unsigned i = 0; 3757 // Copy the beginning value(s) from the original aggregate. 3758 for (; i != LinearIndex; ++i) 3759 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3760 SDValue(Agg.getNode(), Agg.getResNo() + i); 3761 // Copy values from the inserted value(s). 3762 if (NumValValues) { 3763 SDValue Val = getValue(Op1); 3764 for (; i != LinearIndex + NumValValues; ++i) 3765 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3766 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3767 } 3768 // Copy remaining value(s) from the original aggregate. 3769 for (; i != NumAggValues; ++i) 3770 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3771 SDValue(Agg.getNode(), Agg.getResNo() + i); 3772 3773 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3774 DAG.getVTList(AggValueVTs), Values)); 3775 } 3776 3777 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3778 ArrayRef<unsigned> Indices; 3779 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3780 Indices = EV->getIndices(); 3781 else 3782 Indices = cast<ConstantExpr>(&I)->getIndices(); 3783 3784 const Value *Op0 = I.getOperand(0); 3785 Type *AggTy = Op0->getType(); 3786 Type *ValTy = I.getType(); 3787 bool OutOfUndef = isa<UndefValue>(Op0); 3788 3789 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3790 3791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3792 SmallVector<EVT, 4> ValValueVTs; 3793 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3794 3795 unsigned NumValValues = ValValueVTs.size(); 3796 3797 // Ignore a extractvalue that produces an empty object 3798 if (!NumValValues) { 3799 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3800 return; 3801 } 3802 3803 SmallVector<SDValue, 4> Values(NumValValues); 3804 3805 SDValue Agg = getValue(Op0); 3806 // Copy out the selected value(s). 3807 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3808 Values[i - LinearIndex] = 3809 OutOfUndef ? 3810 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3811 SDValue(Agg.getNode(), Agg.getResNo() + i); 3812 3813 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3814 DAG.getVTList(ValValueVTs), Values)); 3815 } 3816 3817 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3818 Value *Op0 = I.getOperand(0); 3819 // Note that the pointer operand may be a vector of pointers. Take the scalar 3820 // element which holds a pointer. 3821 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3822 SDValue N = getValue(Op0); 3823 SDLoc dl = getCurSDLoc(); 3824 auto &TLI = DAG.getTargetLoweringInfo(); 3825 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3826 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3827 3828 // Normalize Vector GEP - all scalar operands should be converted to the 3829 // splat vector. 3830 unsigned VectorWidth = I.getType()->isVectorTy() ? 3831 I.getType()->getVectorNumElements() : 0; 3832 3833 if (VectorWidth && !N.getValueType().isVector()) { 3834 LLVMContext &Context = *DAG.getContext(); 3835 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3836 N = DAG.getSplatBuildVector(VT, dl, N); 3837 } 3838 3839 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3840 GTI != E; ++GTI) { 3841 const Value *Idx = GTI.getOperand(); 3842 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3843 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3844 if (Field) { 3845 // N = N + Offset 3846 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3847 3848 // In an inbounds GEP with an offset that is nonnegative even when 3849 // interpreted as signed, assume there is no unsigned overflow. 3850 SDNodeFlags Flags; 3851 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3852 Flags.setNoUnsignedWrap(true); 3853 3854 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3855 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3856 } 3857 } else { 3858 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3859 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3860 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3861 3862 // If this is a scalar constant or a splat vector of constants, 3863 // handle it quickly. 3864 const auto *C = dyn_cast<Constant>(Idx); 3865 if (C && isa<VectorType>(C->getType())) 3866 C = C->getSplatValue(); 3867 3868 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) { 3869 if (CI->isZero()) 3870 continue; 3871 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3872 LLVMContext &Context = *DAG.getContext(); 3873 SDValue OffsVal = VectorWidth ? 3874 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3875 DAG.getConstant(Offs, dl, IdxTy); 3876 3877 // In an inbounds GEP with an offset that is nonnegative even when 3878 // interpreted as signed, assume there is no unsigned overflow. 3879 SDNodeFlags Flags; 3880 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3881 Flags.setNoUnsignedWrap(true); 3882 3883 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3884 3885 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3886 continue; 3887 } 3888 3889 // N = N + Idx * ElementSize; 3890 SDValue IdxN = getValue(Idx); 3891 3892 if (!IdxN.getValueType().isVector() && VectorWidth) { 3893 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3894 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3895 } 3896 3897 // If the index is smaller or larger than intptr_t, truncate or extend 3898 // it. 3899 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3900 3901 // If this is a multiply by a power of two, turn it into a shl 3902 // immediately. This is a very common case. 3903 if (ElementSize != 1) { 3904 if (ElementSize.isPowerOf2()) { 3905 unsigned Amt = ElementSize.logBase2(); 3906 IdxN = DAG.getNode(ISD::SHL, dl, 3907 N.getValueType(), IdxN, 3908 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3909 } else { 3910 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3911 IdxN.getValueType()); 3912 IdxN = DAG.getNode(ISD::MUL, dl, 3913 N.getValueType(), IdxN, Scale); 3914 } 3915 } 3916 3917 N = DAG.getNode(ISD::ADD, dl, 3918 N.getValueType(), N, IdxN); 3919 } 3920 } 3921 3922 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3923 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3924 3925 setValue(&I, N); 3926 } 3927 3928 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3929 // If this is a fixed sized alloca in the entry block of the function, 3930 // allocate it statically on the stack. 3931 if (FuncInfo.StaticAllocaMap.count(&I)) 3932 return; // getValue will auto-populate this. 3933 3934 SDLoc dl = getCurSDLoc(); 3935 Type *Ty = I.getAllocatedType(); 3936 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3937 auto &DL = DAG.getDataLayout(); 3938 uint64_t TySize = DL.getTypeAllocSize(Ty); 3939 unsigned Align = 3940 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3941 3942 SDValue AllocSize = getValue(I.getArraySize()); 3943 3944 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3945 if (AllocSize.getValueType() != IntPtr) 3946 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3947 3948 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3949 AllocSize, 3950 DAG.getConstant(TySize, dl, IntPtr)); 3951 3952 // Handle alignment. If the requested alignment is less than or equal to 3953 // the stack alignment, ignore it. If the size is greater than or equal to 3954 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3955 unsigned StackAlign = 3956 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3957 if (Align <= StackAlign) 3958 Align = 0; 3959 3960 // Round the size of the allocation up to the stack alignment size 3961 // by add SA-1 to the size. This doesn't overflow because we're computing 3962 // an address inside an alloca. 3963 SDNodeFlags Flags; 3964 Flags.setNoUnsignedWrap(true); 3965 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3966 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3967 3968 // Mask out the low bits for alignment purposes. 3969 AllocSize = 3970 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3971 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3972 3973 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3974 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3975 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3976 setValue(&I, DSA); 3977 DAG.setRoot(DSA.getValue(1)); 3978 3979 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3980 } 3981 3982 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3983 if (I.isAtomic()) 3984 return visitAtomicLoad(I); 3985 3986 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3987 const Value *SV = I.getOperand(0); 3988 if (TLI.supportSwiftError()) { 3989 // Swifterror values can come from either a function parameter with 3990 // swifterror attribute or an alloca with swifterror attribute. 3991 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3992 if (Arg->hasSwiftErrorAttr()) 3993 return visitLoadFromSwiftError(I); 3994 } 3995 3996 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3997 if (Alloca->isSwiftError()) 3998 return visitLoadFromSwiftError(I); 3999 } 4000 } 4001 4002 SDValue Ptr = getValue(SV); 4003 4004 Type *Ty = I.getType(); 4005 4006 bool isVolatile = I.isVolatile(); 4007 bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal); 4008 bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load); 4009 bool isDereferenceable = 4010 isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout()); 4011 unsigned Alignment = I.getAlignment(); 4012 4013 AAMDNodes AAInfo; 4014 I.getAAMetadata(AAInfo); 4015 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4016 4017 SmallVector<EVT, 4> ValueVTs, MemVTs; 4018 SmallVector<uint64_t, 4> Offsets; 4019 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4020 unsigned NumValues = ValueVTs.size(); 4021 if (NumValues == 0) 4022 return; 4023 4024 SDValue Root; 4025 bool ConstantMemory = false; 4026 if (isVolatile || NumValues > MaxParallelChains) 4027 // Serialize volatile loads with other side effects. 4028 Root = getRoot(); 4029 else if (AA && 4030 AA->pointsToConstantMemory(MemoryLocation( 4031 SV, 4032 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4033 AAInfo))) { 4034 // Do not serialize (non-volatile) loads of constant memory with anything. 4035 Root = DAG.getEntryNode(); 4036 ConstantMemory = true; 4037 } else { 4038 // Do not serialize non-volatile loads against each other. 4039 Root = DAG.getRoot(); 4040 } 4041 4042 SDLoc dl = getCurSDLoc(); 4043 4044 if (isVolatile) 4045 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4046 4047 // An aggregate load cannot wrap around the address space, so offsets to its 4048 // parts don't wrap either. 4049 SDNodeFlags Flags; 4050 Flags.setNoUnsignedWrap(true); 4051 4052 SmallVector<SDValue, 4> Values(NumValues); 4053 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4054 EVT PtrVT = Ptr.getValueType(); 4055 unsigned ChainI = 0; 4056 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4057 // Serializing loads here may result in excessive register pressure, and 4058 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4059 // could recover a bit by hoisting nodes upward in the chain by recognizing 4060 // they are side-effect free or do not alias. The optimizer should really 4061 // avoid this case by converting large object/array copies to llvm.memcpy 4062 // (MaxParallelChains should always remain as failsafe). 4063 if (ChainI == MaxParallelChains) { 4064 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4065 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4066 makeArrayRef(Chains.data(), ChainI)); 4067 Root = Chain; 4068 ChainI = 0; 4069 } 4070 SDValue A = DAG.getNode(ISD::ADD, dl, 4071 PtrVT, Ptr, 4072 DAG.getConstant(Offsets[i], dl, PtrVT), 4073 Flags); 4074 auto MMOFlags = MachineMemOperand::MONone; 4075 if (isVolatile) 4076 MMOFlags |= MachineMemOperand::MOVolatile; 4077 if (isNonTemporal) 4078 MMOFlags |= MachineMemOperand::MONonTemporal; 4079 if (isInvariant) 4080 MMOFlags |= MachineMemOperand::MOInvariant; 4081 if (isDereferenceable) 4082 MMOFlags |= MachineMemOperand::MODereferenceable; 4083 MMOFlags |= TLI.getMMOFlags(I); 4084 4085 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4086 MachinePointerInfo(SV, Offsets[i]), Alignment, 4087 MMOFlags, AAInfo, Ranges); 4088 Chains[ChainI] = L.getValue(1); 4089 4090 if (MemVTs[i] != ValueVTs[i]) 4091 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4092 4093 Values[i] = L; 4094 } 4095 4096 if (!ConstantMemory) { 4097 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4098 makeArrayRef(Chains.data(), ChainI)); 4099 if (isVolatile) 4100 DAG.setRoot(Chain); 4101 else 4102 PendingLoads.push_back(Chain); 4103 } 4104 4105 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4106 DAG.getVTList(ValueVTs), Values)); 4107 } 4108 4109 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4110 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4111 "call visitStoreToSwiftError when backend supports swifterror"); 4112 4113 SmallVector<EVT, 4> ValueVTs; 4114 SmallVector<uint64_t, 4> Offsets; 4115 const Value *SrcV = I.getOperand(0); 4116 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4117 SrcV->getType(), ValueVTs, &Offsets); 4118 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4119 "expect a single EVT for swifterror"); 4120 4121 SDValue Src = getValue(SrcV); 4122 // Create a virtual register, then update the virtual register. 4123 Register VReg = 4124 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4125 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4126 // Chain can be getRoot or getControlRoot. 4127 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4128 SDValue(Src.getNode(), Src.getResNo())); 4129 DAG.setRoot(CopyNode); 4130 } 4131 4132 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4133 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4134 "call visitLoadFromSwiftError when backend supports swifterror"); 4135 4136 assert(!I.isVolatile() && 4137 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4138 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4139 "Support volatile, non temporal, invariant for load_from_swift_error"); 4140 4141 const Value *SV = I.getOperand(0); 4142 Type *Ty = I.getType(); 4143 AAMDNodes AAInfo; 4144 I.getAAMetadata(AAInfo); 4145 assert( 4146 (!AA || 4147 !AA->pointsToConstantMemory(MemoryLocation( 4148 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4149 AAInfo))) && 4150 "load_from_swift_error should not be constant memory"); 4151 4152 SmallVector<EVT, 4> ValueVTs; 4153 SmallVector<uint64_t, 4> Offsets; 4154 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4155 ValueVTs, &Offsets); 4156 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4157 "expect a single EVT for swifterror"); 4158 4159 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4160 SDValue L = DAG.getCopyFromReg( 4161 getRoot(), getCurSDLoc(), 4162 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4163 4164 setValue(&I, L); 4165 } 4166 4167 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4168 if (I.isAtomic()) 4169 return visitAtomicStore(I); 4170 4171 const Value *SrcV = I.getOperand(0); 4172 const Value *PtrV = I.getOperand(1); 4173 4174 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4175 if (TLI.supportSwiftError()) { 4176 // Swifterror values can come from either a function parameter with 4177 // swifterror attribute or an alloca with swifterror attribute. 4178 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4179 if (Arg->hasSwiftErrorAttr()) 4180 return visitStoreToSwiftError(I); 4181 } 4182 4183 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4184 if (Alloca->isSwiftError()) 4185 return visitStoreToSwiftError(I); 4186 } 4187 } 4188 4189 SmallVector<EVT, 4> ValueVTs, MemVTs; 4190 SmallVector<uint64_t, 4> Offsets; 4191 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4192 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4193 unsigned NumValues = ValueVTs.size(); 4194 if (NumValues == 0) 4195 return; 4196 4197 // Get the lowered operands. Note that we do this after 4198 // checking if NumResults is zero, because with zero results 4199 // the operands won't have values in the map. 4200 SDValue Src = getValue(SrcV); 4201 SDValue Ptr = getValue(PtrV); 4202 4203 SDValue Root = getRoot(); 4204 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4205 SDLoc dl = getCurSDLoc(); 4206 EVT PtrVT = Ptr.getValueType(); 4207 unsigned Alignment = I.getAlignment(); 4208 AAMDNodes AAInfo; 4209 I.getAAMetadata(AAInfo); 4210 4211 auto MMOFlags = MachineMemOperand::MONone; 4212 if (I.isVolatile()) 4213 MMOFlags |= MachineMemOperand::MOVolatile; 4214 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4215 MMOFlags |= MachineMemOperand::MONonTemporal; 4216 MMOFlags |= TLI.getMMOFlags(I); 4217 4218 // An aggregate load cannot wrap around the address space, so offsets to its 4219 // parts don't wrap either. 4220 SDNodeFlags Flags; 4221 Flags.setNoUnsignedWrap(true); 4222 4223 unsigned ChainI = 0; 4224 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4225 // See visitLoad comments. 4226 if (ChainI == MaxParallelChains) { 4227 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4228 makeArrayRef(Chains.data(), ChainI)); 4229 Root = Chain; 4230 ChainI = 0; 4231 } 4232 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 4233 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 4234 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4235 if (MemVTs[i] != ValueVTs[i]) 4236 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4237 SDValue St = 4238 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4239 Alignment, MMOFlags, AAInfo); 4240 Chains[ChainI] = St; 4241 } 4242 4243 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4244 makeArrayRef(Chains.data(), ChainI)); 4245 DAG.setRoot(StoreNode); 4246 } 4247 4248 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4249 bool IsCompressing) { 4250 SDLoc sdl = getCurSDLoc(); 4251 4252 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4253 unsigned& Alignment) { 4254 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4255 Src0 = I.getArgOperand(0); 4256 Ptr = I.getArgOperand(1); 4257 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4258 Mask = I.getArgOperand(3); 4259 }; 4260 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4261 unsigned& Alignment) { 4262 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4263 Src0 = I.getArgOperand(0); 4264 Ptr = I.getArgOperand(1); 4265 Mask = I.getArgOperand(2); 4266 Alignment = 0; 4267 }; 4268 4269 Value *PtrOperand, *MaskOperand, *Src0Operand; 4270 unsigned Alignment; 4271 if (IsCompressing) 4272 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4273 else 4274 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4275 4276 SDValue Ptr = getValue(PtrOperand); 4277 SDValue Src0 = getValue(Src0Operand); 4278 SDValue Mask = getValue(MaskOperand); 4279 4280 EVT VT = Src0.getValueType(); 4281 if (!Alignment) 4282 Alignment = DAG.getEVTAlignment(VT); 4283 4284 AAMDNodes AAInfo; 4285 I.getAAMetadata(AAInfo); 4286 4287 MachineMemOperand *MMO = 4288 DAG.getMachineFunction(). 4289 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4290 MachineMemOperand::MOStore, VT.getStoreSize(), 4291 Alignment, AAInfo); 4292 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4293 MMO, false /* Truncating */, 4294 IsCompressing); 4295 DAG.setRoot(StoreNode); 4296 setValue(&I, StoreNode); 4297 } 4298 4299 // Get a uniform base for the Gather/Scatter intrinsic. 4300 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4301 // We try to represent it as a base pointer + vector of indices. 4302 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4303 // The first operand of the GEP may be a single pointer or a vector of pointers 4304 // Example: 4305 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4306 // or 4307 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4308 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4309 // 4310 // When the first GEP operand is a single pointer - it is the uniform base we 4311 // are looking for. If first operand of the GEP is a splat vector - we 4312 // extract the splat value and use it as a uniform base. 4313 // In all other cases the function returns 'false'. 4314 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index, 4315 ISD::MemIndexType &IndexType, SDValue &Scale, 4316 SelectionDAGBuilder *SDB) { 4317 SelectionDAG& DAG = SDB->DAG; 4318 LLVMContext &Context = *DAG.getContext(); 4319 4320 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4321 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4322 if (!GEP) 4323 return false; 4324 4325 const Value *GEPPtr = GEP->getPointerOperand(); 4326 if (!GEPPtr->getType()->isVectorTy()) 4327 Ptr = GEPPtr; 4328 else if (!(Ptr = getSplatValue(GEPPtr))) 4329 return false; 4330 4331 unsigned FinalIndex = GEP->getNumOperands() - 1; 4332 Value *IndexVal = GEP->getOperand(FinalIndex); 4333 4334 // Ensure all the other indices are 0. 4335 for (unsigned i = 1; i < FinalIndex; ++i) { 4336 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4337 if (!C) 4338 return false; 4339 if (isa<VectorType>(C->getType())) 4340 C = C->getSplatValue(); 4341 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4342 if (!CI || !CI->isZero()) 4343 return false; 4344 } 4345 4346 // The operands of the GEP may be defined in another basic block. 4347 // In this case we'll not find nodes for the operands. 4348 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4349 return false; 4350 4351 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4352 const DataLayout &DL = DAG.getDataLayout(); 4353 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4354 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4355 Base = SDB->getValue(Ptr); 4356 Index = SDB->getValue(IndexVal); 4357 IndexType = ISD::SIGNED_SCALED; 4358 4359 if (!Index.getValueType().isVector()) { 4360 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4361 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4362 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4363 } 4364 return true; 4365 } 4366 4367 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4368 SDLoc sdl = getCurSDLoc(); 4369 4370 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4371 const Value *Ptr = I.getArgOperand(1); 4372 SDValue Src0 = getValue(I.getArgOperand(0)); 4373 SDValue Mask = getValue(I.getArgOperand(3)); 4374 EVT VT = Src0.getValueType(); 4375 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4376 if (!Alignment) 4377 Alignment = DAG.getEVTAlignment(VT); 4378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4379 4380 AAMDNodes AAInfo; 4381 I.getAAMetadata(AAInfo); 4382 4383 SDValue Base; 4384 SDValue Index; 4385 ISD::MemIndexType IndexType; 4386 SDValue Scale; 4387 const Value *BasePtr = Ptr; 4388 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4389 this); 4390 4391 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4392 MachineMemOperand *MMO = DAG.getMachineFunction(). 4393 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4394 MachineMemOperand::MOStore, VT.getStoreSize(), 4395 Alignment, AAInfo); 4396 if (!UniformBase) { 4397 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4398 Index = getValue(Ptr); 4399 IndexType = ISD::SIGNED_SCALED; 4400 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4401 } 4402 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4403 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4404 Ops, MMO, IndexType); 4405 DAG.setRoot(Scatter); 4406 setValue(&I, Scatter); 4407 } 4408 4409 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4410 SDLoc sdl = getCurSDLoc(); 4411 4412 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4413 unsigned& Alignment) { 4414 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4415 Ptr = I.getArgOperand(0); 4416 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4417 Mask = I.getArgOperand(2); 4418 Src0 = I.getArgOperand(3); 4419 }; 4420 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4421 unsigned& Alignment) { 4422 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4423 Ptr = I.getArgOperand(0); 4424 Alignment = 0; 4425 Mask = I.getArgOperand(1); 4426 Src0 = I.getArgOperand(2); 4427 }; 4428 4429 Value *PtrOperand, *MaskOperand, *Src0Operand; 4430 unsigned Alignment; 4431 if (IsExpanding) 4432 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4433 else 4434 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4435 4436 SDValue Ptr = getValue(PtrOperand); 4437 SDValue Src0 = getValue(Src0Operand); 4438 SDValue Mask = getValue(MaskOperand); 4439 4440 EVT VT = Src0.getValueType(); 4441 if (!Alignment) 4442 Alignment = DAG.getEVTAlignment(VT); 4443 4444 AAMDNodes AAInfo; 4445 I.getAAMetadata(AAInfo); 4446 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4447 4448 // Do not serialize masked loads of constant memory with anything. 4449 bool AddToChain = 4450 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4451 PtrOperand, 4452 LocationSize::precise( 4453 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4454 AAInfo)); 4455 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4456 4457 MachineMemOperand *MMO = 4458 DAG.getMachineFunction(). 4459 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4460 MachineMemOperand::MOLoad, VT.getStoreSize(), 4461 Alignment, AAInfo, Ranges); 4462 4463 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4464 ISD::NON_EXTLOAD, IsExpanding); 4465 if (AddToChain) 4466 PendingLoads.push_back(Load.getValue(1)); 4467 setValue(&I, Load); 4468 } 4469 4470 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4471 SDLoc sdl = getCurSDLoc(); 4472 4473 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4474 const Value *Ptr = I.getArgOperand(0); 4475 SDValue Src0 = getValue(I.getArgOperand(3)); 4476 SDValue Mask = getValue(I.getArgOperand(2)); 4477 4478 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4479 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4480 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4481 if (!Alignment) 4482 Alignment = DAG.getEVTAlignment(VT); 4483 4484 AAMDNodes AAInfo; 4485 I.getAAMetadata(AAInfo); 4486 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4487 4488 SDValue Root = DAG.getRoot(); 4489 SDValue Base; 4490 SDValue Index; 4491 ISD::MemIndexType IndexType; 4492 SDValue Scale; 4493 const Value *BasePtr = Ptr; 4494 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4495 this); 4496 bool ConstantMemory = false; 4497 if (UniformBase && AA && 4498 AA->pointsToConstantMemory( 4499 MemoryLocation(BasePtr, 4500 LocationSize::precise( 4501 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4502 AAInfo))) { 4503 // Do not serialize (non-volatile) loads of constant memory with anything. 4504 Root = DAG.getEntryNode(); 4505 ConstantMemory = true; 4506 } 4507 4508 MachineMemOperand *MMO = 4509 DAG.getMachineFunction(). 4510 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4511 MachineMemOperand::MOLoad, VT.getStoreSize(), 4512 Alignment, AAInfo, Ranges); 4513 4514 if (!UniformBase) { 4515 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4516 Index = getValue(Ptr); 4517 IndexType = ISD::SIGNED_SCALED; 4518 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4519 } 4520 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4521 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4522 Ops, MMO, IndexType); 4523 4524 SDValue OutChain = Gather.getValue(1); 4525 if (!ConstantMemory) 4526 PendingLoads.push_back(OutChain); 4527 setValue(&I, Gather); 4528 } 4529 4530 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4531 SDLoc dl = getCurSDLoc(); 4532 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4533 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4534 SyncScope::ID SSID = I.getSyncScopeID(); 4535 4536 SDValue InChain = getRoot(); 4537 4538 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4539 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4540 4541 auto Alignment = DAG.getEVTAlignment(MemVT); 4542 4543 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4544 if (I.isVolatile()) 4545 Flags |= MachineMemOperand::MOVolatile; 4546 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4547 4548 MachineFunction &MF = DAG.getMachineFunction(); 4549 MachineMemOperand *MMO = 4550 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4551 Flags, MemVT.getStoreSize(), Alignment, 4552 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4553 FailureOrdering); 4554 4555 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4556 dl, MemVT, VTs, InChain, 4557 getValue(I.getPointerOperand()), 4558 getValue(I.getCompareOperand()), 4559 getValue(I.getNewValOperand()), MMO); 4560 4561 SDValue OutChain = L.getValue(2); 4562 4563 setValue(&I, L); 4564 DAG.setRoot(OutChain); 4565 } 4566 4567 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4568 SDLoc dl = getCurSDLoc(); 4569 ISD::NodeType NT; 4570 switch (I.getOperation()) { 4571 default: llvm_unreachable("Unknown atomicrmw operation"); 4572 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4573 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4574 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4575 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4576 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4577 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4578 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4579 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4580 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4581 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4582 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4583 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4584 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4585 } 4586 AtomicOrdering Ordering = I.getOrdering(); 4587 SyncScope::ID SSID = I.getSyncScopeID(); 4588 4589 SDValue InChain = getRoot(); 4590 4591 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4592 auto Alignment = DAG.getEVTAlignment(MemVT); 4593 4594 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4595 if (I.isVolatile()) 4596 Flags |= MachineMemOperand::MOVolatile; 4597 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4598 4599 MachineFunction &MF = DAG.getMachineFunction(); 4600 MachineMemOperand *MMO = 4601 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4602 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4603 nullptr, SSID, Ordering); 4604 4605 SDValue L = 4606 DAG.getAtomic(NT, dl, MemVT, InChain, 4607 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4608 MMO); 4609 4610 SDValue OutChain = L.getValue(1); 4611 4612 setValue(&I, L); 4613 DAG.setRoot(OutChain); 4614 } 4615 4616 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4617 SDLoc dl = getCurSDLoc(); 4618 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4619 SDValue Ops[3]; 4620 Ops[0] = getRoot(); 4621 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4622 TLI.getFenceOperandTy(DAG.getDataLayout())); 4623 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4624 TLI.getFenceOperandTy(DAG.getDataLayout())); 4625 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4626 } 4627 4628 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4629 SDLoc dl = getCurSDLoc(); 4630 AtomicOrdering Order = I.getOrdering(); 4631 SyncScope::ID SSID = I.getSyncScopeID(); 4632 4633 SDValue InChain = getRoot(); 4634 4635 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4636 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4637 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4638 4639 if (!TLI.supportsUnalignedAtomics() && 4640 I.getAlignment() < MemVT.getSizeInBits() / 8) 4641 report_fatal_error("Cannot generate unaligned atomic load"); 4642 4643 auto Flags = MachineMemOperand::MOLoad; 4644 if (I.isVolatile()) 4645 Flags |= MachineMemOperand::MOVolatile; 4646 if (I.hasMetadata(LLVMContext::MD_invariant_load)) 4647 Flags |= MachineMemOperand::MOInvariant; 4648 if (isDereferenceablePointer(I.getPointerOperand(), I.getType(), 4649 DAG.getDataLayout())) 4650 Flags |= MachineMemOperand::MODereferenceable; 4651 4652 Flags |= TLI.getMMOFlags(I); 4653 4654 MachineMemOperand *MMO = 4655 DAG.getMachineFunction(). 4656 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4657 Flags, MemVT.getStoreSize(), 4658 I.getAlignment() ? I.getAlignment() : 4659 DAG.getEVTAlignment(MemVT), 4660 AAMDNodes(), nullptr, SSID, Order); 4661 4662 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4663 4664 SDValue Ptr = getValue(I.getPointerOperand()); 4665 4666 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4667 // TODO: Once this is better exercised by tests, it should be merged with 4668 // the normal path for loads to prevent future divergence. 4669 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4670 if (MemVT != VT) 4671 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4672 4673 setValue(&I, L); 4674 if (!I.isUnordered()) { 4675 SDValue OutChain = L.getValue(1); 4676 DAG.setRoot(OutChain); 4677 } 4678 return; 4679 } 4680 4681 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4682 Ptr, MMO); 4683 4684 SDValue OutChain = L.getValue(1); 4685 if (MemVT != VT) 4686 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4687 4688 setValue(&I, L); 4689 DAG.setRoot(OutChain); 4690 } 4691 4692 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4693 SDLoc dl = getCurSDLoc(); 4694 4695 AtomicOrdering Ordering = I.getOrdering(); 4696 SyncScope::ID SSID = I.getSyncScopeID(); 4697 4698 SDValue InChain = getRoot(); 4699 4700 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4701 EVT MemVT = 4702 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4703 4704 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4705 report_fatal_error("Cannot generate unaligned atomic store"); 4706 4707 auto Flags = MachineMemOperand::MOStore; 4708 if (I.isVolatile()) 4709 Flags |= MachineMemOperand::MOVolatile; 4710 Flags |= TLI.getMMOFlags(I); 4711 4712 MachineFunction &MF = DAG.getMachineFunction(); 4713 MachineMemOperand *MMO = 4714 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4715 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4716 nullptr, SSID, Ordering); 4717 4718 SDValue Val = getValue(I.getValueOperand()); 4719 if (Val.getValueType() != MemVT) 4720 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4721 SDValue Ptr = getValue(I.getPointerOperand()); 4722 4723 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4724 // TODO: Once this is better exercised by tests, it should be merged with 4725 // the normal path for stores to prevent future divergence. 4726 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4727 DAG.setRoot(S); 4728 return; 4729 } 4730 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4731 Ptr, Val, MMO); 4732 4733 4734 DAG.setRoot(OutChain); 4735 } 4736 4737 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4738 /// node. 4739 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4740 unsigned Intrinsic) { 4741 // Ignore the callsite's attributes. A specific call site may be marked with 4742 // readnone, but the lowering code will expect the chain based on the 4743 // definition. 4744 const Function *F = I.getCalledFunction(); 4745 bool HasChain = !F->doesNotAccessMemory(); 4746 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4747 4748 // Build the operand list. 4749 SmallVector<SDValue, 8> Ops; 4750 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4751 if (OnlyLoad) { 4752 // We don't need to serialize loads against other loads. 4753 Ops.push_back(DAG.getRoot()); 4754 } else { 4755 Ops.push_back(getRoot()); 4756 } 4757 } 4758 4759 // Info is set by getTgtMemInstrinsic 4760 TargetLowering::IntrinsicInfo Info; 4761 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4762 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4763 DAG.getMachineFunction(), 4764 Intrinsic); 4765 4766 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4767 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4768 Info.opc == ISD::INTRINSIC_W_CHAIN) 4769 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4770 TLI.getPointerTy(DAG.getDataLayout()))); 4771 4772 // Add all operands of the call to the operand list. 4773 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4774 const Value *Arg = I.getArgOperand(i); 4775 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4776 Ops.push_back(getValue(Arg)); 4777 continue; 4778 } 4779 4780 // Use TargetConstant instead of a regular constant for immarg. 4781 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4782 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4783 assert(CI->getBitWidth() <= 64 && 4784 "large intrinsic immediates not handled"); 4785 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4786 } else { 4787 Ops.push_back( 4788 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4789 } 4790 } 4791 4792 SmallVector<EVT, 4> ValueVTs; 4793 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4794 4795 if (HasChain) 4796 ValueVTs.push_back(MVT::Other); 4797 4798 SDVTList VTs = DAG.getVTList(ValueVTs); 4799 4800 // Create the node. 4801 SDValue Result; 4802 if (IsTgtIntrinsic) { 4803 // This is target intrinsic that touches memory 4804 AAMDNodes AAInfo; 4805 I.getAAMetadata(AAInfo); 4806 Result = DAG.getMemIntrinsicNode( 4807 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4808 MachinePointerInfo(Info.ptrVal, Info.offset), 4809 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4810 } else if (!HasChain) { 4811 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4812 } else if (!I.getType()->isVoidTy()) { 4813 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4814 } else { 4815 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4816 } 4817 4818 if (HasChain) { 4819 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4820 if (OnlyLoad) 4821 PendingLoads.push_back(Chain); 4822 else 4823 DAG.setRoot(Chain); 4824 } 4825 4826 if (!I.getType()->isVoidTy()) { 4827 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4828 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4829 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4830 } else 4831 Result = lowerRangeToAssertZExt(DAG, I, Result); 4832 4833 setValue(&I, Result); 4834 } 4835 } 4836 4837 /// GetSignificand - Get the significand and build it into a floating-point 4838 /// number with exponent of 1: 4839 /// 4840 /// Op = (Op & 0x007fffff) | 0x3f800000; 4841 /// 4842 /// where Op is the hexadecimal representation of floating point value. 4843 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4844 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4845 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4846 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4847 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4848 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4849 } 4850 4851 /// GetExponent - Get the exponent: 4852 /// 4853 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4854 /// 4855 /// where Op is the hexadecimal representation of floating point value. 4856 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4857 const TargetLowering &TLI, const SDLoc &dl) { 4858 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4859 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4860 SDValue t1 = DAG.getNode( 4861 ISD::SRL, dl, MVT::i32, t0, 4862 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4863 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4864 DAG.getConstant(127, dl, MVT::i32)); 4865 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4866 } 4867 4868 /// getF32Constant - Get 32-bit floating point constant. 4869 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4870 const SDLoc &dl) { 4871 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4872 MVT::f32); 4873 } 4874 4875 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4876 SelectionDAG &DAG) { 4877 // TODO: What fast-math-flags should be set on the floating-point nodes? 4878 4879 // IntegerPartOfX = ((int32_t)(t0); 4880 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4881 4882 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4883 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4884 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4885 4886 // IntegerPartOfX <<= 23; 4887 IntegerPartOfX = DAG.getNode( 4888 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4889 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4890 DAG.getDataLayout()))); 4891 4892 SDValue TwoToFractionalPartOfX; 4893 if (LimitFloatPrecision <= 6) { 4894 // For floating-point precision of 6: 4895 // 4896 // TwoToFractionalPartOfX = 4897 // 0.997535578f + 4898 // (0.735607626f + 0.252464424f * x) * x; 4899 // 4900 // error 0.0144103317, which is 6 bits 4901 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4902 getF32Constant(DAG, 0x3e814304, dl)); 4903 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4904 getF32Constant(DAG, 0x3f3c50c8, dl)); 4905 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4906 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4907 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4908 } else if (LimitFloatPrecision <= 12) { 4909 // For floating-point precision of 12: 4910 // 4911 // TwoToFractionalPartOfX = 4912 // 0.999892986f + 4913 // (0.696457318f + 4914 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4915 // 4916 // error 0.000107046256, which is 13 to 14 bits 4917 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4918 getF32Constant(DAG, 0x3da235e3, dl)); 4919 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4920 getF32Constant(DAG, 0x3e65b8f3, dl)); 4921 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4922 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4923 getF32Constant(DAG, 0x3f324b07, dl)); 4924 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4925 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4926 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4927 } else { // LimitFloatPrecision <= 18 4928 // For floating-point precision of 18: 4929 // 4930 // TwoToFractionalPartOfX = 4931 // 0.999999982f + 4932 // (0.693148872f + 4933 // (0.240227044f + 4934 // (0.554906021e-1f + 4935 // (0.961591928e-2f + 4936 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4937 // error 2.47208000*10^(-7), which is better than 18 bits 4938 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4939 getF32Constant(DAG, 0x3924b03e, dl)); 4940 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4941 getF32Constant(DAG, 0x3ab24b87, dl)); 4942 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4943 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4944 getF32Constant(DAG, 0x3c1d8c17, dl)); 4945 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4946 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4947 getF32Constant(DAG, 0x3d634a1d, dl)); 4948 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4949 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4950 getF32Constant(DAG, 0x3e75fe14, dl)); 4951 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4952 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4953 getF32Constant(DAG, 0x3f317234, dl)); 4954 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4955 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4956 getF32Constant(DAG, 0x3f800000, dl)); 4957 } 4958 4959 // Add the exponent into the result in integer domain. 4960 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4961 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4962 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4963 } 4964 4965 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4966 /// limited-precision mode. 4967 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4968 const TargetLowering &TLI) { 4969 if (Op.getValueType() == MVT::f32 && 4970 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4971 4972 // Put the exponent in the right bit position for later addition to the 4973 // final result: 4974 // 4975 // #define LOG2OFe 1.4426950f 4976 // t0 = Op * LOG2OFe 4977 4978 // TODO: What fast-math-flags should be set here? 4979 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4980 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4981 return getLimitedPrecisionExp2(t0, dl, DAG); 4982 } 4983 4984 // No special expansion. 4985 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4986 } 4987 4988 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4989 /// limited-precision mode. 4990 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4991 const TargetLowering &TLI) { 4992 // TODO: What fast-math-flags should be set on the floating-point nodes? 4993 4994 if (Op.getValueType() == MVT::f32 && 4995 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4996 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4997 4998 // Scale the exponent by log(2) [0.69314718f]. 4999 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5000 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5001 getF32Constant(DAG, 0x3f317218, dl)); 5002 5003 // Get the significand and build it into a floating-point number with 5004 // exponent of 1. 5005 SDValue X = GetSignificand(DAG, Op1, dl); 5006 5007 SDValue LogOfMantissa; 5008 if (LimitFloatPrecision <= 6) { 5009 // For floating-point precision of 6: 5010 // 5011 // LogofMantissa = 5012 // -1.1609546f + 5013 // (1.4034025f - 0.23903021f * x) * x; 5014 // 5015 // error 0.0034276066, which is better than 8 bits 5016 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5017 getF32Constant(DAG, 0xbe74c456, dl)); 5018 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5019 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5020 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5021 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5022 getF32Constant(DAG, 0x3f949a29, dl)); 5023 } else if (LimitFloatPrecision <= 12) { 5024 // For floating-point precision of 12: 5025 // 5026 // LogOfMantissa = 5027 // -1.7417939f + 5028 // (2.8212026f + 5029 // (-1.4699568f + 5030 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5031 // 5032 // error 0.000061011436, which is 14 bits 5033 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5034 getF32Constant(DAG, 0xbd67b6d6, dl)); 5035 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5036 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5037 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5038 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5039 getF32Constant(DAG, 0x3fbc278b, dl)); 5040 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5041 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5042 getF32Constant(DAG, 0x40348e95, dl)); 5043 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5044 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5045 getF32Constant(DAG, 0x3fdef31a, dl)); 5046 } else { // LimitFloatPrecision <= 18 5047 // For floating-point precision of 18: 5048 // 5049 // LogOfMantissa = 5050 // -2.1072184f + 5051 // (4.2372794f + 5052 // (-3.7029485f + 5053 // (2.2781945f + 5054 // (-0.87823314f + 5055 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5056 // 5057 // error 0.0000023660568, which is better than 18 bits 5058 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5059 getF32Constant(DAG, 0xbc91e5ac, dl)); 5060 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5061 getF32Constant(DAG, 0x3e4350aa, dl)); 5062 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5063 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5064 getF32Constant(DAG, 0x3f60d3e3, dl)); 5065 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5066 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5067 getF32Constant(DAG, 0x4011cdf0, dl)); 5068 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5069 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5070 getF32Constant(DAG, 0x406cfd1c, dl)); 5071 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5072 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5073 getF32Constant(DAG, 0x408797cb, dl)); 5074 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5075 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5076 getF32Constant(DAG, 0x4006dcab, dl)); 5077 } 5078 5079 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5080 } 5081 5082 // No special expansion. 5083 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5084 } 5085 5086 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5087 /// limited-precision mode. 5088 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5089 const TargetLowering &TLI) { 5090 // TODO: What fast-math-flags should be set on the floating-point nodes? 5091 5092 if (Op.getValueType() == MVT::f32 && 5093 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5094 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5095 5096 // Get the exponent. 5097 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5098 5099 // Get the significand and build it into a floating-point number with 5100 // exponent of 1. 5101 SDValue X = GetSignificand(DAG, Op1, dl); 5102 5103 // Different possible minimax approximations of significand in 5104 // floating-point for various degrees of accuracy over [1,2]. 5105 SDValue Log2ofMantissa; 5106 if (LimitFloatPrecision <= 6) { 5107 // For floating-point precision of 6: 5108 // 5109 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5110 // 5111 // error 0.0049451742, which is more than 7 bits 5112 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5113 getF32Constant(DAG, 0xbeb08fe0, dl)); 5114 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5115 getF32Constant(DAG, 0x40019463, dl)); 5116 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5117 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5118 getF32Constant(DAG, 0x3fd6633d, dl)); 5119 } else if (LimitFloatPrecision <= 12) { 5120 // For floating-point precision of 12: 5121 // 5122 // Log2ofMantissa = 5123 // -2.51285454f + 5124 // (4.07009056f + 5125 // (-2.12067489f + 5126 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5127 // 5128 // error 0.0000876136000, which is better than 13 bits 5129 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5130 getF32Constant(DAG, 0xbda7262e, dl)); 5131 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5132 getF32Constant(DAG, 0x3f25280b, dl)); 5133 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5134 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5135 getF32Constant(DAG, 0x4007b923, dl)); 5136 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5137 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5138 getF32Constant(DAG, 0x40823e2f, dl)); 5139 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5140 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5141 getF32Constant(DAG, 0x4020d29c, dl)); 5142 } else { // LimitFloatPrecision <= 18 5143 // For floating-point precision of 18: 5144 // 5145 // Log2ofMantissa = 5146 // -3.0400495f + 5147 // (6.1129976f + 5148 // (-5.3420409f + 5149 // (3.2865683f + 5150 // (-1.2669343f + 5151 // (0.27515199f - 5152 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5153 // 5154 // error 0.0000018516, which is better than 18 bits 5155 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5156 getF32Constant(DAG, 0xbcd2769e, dl)); 5157 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5158 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5159 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5160 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5161 getF32Constant(DAG, 0x3fa22ae7, dl)); 5162 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5163 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5164 getF32Constant(DAG, 0x40525723, dl)); 5165 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5166 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5167 getF32Constant(DAG, 0x40aaf200, dl)); 5168 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5169 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5170 getF32Constant(DAG, 0x40c39dad, dl)); 5171 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5172 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5173 getF32Constant(DAG, 0x4042902c, dl)); 5174 } 5175 5176 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5177 } 5178 5179 // No special expansion. 5180 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5181 } 5182 5183 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5184 /// limited-precision mode. 5185 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5186 const TargetLowering &TLI) { 5187 // TODO: What fast-math-flags should be set on the floating-point nodes? 5188 5189 if (Op.getValueType() == MVT::f32 && 5190 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5191 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5192 5193 // Scale the exponent by log10(2) [0.30102999f]. 5194 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5195 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5196 getF32Constant(DAG, 0x3e9a209a, dl)); 5197 5198 // Get the significand and build it into a floating-point number with 5199 // exponent of 1. 5200 SDValue X = GetSignificand(DAG, Op1, dl); 5201 5202 SDValue Log10ofMantissa; 5203 if (LimitFloatPrecision <= 6) { 5204 // For floating-point precision of 6: 5205 // 5206 // Log10ofMantissa = 5207 // -0.50419619f + 5208 // (0.60948995f - 0.10380950f * x) * x; 5209 // 5210 // error 0.0014886165, which is 6 bits 5211 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5212 getF32Constant(DAG, 0xbdd49a13, dl)); 5213 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5214 getF32Constant(DAG, 0x3f1c0789, dl)); 5215 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5216 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5217 getF32Constant(DAG, 0x3f011300, dl)); 5218 } else if (LimitFloatPrecision <= 12) { 5219 // For floating-point precision of 12: 5220 // 5221 // Log10ofMantissa = 5222 // -0.64831180f + 5223 // (0.91751397f + 5224 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5225 // 5226 // error 0.00019228036, which is better than 12 bits 5227 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5228 getF32Constant(DAG, 0x3d431f31, dl)); 5229 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5230 getF32Constant(DAG, 0x3ea21fb2, dl)); 5231 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5232 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5233 getF32Constant(DAG, 0x3f6ae232, dl)); 5234 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5235 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5236 getF32Constant(DAG, 0x3f25f7c3, dl)); 5237 } else { // LimitFloatPrecision <= 18 5238 // For floating-point precision of 18: 5239 // 5240 // Log10ofMantissa = 5241 // -0.84299375f + 5242 // (1.5327582f + 5243 // (-1.0688956f + 5244 // (0.49102474f + 5245 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5246 // 5247 // error 0.0000037995730, which is better than 18 bits 5248 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5249 getF32Constant(DAG, 0x3c5d51ce, dl)); 5250 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5251 getF32Constant(DAG, 0x3e00685a, dl)); 5252 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5253 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5254 getF32Constant(DAG, 0x3efb6798, dl)); 5255 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5256 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5257 getF32Constant(DAG, 0x3f88d192, dl)); 5258 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5259 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5260 getF32Constant(DAG, 0x3fc4316c, dl)); 5261 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5262 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5263 getF32Constant(DAG, 0x3f57ce70, dl)); 5264 } 5265 5266 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5267 } 5268 5269 // No special expansion. 5270 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5271 } 5272 5273 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5274 /// limited-precision mode. 5275 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5276 const TargetLowering &TLI) { 5277 if (Op.getValueType() == MVT::f32 && 5278 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5279 return getLimitedPrecisionExp2(Op, dl, DAG); 5280 5281 // No special expansion. 5282 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5283 } 5284 5285 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5286 /// limited-precision mode with x == 10.0f. 5287 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5288 SelectionDAG &DAG, const TargetLowering &TLI) { 5289 bool IsExp10 = false; 5290 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5291 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5292 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5293 APFloat Ten(10.0f); 5294 IsExp10 = LHSC->isExactlyValue(Ten); 5295 } 5296 } 5297 5298 // TODO: What fast-math-flags should be set on the FMUL node? 5299 if (IsExp10) { 5300 // Put the exponent in the right bit position for later addition to the 5301 // final result: 5302 // 5303 // #define LOG2OF10 3.3219281f 5304 // t0 = Op * LOG2OF10; 5305 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5306 getF32Constant(DAG, 0x40549a78, dl)); 5307 return getLimitedPrecisionExp2(t0, dl, DAG); 5308 } 5309 5310 // No special expansion. 5311 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5312 } 5313 5314 /// ExpandPowI - Expand a llvm.powi intrinsic. 5315 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5316 SelectionDAG &DAG) { 5317 // If RHS is a constant, we can expand this out to a multiplication tree, 5318 // otherwise we end up lowering to a call to __powidf2 (for example). When 5319 // optimizing for size, we only want to do this if the expansion would produce 5320 // a small number of multiplies, otherwise we do the full expansion. 5321 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5322 // Get the exponent as a positive value. 5323 unsigned Val = RHSC->getSExtValue(); 5324 if ((int)Val < 0) Val = -Val; 5325 5326 // powi(x, 0) -> 1.0 5327 if (Val == 0) 5328 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5329 5330 const Function &F = DAG.getMachineFunction().getFunction(); 5331 if (!F.hasOptSize() || 5332 // If optimizing for size, don't insert too many multiplies. 5333 // This inserts up to 5 multiplies. 5334 countPopulation(Val) + Log2_32(Val) < 7) { 5335 // We use the simple binary decomposition method to generate the multiply 5336 // sequence. There are more optimal ways to do this (for example, 5337 // powi(x,15) generates one more multiply than it should), but this has 5338 // the benefit of being both really simple and much better than a libcall. 5339 SDValue Res; // Logically starts equal to 1.0 5340 SDValue CurSquare = LHS; 5341 // TODO: Intrinsics should have fast-math-flags that propagate to these 5342 // nodes. 5343 while (Val) { 5344 if (Val & 1) { 5345 if (Res.getNode()) 5346 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5347 else 5348 Res = CurSquare; // 1.0*CurSquare. 5349 } 5350 5351 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5352 CurSquare, CurSquare); 5353 Val >>= 1; 5354 } 5355 5356 // If the original was negative, invert the result, producing 1/(x*x*x). 5357 if (RHSC->getSExtValue() < 0) 5358 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5359 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5360 return Res; 5361 } 5362 } 5363 5364 // Otherwise, expand to a libcall. 5365 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5366 } 5367 5368 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5369 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5370 static void 5371 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5372 const SDValue &N) { 5373 switch (N.getOpcode()) { 5374 case ISD::CopyFromReg: { 5375 SDValue Op = N.getOperand(1); 5376 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5377 Op.getValueType().getSizeInBits()); 5378 return; 5379 } 5380 case ISD::BITCAST: 5381 case ISD::AssertZext: 5382 case ISD::AssertSext: 5383 case ISD::TRUNCATE: 5384 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5385 return; 5386 case ISD::BUILD_PAIR: 5387 case ISD::BUILD_VECTOR: 5388 case ISD::CONCAT_VECTORS: 5389 for (SDValue Op : N->op_values()) 5390 getUnderlyingArgRegs(Regs, Op); 5391 return; 5392 default: 5393 return; 5394 } 5395 } 5396 5397 /// If the DbgValueInst is a dbg_value of a function argument, create the 5398 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5399 /// instruction selection, they will be inserted to the entry BB. 5400 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5401 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5402 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5403 const Argument *Arg = dyn_cast<Argument>(V); 5404 if (!Arg) 5405 return false; 5406 5407 if (!IsDbgDeclare) { 5408 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5409 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5410 // the entry block. 5411 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5412 if (!IsInEntryBlock) 5413 return false; 5414 5415 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5416 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5417 // variable that also is a param. 5418 // 5419 // Although, if we are at the top of the entry block already, we can still 5420 // emit using ArgDbgValue. This might catch some situations when the 5421 // dbg.value refers to an argument that isn't used in the entry block, so 5422 // any CopyToReg node would be optimized out and the only way to express 5423 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5424 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5425 // we should only emit as ArgDbgValue if the Variable is an argument to the 5426 // current function, and the dbg.value intrinsic is found in the entry 5427 // block. 5428 bool VariableIsFunctionInputArg = Variable->isParameter() && 5429 !DL->getInlinedAt(); 5430 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5431 if (!IsInPrologue && !VariableIsFunctionInputArg) 5432 return false; 5433 5434 // Here we assume that a function argument on IR level only can be used to 5435 // describe one input parameter on source level. If we for example have 5436 // source code like this 5437 // 5438 // struct A { long x, y; }; 5439 // void foo(struct A a, long b) { 5440 // ... 5441 // b = a.x; 5442 // ... 5443 // } 5444 // 5445 // and IR like this 5446 // 5447 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5448 // entry: 5449 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5450 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5451 // call void @llvm.dbg.value(metadata i32 %b, "b", 5452 // ... 5453 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5454 // ... 5455 // 5456 // then the last dbg.value is describing a parameter "b" using a value that 5457 // is an argument. But since we already has used %a1 to describe a parameter 5458 // we should not handle that last dbg.value here (that would result in an 5459 // incorrect hoisting of the DBG_VALUE to the function entry). 5460 // Notice that we allow one dbg.value per IR level argument, to accomodate 5461 // for the situation with fragments above. 5462 if (VariableIsFunctionInputArg) { 5463 unsigned ArgNo = Arg->getArgNo(); 5464 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5465 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5466 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5467 return false; 5468 FuncInfo.DescribedArgs.set(ArgNo); 5469 } 5470 } 5471 5472 MachineFunction &MF = DAG.getMachineFunction(); 5473 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5474 5475 bool IsIndirect = false; 5476 Optional<MachineOperand> Op; 5477 // Some arguments' frame index is recorded during argument lowering. 5478 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5479 if (FI != std::numeric_limits<int>::max()) 5480 Op = MachineOperand::CreateFI(FI); 5481 5482 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5483 if (!Op && N.getNode()) { 5484 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5485 Register Reg; 5486 if (ArgRegsAndSizes.size() == 1) 5487 Reg = ArgRegsAndSizes.front().first; 5488 5489 if (Reg && Reg.isVirtual()) { 5490 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5491 Register PR = RegInfo.getLiveInPhysReg(Reg); 5492 if (PR) 5493 Reg = PR; 5494 } 5495 if (Reg) { 5496 Op = MachineOperand::CreateReg(Reg, false); 5497 IsIndirect = IsDbgDeclare; 5498 } 5499 } 5500 5501 if (!Op && N.getNode()) { 5502 // Check if frame index is available. 5503 SDValue LCandidate = peekThroughBitcasts(N); 5504 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5505 if (FrameIndexSDNode *FINode = 5506 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5507 Op = MachineOperand::CreateFI(FINode->getIndex()); 5508 } 5509 5510 if (!Op) { 5511 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5512 auto splitMultiRegDbgValue 5513 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5514 unsigned Offset = 0; 5515 for (auto RegAndSize : SplitRegs) { 5516 auto FragmentExpr = DIExpression::createFragmentExpression( 5517 Expr, Offset, RegAndSize.second); 5518 if (!FragmentExpr) 5519 continue; 5520 FuncInfo.ArgDbgValues.push_back( 5521 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5522 RegAndSize.first, Variable, *FragmentExpr)); 5523 Offset += RegAndSize.second; 5524 } 5525 }; 5526 5527 // Check if ValueMap has reg number. 5528 DenseMap<const Value *, unsigned>::const_iterator 5529 VMI = FuncInfo.ValueMap.find(V); 5530 if (VMI != FuncInfo.ValueMap.end()) { 5531 const auto &TLI = DAG.getTargetLoweringInfo(); 5532 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5533 V->getType(), getABIRegCopyCC(V)); 5534 if (RFV.occupiesMultipleRegs()) { 5535 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5536 return true; 5537 } 5538 5539 Op = MachineOperand::CreateReg(VMI->second, false); 5540 IsIndirect = IsDbgDeclare; 5541 } else if (ArgRegsAndSizes.size() > 1) { 5542 // This was split due to the calling convention, and no virtual register 5543 // mapping exists for the value. 5544 splitMultiRegDbgValue(ArgRegsAndSizes); 5545 return true; 5546 } 5547 } 5548 5549 if (!Op) 5550 return false; 5551 5552 assert(Variable->isValidLocationForIntrinsic(DL) && 5553 "Expected inlined-at fields to agree"); 5554 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5555 FuncInfo.ArgDbgValues.push_back( 5556 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5557 *Op, Variable, Expr)); 5558 5559 return true; 5560 } 5561 5562 /// Return the appropriate SDDbgValue based on N. 5563 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5564 DILocalVariable *Variable, 5565 DIExpression *Expr, 5566 const DebugLoc &dl, 5567 unsigned DbgSDNodeOrder) { 5568 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5569 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5570 // stack slot locations. 5571 // 5572 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5573 // debug values here after optimization: 5574 // 5575 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5576 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5577 // 5578 // Both describe the direct values of their associated variables. 5579 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5580 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5581 } 5582 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5583 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5584 } 5585 5586 // VisualStudio defines setjmp as _setjmp 5587 #if defined(_MSC_VER) && defined(setjmp) && \ 5588 !defined(setjmp_undefined_for_msvc) 5589 # pragma push_macro("setjmp") 5590 # undef setjmp 5591 # define setjmp_undefined_for_msvc 5592 #endif 5593 5594 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5595 switch (Intrinsic) { 5596 case Intrinsic::smul_fix: 5597 return ISD::SMULFIX; 5598 case Intrinsic::umul_fix: 5599 return ISD::UMULFIX; 5600 default: 5601 llvm_unreachable("Unhandled fixed point intrinsic"); 5602 } 5603 } 5604 5605 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5606 const char *FunctionName) { 5607 assert(FunctionName && "FunctionName must not be nullptr"); 5608 SDValue Callee = DAG.getExternalSymbol( 5609 FunctionName, 5610 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5611 LowerCallTo(&I, Callee, I.isTailCall()); 5612 } 5613 5614 /// Lower the call to the specified intrinsic function. 5615 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5616 unsigned Intrinsic) { 5617 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5618 SDLoc sdl = getCurSDLoc(); 5619 DebugLoc dl = getCurDebugLoc(); 5620 SDValue Res; 5621 5622 switch (Intrinsic) { 5623 default: 5624 // By default, turn this into a target intrinsic node. 5625 visitTargetIntrinsic(I, Intrinsic); 5626 return; 5627 case Intrinsic::vastart: visitVAStart(I); return; 5628 case Intrinsic::vaend: visitVAEnd(I); return; 5629 case Intrinsic::vacopy: visitVACopy(I); return; 5630 case Intrinsic::returnaddress: 5631 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5632 TLI.getPointerTy(DAG.getDataLayout()), 5633 getValue(I.getArgOperand(0)))); 5634 return; 5635 case Intrinsic::addressofreturnaddress: 5636 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5637 TLI.getPointerTy(DAG.getDataLayout()))); 5638 return; 5639 case Intrinsic::sponentry: 5640 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5641 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5642 return; 5643 case Intrinsic::frameaddress: 5644 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5645 TLI.getFrameIndexTy(DAG.getDataLayout()), 5646 getValue(I.getArgOperand(0)))); 5647 return; 5648 case Intrinsic::read_register: { 5649 Value *Reg = I.getArgOperand(0); 5650 SDValue Chain = getRoot(); 5651 SDValue RegName = 5652 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5653 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5654 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5655 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5656 setValue(&I, Res); 5657 DAG.setRoot(Res.getValue(1)); 5658 return; 5659 } 5660 case Intrinsic::write_register: { 5661 Value *Reg = I.getArgOperand(0); 5662 Value *RegValue = I.getArgOperand(1); 5663 SDValue Chain = getRoot(); 5664 SDValue RegName = 5665 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5666 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5667 RegName, getValue(RegValue))); 5668 return; 5669 } 5670 case Intrinsic::setjmp: 5671 lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]); 5672 return; 5673 case Intrinsic::longjmp: 5674 lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]); 5675 return; 5676 case Intrinsic::memcpy: { 5677 const auto &MCI = cast<MemCpyInst>(I); 5678 SDValue Op1 = getValue(I.getArgOperand(0)); 5679 SDValue Op2 = getValue(I.getArgOperand(1)); 5680 SDValue Op3 = getValue(I.getArgOperand(2)); 5681 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5682 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5683 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5684 unsigned Align = MinAlign(DstAlign, SrcAlign); 5685 bool isVol = MCI.isVolatile(); 5686 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5687 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5688 // node. 5689 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5690 false, isTC, 5691 MachinePointerInfo(I.getArgOperand(0)), 5692 MachinePointerInfo(I.getArgOperand(1))); 5693 updateDAGForMaybeTailCall(MC); 5694 return; 5695 } 5696 case Intrinsic::memset: { 5697 const auto &MSI = cast<MemSetInst>(I); 5698 SDValue Op1 = getValue(I.getArgOperand(0)); 5699 SDValue Op2 = getValue(I.getArgOperand(1)); 5700 SDValue Op3 = getValue(I.getArgOperand(2)); 5701 // @llvm.memset defines 0 and 1 to both mean no alignment. 5702 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5703 bool isVol = MSI.isVolatile(); 5704 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5705 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5706 isTC, MachinePointerInfo(I.getArgOperand(0))); 5707 updateDAGForMaybeTailCall(MS); 5708 return; 5709 } 5710 case Intrinsic::memmove: { 5711 const auto &MMI = cast<MemMoveInst>(I); 5712 SDValue Op1 = getValue(I.getArgOperand(0)); 5713 SDValue Op2 = getValue(I.getArgOperand(1)); 5714 SDValue Op3 = getValue(I.getArgOperand(2)); 5715 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5716 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5717 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5718 unsigned Align = MinAlign(DstAlign, SrcAlign); 5719 bool isVol = MMI.isVolatile(); 5720 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5721 // FIXME: Support passing different dest/src alignments to the memmove DAG 5722 // node. 5723 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5724 isTC, MachinePointerInfo(I.getArgOperand(0)), 5725 MachinePointerInfo(I.getArgOperand(1))); 5726 updateDAGForMaybeTailCall(MM); 5727 return; 5728 } 5729 case Intrinsic::memcpy_element_unordered_atomic: { 5730 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5731 SDValue Dst = getValue(MI.getRawDest()); 5732 SDValue Src = getValue(MI.getRawSource()); 5733 SDValue Length = getValue(MI.getLength()); 5734 5735 unsigned DstAlign = MI.getDestAlignment(); 5736 unsigned SrcAlign = MI.getSourceAlignment(); 5737 Type *LengthTy = MI.getLength()->getType(); 5738 unsigned ElemSz = MI.getElementSizeInBytes(); 5739 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5740 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5741 SrcAlign, Length, LengthTy, ElemSz, isTC, 5742 MachinePointerInfo(MI.getRawDest()), 5743 MachinePointerInfo(MI.getRawSource())); 5744 updateDAGForMaybeTailCall(MC); 5745 return; 5746 } 5747 case Intrinsic::memmove_element_unordered_atomic: { 5748 auto &MI = cast<AtomicMemMoveInst>(I); 5749 SDValue Dst = getValue(MI.getRawDest()); 5750 SDValue Src = getValue(MI.getRawSource()); 5751 SDValue Length = getValue(MI.getLength()); 5752 5753 unsigned DstAlign = MI.getDestAlignment(); 5754 unsigned SrcAlign = MI.getSourceAlignment(); 5755 Type *LengthTy = MI.getLength()->getType(); 5756 unsigned ElemSz = MI.getElementSizeInBytes(); 5757 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5758 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5759 SrcAlign, Length, LengthTy, ElemSz, isTC, 5760 MachinePointerInfo(MI.getRawDest()), 5761 MachinePointerInfo(MI.getRawSource())); 5762 updateDAGForMaybeTailCall(MC); 5763 return; 5764 } 5765 case Intrinsic::memset_element_unordered_atomic: { 5766 auto &MI = cast<AtomicMemSetInst>(I); 5767 SDValue Dst = getValue(MI.getRawDest()); 5768 SDValue Val = getValue(MI.getValue()); 5769 SDValue Length = getValue(MI.getLength()); 5770 5771 unsigned DstAlign = MI.getDestAlignment(); 5772 Type *LengthTy = MI.getLength()->getType(); 5773 unsigned ElemSz = MI.getElementSizeInBytes(); 5774 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5775 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5776 LengthTy, ElemSz, isTC, 5777 MachinePointerInfo(MI.getRawDest())); 5778 updateDAGForMaybeTailCall(MC); 5779 return; 5780 } 5781 case Intrinsic::dbg_addr: 5782 case Intrinsic::dbg_declare: { 5783 const auto &DI = cast<DbgVariableIntrinsic>(I); 5784 DILocalVariable *Variable = DI.getVariable(); 5785 DIExpression *Expression = DI.getExpression(); 5786 dropDanglingDebugInfo(Variable, Expression); 5787 assert(Variable && "Missing variable"); 5788 5789 // Check if address has undef value. 5790 const Value *Address = DI.getVariableLocation(); 5791 if (!Address || isa<UndefValue>(Address) || 5792 (Address->use_empty() && !isa<Argument>(Address))) { 5793 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5794 return; 5795 } 5796 5797 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5798 5799 // Check if this variable can be described by a frame index, typically 5800 // either as a static alloca or a byval parameter. 5801 int FI = std::numeric_limits<int>::max(); 5802 if (const auto *AI = 5803 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5804 if (AI->isStaticAlloca()) { 5805 auto I = FuncInfo.StaticAllocaMap.find(AI); 5806 if (I != FuncInfo.StaticAllocaMap.end()) 5807 FI = I->second; 5808 } 5809 } else if (const auto *Arg = dyn_cast<Argument>( 5810 Address->stripInBoundsConstantOffsets())) { 5811 FI = FuncInfo.getArgumentFrameIndex(Arg); 5812 } 5813 5814 // llvm.dbg.addr is control dependent and always generates indirect 5815 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5816 // the MachineFunction variable table. 5817 if (FI != std::numeric_limits<int>::max()) { 5818 if (Intrinsic == Intrinsic::dbg_addr) { 5819 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5820 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5821 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5822 } 5823 return; 5824 } 5825 5826 SDValue &N = NodeMap[Address]; 5827 if (!N.getNode() && isa<Argument>(Address)) 5828 // Check unused arguments map. 5829 N = UnusedArgNodeMap[Address]; 5830 SDDbgValue *SDV; 5831 if (N.getNode()) { 5832 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5833 Address = BCI->getOperand(0); 5834 // Parameters are handled specially. 5835 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5836 if (isParameter && FINode) { 5837 // Byval parameter. We have a frame index at this point. 5838 SDV = 5839 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5840 /*IsIndirect*/ true, dl, SDNodeOrder); 5841 } else if (isa<Argument>(Address)) { 5842 // Address is an argument, so try to emit its dbg value using 5843 // virtual register info from the FuncInfo.ValueMap. 5844 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5845 return; 5846 } else { 5847 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5848 true, dl, SDNodeOrder); 5849 } 5850 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5851 } else { 5852 // If Address is an argument then try to emit its dbg value using 5853 // virtual register info from the FuncInfo.ValueMap. 5854 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5855 N)) { 5856 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5857 } 5858 } 5859 return; 5860 } 5861 case Intrinsic::dbg_label: { 5862 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5863 DILabel *Label = DI.getLabel(); 5864 assert(Label && "Missing label"); 5865 5866 SDDbgLabel *SDV; 5867 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5868 DAG.AddDbgLabel(SDV); 5869 return; 5870 } 5871 case Intrinsic::dbg_value: { 5872 const DbgValueInst &DI = cast<DbgValueInst>(I); 5873 assert(DI.getVariable() && "Missing variable"); 5874 5875 DILocalVariable *Variable = DI.getVariable(); 5876 DIExpression *Expression = DI.getExpression(); 5877 dropDanglingDebugInfo(Variable, Expression); 5878 const Value *V = DI.getValue(); 5879 if (!V) 5880 return; 5881 5882 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5883 SDNodeOrder)) 5884 return; 5885 5886 // TODO: Dangling debug info will eventually either be resolved or produce 5887 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5888 // between the original dbg.value location and its resolved DBG_VALUE, which 5889 // we should ideally fill with an extra Undef DBG_VALUE. 5890 5891 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5892 return; 5893 } 5894 5895 case Intrinsic::eh_typeid_for: { 5896 // Find the type id for the given typeinfo. 5897 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5898 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5899 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5900 setValue(&I, Res); 5901 return; 5902 } 5903 5904 case Intrinsic::eh_return_i32: 5905 case Intrinsic::eh_return_i64: 5906 DAG.getMachineFunction().setCallsEHReturn(true); 5907 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5908 MVT::Other, 5909 getControlRoot(), 5910 getValue(I.getArgOperand(0)), 5911 getValue(I.getArgOperand(1)))); 5912 return; 5913 case Intrinsic::eh_unwind_init: 5914 DAG.getMachineFunction().setCallsUnwindInit(true); 5915 return; 5916 case Intrinsic::eh_dwarf_cfa: 5917 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5918 TLI.getPointerTy(DAG.getDataLayout()), 5919 getValue(I.getArgOperand(0)))); 5920 return; 5921 case Intrinsic::eh_sjlj_callsite: { 5922 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5923 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5924 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5925 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5926 5927 MMI.setCurrentCallSite(CI->getZExtValue()); 5928 return; 5929 } 5930 case Intrinsic::eh_sjlj_functioncontext: { 5931 // Get and store the index of the function context. 5932 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5933 AllocaInst *FnCtx = 5934 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5935 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5936 MFI.setFunctionContextIndex(FI); 5937 return; 5938 } 5939 case Intrinsic::eh_sjlj_setjmp: { 5940 SDValue Ops[2]; 5941 Ops[0] = getRoot(); 5942 Ops[1] = getValue(I.getArgOperand(0)); 5943 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5944 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5945 setValue(&I, Op.getValue(0)); 5946 DAG.setRoot(Op.getValue(1)); 5947 return; 5948 } 5949 case Intrinsic::eh_sjlj_longjmp: 5950 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5951 getRoot(), getValue(I.getArgOperand(0)))); 5952 return; 5953 case Intrinsic::eh_sjlj_setup_dispatch: 5954 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5955 getRoot())); 5956 return; 5957 case Intrinsic::masked_gather: 5958 visitMaskedGather(I); 5959 return; 5960 case Intrinsic::masked_load: 5961 visitMaskedLoad(I); 5962 return; 5963 case Intrinsic::masked_scatter: 5964 visitMaskedScatter(I); 5965 return; 5966 case Intrinsic::masked_store: 5967 visitMaskedStore(I); 5968 return; 5969 case Intrinsic::masked_expandload: 5970 visitMaskedLoad(I, true /* IsExpanding */); 5971 return; 5972 case Intrinsic::masked_compressstore: 5973 visitMaskedStore(I, true /* IsCompressing */); 5974 return; 5975 case Intrinsic::powi: 5976 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5977 getValue(I.getArgOperand(1)), DAG)); 5978 return; 5979 case Intrinsic::log: 5980 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5981 return; 5982 case Intrinsic::log2: 5983 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5984 return; 5985 case Intrinsic::log10: 5986 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5987 return; 5988 case Intrinsic::exp: 5989 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5990 return; 5991 case Intrinsic::exp2: 5992 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5993 return; 5994 case Intrinsic::pow: 5995 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5996 getValue(I.getArgOperand(1)), DAG, TLI)); 5997 return; 5998 case Intrinsic::sqrt: 5999 case Intrinsic::fabs: 6000 case Intrinsic::sin: 6001 case Intrinsic::cos: 6002 case Intrinsic::floor: 6003 case Intrinsic::ceil: 6004 case Intrinsic::trunc: 6005 case Intrinsic::rint: 6006 case Intrinsic::nearbyint: 6007 case Intrinsic::round: 6008 case Intrinsic::canonicalize: { 6009 unsigned Opcode; 6010 switch (Intrinsic) { 6011 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6012 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6013 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6014 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6015 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6016 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6017 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6018 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6019 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6020 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6021 case Intrinsic::round: Opcode = ISD::FROUND; break; 6022 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6023 } 6024 6025 setValue(&I, DAG.getNode(Opcode, sdl, 6026 getValue(I.getArgOperand(0)).getValueType(), 6027 getValue(I.getArgOperand(0)))); 6028 return; 6029 } 6030 case Intrinsic::lround: 6031 case Intrinsic::llround: 6032 case Intrinsic::lrint: 6033 case Intrinsic::llrint: { 6034 unsigned Opcode; 6035 switch (Intrinsic) { 6036 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6037 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6038 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6039 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6040 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6041 } 6042 6043 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6044 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6045 getValue(I.getArgOperand(0)))); 6046 return; 6047 } 6048 case Intrinsic::minnum: 6049 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6050 getValue(I.getArgOperand(0)).getValueType(), 6051 getValue(I.getArgOperand(0)), 6052 getValue(I.getArgOperand(1)))); 6053 return; 6054 case Intrinsic::maxnum: 6055 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6056 getValue(I.getArgOperand(0)).getValueType(), 6057 getValue(I.getArgOperand(0)), 6058 getValue(I.getArgOperand(1)))); 6059 return; 6060 case Intrinsic::minimum: 6061 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6062 getValue(I.getArgOperand(0)).getValueType(), 6063 getValue(I.getArgOperand(0)), 6064 getValue(I.getArgOperand(1)))); 6065 return; 6066 case Intrinsic::maximum: 6067 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6068 getValue(I.getArgOperand(0)).getValueType(), 6069 getValue(I.getArgOperand(0)), 6070 getValue(I.getArgOperand(1)))); 6071 return; 6072 case Intrinsic::copysign: 6073 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6074 getValue(I.getArgOperand(0)).getValueType(), 6075 getValue(I.getArgOperand(0)), 6076 getValue(I.getArgOperand(1)))); 6077 return; 6078 case Intrinsic::fma: 6079 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6080 getValue(I.getArgOperand(0)).getValueType(), 6081 getValue(I.getArgOperand(0)), 6082 getValue(I.getArgOperand(1)), 6083 getValue(I.getArgOperand(2)))); 6084 return; 6085 case Intrinsic::experimental_constrained_fadd: 6086 case Intrinsic::experimental_constrained_fsub: 6087 case Intrinsic::experimental_constrained_fmul: 6088 case Intrinsic::experimental_constrained_fdiv: 6089 case Intrinsic::experimental_constrained_frem: 6090 case Intrinsic::experimental_constrained_fma: 6091 case Intrinsic::experimental_constrained_fptosi: 6092 case Intrinsic::experimental_constrained_fptoui: 6093 case Intrinsic::experimental_constrained_fptrunc: 6094 case Intrinsic::experimental_constrained_fpext: 6095 case Intrinsic::experimental_constrained_sqrt: 6096 case Intrinsic::experimental_constrained_pow: 6097 case Intrinsic::experimental_constrained_powi: 6098 case Intrinsic::experimental_constrained_sin: 6099 case Intrinsic::experimental_constrained_cos: 6100 case Intrinsic::experimental_constrained_exp: 6101 case Intrinsic::experimental_constrained_exp2: 6102 case Intrinsic::experimental_constrained_log: 6103 case Intrinsic::experimental_constrained_log10: 6104 case Intrinsic::experimental_constrained_log2: 6105 case Intrinsic::experimental_constrained_rint: 6106 case Intrinsic::experimental_constrained_nearbyint: 6107 case Intrinsic::experimental_constrained_maxnum: 6108 case Intrinsic::experimental_constrained_minnum: 6109 case Intrinsic::experimental_constrained_ceil: 6110 case Intrinsic::experimental_constrained_floor: 6111 case Intrinsic::experimental_constrained_round: 6112 case Intrinsic::experimental_constrained_trunc: 6113 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6114 return; 6115 case Intrinsic::fmuladd: { 6116 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6117 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6118 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 6119 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6120 getValue(I.getArgOperand(0)).getValueType(), 6121 getValue(I.getArgOperand(0)), 6122 getValue(I.getArgOperand(1)), 6123 getValue(I.getArgOperand(2)))); 6124 } else { 6125 // TODO: Intrinsic calls should have fast-math-flags. 6126 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6127 getValue(I.getArgOperand(0)).getValueType(), 6128 getValue(I.getArgOperand(0)), 6129 getValue(I.getArgOperand(1))); 6130 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6131 getValue(I.getArgOperand(0)).getValueType(), 6132 Mul, 6133 getValue(I.getArgOperand(2))); 6134 setValue(&I, Add); 6135 } 6136 return; 6137 } 6138 case Intrinsic::convert_to_fp16: 6139 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6140 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6141 getValue(I.getArgOperand(0)), 6142 DAG.getTargetConstant(0, sdl, 6143 MVT::i32)))); 6144 return; 6145 case Intrinsic::convert_from_fp16: 6146 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6147 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6148 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6149 getValue(I.getArgOperand(0))))); 6150 return; 6151 case Intrinsic::pcmarker: { 6152 SDValue Tmp = getValue(I.getArgOperand(0)); 6153 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6154 return; 6155 } 6156 case Intrinsic::readcyclecounter: { 6157 SDValue Op = getRoot(); 6158 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6159 DAG.getVTList(MVT::i64, MVT::Other), Op); 6160 setValue(&I, Res); 6161 DAG.setRoot(Res.getValue(1)); 6162 return; 6163 } 6164 case Intrinsic::bitreverse: 6165 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6166 getValue(I.getArgOperand(0)).getValueType(), 6167 getValue(I.getArgOperand(0)))); 6168 return; 6169 case Intrinsic::bswap: 6170 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6171 getValue(I.getArgOperand(0)).getValueType(), 6172 getValue(I.getArgOperand(0)))); 6173 return; 6174 case Intrinsic::cttz: { 6175 SDValue Arg = getValue(I.getArgOperand(0)); 6176 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6177 EVT Ty = Arg.getValueType(); 6178 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6179 sdl, Ty, Arg)); 6180 return; 6181 } 6182 case Intrinsic::ctlz: { 6183 SDValue Arg = getValue(I.getArgOperand(0)); 6184 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6185 EVT Ty = Arg.getValueType(); 6186 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6187 sdl, Ty, Arg)); 6188 return; 6189 } 6190 case Intrinsic::ctpop: { 6191 SDValue Arg = getValue(I.getArgOperand(0)); 6192 EVT Ty = Arg.getValueType(); 6193 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6194 return; 6195 } 6196 case Intrinsic::fshl: 6197 case Intrinsic::fshr: { 6198 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6199 SDValue X = getValue(I.getArgOperand(0)); 6200 SDValue Y = getValue(I.getArgOperand(1)); 6201 SDValue Z = getValue(I.getArgOperand(2)); 6202 EVT VT = X.getValueType(); 6203 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6204 SDValue Zero = DAG.getConstant(0, sdl, VT); 6205 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6206 6207 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6208 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6209 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6210 return; 6211 } 6212 6213 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6214 // avoid the select that is necessary in the general case to filter out 6215 // the 0-shift possibility that leads to UB. 6216 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6217 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6218 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6219 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6220 return; 6221 } 6222 6223 // Some targets only rotate one way. Try the opposite direction. 6224 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6225 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6226 // Negate the shift amount because it is safe to ignore the high bits. 6227 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6228 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6229 return; 6230 } 6231 6232 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6233 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6234 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6235 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6236 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6237 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6238 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6239 return; 6240 } 6241 6242 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6243 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6244 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6245 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6246 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6247 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6248 6249 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6250 // and that is undefined. We must compare and select to avoid UB. 6251 EVT CCVT = MVT::i1; 6252 if (VT.isVector()) 6253 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6254 6255 // For fshl, 0-shift returns the 1st arg (X). 6256 // For fshr, 0-shift returns the 2nd arg (Y). 6257 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6258 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6259 return; 6260 } 6261 case Intrinsic::sadd_sat: { 6262 SDValue Op1 = getValue(I.getArgOperand(0)); 6263 SDValue Op2 = getValue(I.getArgOperand(1)); 6264 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6265 return; 6266 } 6267 case Intrinsic::uadd_sat: { 6268 SDValue Op1 = getValue(I.getArgOperand(0)); 6269 SDValue Op2 = getValue(I.getArgOperand(1)); 6270 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6271 return; 6272 } 6273 case Intrinsic::ssub_sat: { 6274 SDValue Op1 = getValue(I.getArgOperand(0)); 6275 SDValue Op2 = getValue(I.getArgOperand(1)); 6276 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6277 return; 6278 } 6279 case Intrinsic::usub_sat: { 6280 SDValue Op1 = getValue(I.getArgOperand(0)); 6281 SDValue Op2 = getValue(I.getArgOperand(1)); 6282 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6283 return; 6284 } 6285 case Intrinsic::smul_fix: 6286 case Intrinsic::umul_fix: { 6287 SDValue Op1 = getValue(I.getArgOperand(0)); 6288 SDValue Op2 = getValue(I.getArgOperand(1)); 6289 SDValue Op3 = getValue(I.getArgOperand(2)); 6290 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6291 Op1.getValueType(), Op1, Op2, Op3)); 6292 return; 6293 } 6294 case Intrinsic::smul_fix_sat: { 6295 SDValue Op1 = getValue(I.getArgOperand(0)); 6296 SDValue Op2 = getValue(I.getArgOperand(1)); 6297 SDValue Op3 = getValue(I.getArgOperand(2)); 6298 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6299 Op3)); 6300 return; 6301 } 6302 case Intrinsic::umul_fix_sat: { 6303 SDValue Op1 = getValue(I.getArgOperand(0)); 6304 SDValue Op2 = getValue(I.getArgOperand(1)); 6305 SDValue Op3 = getValue(I.getArgOperand(2)); 6306 setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6307 Op3)); 6308 return; 6309 } 6310 case Intrinsic::stacksave: { 6311 SDValue Op = getRoot(); 6312 Res = DAG.getNode( 6313 ISD::STACKSAVE, sdl, 6314 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6315 setValue(&I, Res); 6316 DAG.setRoot(Res.getValue(1)); 6317 return; 6318 } 6319 case Intrinsic::stackrestore: 6320 Res = getValue(I.getArgOperand(0)); 6321 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6322 return; 6323 case Intrinsic::get_dynamic_area_offset: { 6324 SDValue Op = getRoot(); 6325 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6326 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6327 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6328 // target. 6329 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6330 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6331 " intrinsic!"); 6332 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6333 Op); 6334 DAG.setRoot(Op); 6335 setValue(&I, Res); 6336 return; 6337 } 6338 case Intrinsic::stackguard: { 6339 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6340 MachineFunction &MF = DAG.getMachineFunction(); 6341 const Module &M = *MF.getFunction().getParent(); 6342 SDValue Chain = getRoot(); 6343 if (TLI.useLoadStackGuardNode()) { 6344 Res = getLoadStackGuard(DAG, sdl, Chain); 6345 } else { 6346 const Value *Global = TLI.getSDagStackGuard(M); 6347 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6348 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6349 MachinePointerInfo(Global, 0), Align, 6350 MachineMemOperand::MOVolatile); 6351 } 6352 if (TLI.useStackGuardXorFP()) 6353 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6354 DAG.setRoot(Chain); 6355 setValue(&I, Res); 6356 return; 6357 } 6358 case Intrinsic::stackprotector: { 6359 // Emit code into the DAG to store the stack guard onto the stack. 6360 MachineFunction &MF = DAG.getMachineFunction(); 6361 MachineFrameInfo &MFI = MF.getFrameInfo(); 6362 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6363 SDValue Src, Chain = getRoot(); 6364 6365 if (TLI.useLoadStackGuardNode()) 6366 Src = getLoadStackGuard(DAG, sdl, Chain); 6367 else 6368 Src = getValue(I.getArgOperand(0)); // The guard's value. 6369 6370 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6371 6372 int FI = FuncInfo.StaticAllocaMap[Slot]; 6373 MFI.setStackProtectorIndex(FI); 6374 6375 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6376 6377 // Store the stack protector onto the stack. 6378 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6379 DAG.getMachineFunction(), FI), 6380 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6381 setValue(&I, Res); 6382 DAG.setRoot(Res); 6383 return; 6384 } 6385 case Intrinsic::objectsize: { 6386 // If we don't know by now, we're never going to know. 6387 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 6388 6389 assert(CI && "Non-constant type in __builtin_object_size?"); 6390 6391 SDValue Arg = getValue(I.getCalledValue()); 6392 EVT Ty = Arg.getValueType(); 6393 6394 if (CI->isZero()) 6395 Res = DAG.getConstant(-1ULL, sdl, Ty); 6396 else 6397 Res = DAG.getConstant(0, sdl, Ty); 6398 6399 setValue(&I, Res); 6400 return; 6401 } 6402 6403 case Intrinsic::is_constant: 6404 // If this wasn't constant-folded away by now, then it's not a 6405 // constant. 6406 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 6407 return; 6408 6409 case Intrinsic::annotation: 6410 case Intrinsic::ptr_annotation: 6411 case Intrinsic::launder_invariant_group: 6412 case Intrinsic::strip_invariant_group: 6413 // Drop the intrinsic, but forward the value 6414 setValue(&I, getValue(I.getOperand(0))); 6415 return; 6416 case Intrinsic::assume: 6417 case Intrinsic::var_annotation: 6418 case Intrinsic::sideeffect: 6419 // Discard annotate attributes, assumptions, and artificial side-effects. 6420 return; 6421 6422 case Intrinsic::codeview_annotation: { 6423 // Emit a label associated with this metadata. 6424 MachineFunction &MF = DAG.getMachineFunction(); 6425 MCSymbol *Label = 6426 MF.getMMI().getContext().createTempSymbol("annotation", true); 6427 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6428 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6429 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6430 DAG.setRoot(Res); 6431 return; 6432 } 6433 6434 case Intrinsic::init_trampoline: { 6435 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6436 6437 SDValue Ops[6]; 6438 Ops[0] = getRoot(); 6439 Ops[1] = getValue(I.getArgOperand(0)); 6440 Ops[2] = getValue(I.getArgOperand(1)); 6441 Ops[3] = getValue(I.getArgOperand(2)); 6442 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6443 Ops[5] = DAG.getSrcValue(F); 6444 6445 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6446 6447 DAG.setRoot(Res); 6448 return; 6449 } 6450 case Intrinsic::adjust_trampoline: 6451 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6452 TLI.getPointerTy(DAG.getDataLayout()), 6453 getValue(I.getArgOperand(0)))); 6454 return; 6455 case Intrinsic::gcroot: { 6456 assert(DAG.getMachineFunction().getFunction().hasGC() && 6457 "only valid in functions with gc specified, enforced by Verifier"); 6458 assert(GFI && "implied by previous"); 6459 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6460 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6461 6462 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6463 GFI->addStackRoot(FI->getIndex(), TypeMap); 6464 return; 6465 } 6466 case Intrinsic::gcread: 6467 case Intrinsic::gcwrite: 6468 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6469 case Intrinsic::flt_rounds: 6470 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6471 return; 6472 6473 case Intrinsic::expect: 6474 // Just replace __builtin_expect(exp, c) with EXP. 6475 setValue(&I, getValue(I.getArgOperand(0))); 6476 return; 6477 6478 case Intrinsic::debugtrap: 6479 case Intrinsic::trap: { 6480 StringRef TrapFuncName = 6481 I.getAttributes() 6482 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6483 .getValueAsString(); 6484 if (TrapFuncName.empty()) { 6485 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6486 ISD::TRAP : ISD::DEBUGTRAP; 6487 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6488 return; 6489 } 6490 TargetLowering::ArgListTy Args; 6491 6492 TargetLowering::CallLoweringInfo CLI(DAG); 6493 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6494 CallingConv::C, I.getType(), 6495 DAG.getExternalSymbol(TrapFuncName.data(), 6496 TLI.getPointerTy(DAG.getDataLayout())), 6497 std::move(Args)); 6498 6499 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6500 DAG.setRoot(Result.second); 6501 return; 6502 } 6503 6504 case Intrinsic::uadd_with_overflow: 6505 case Intrinsic::sadd_with_overflow: 6506 case Intrinsic::usub_with_overflow: 6507 case Intrinsic::ssub_with_overflow: 6508 case Intrinsic::umul_with_overflow: 6509 case Intrinsic::smul_with_overflow: { 6510 ISD::NodeType Op; 6511 switch (Intrinsic) { 6512 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6513 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6514 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6515 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6516 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6517 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6518 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6519 } 6520 SDValue Op1 = getValue(I.getArgOperand(0)); 6521 SDValue Op2 = getValue(I.getArgOperand(1)); 6522 6523 EVT ResultVT = Op1.getValueType(); 6524 EVT OverflowVT = MVT::i1; 6525 if (ResultVT.isVector()) 6526 OverflowVT = EVT::getVectorVT( 6527 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6528 6529 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6530 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6531 return; 6532 } 6533 case Intrinsic::prefetch: { 6534 SDValue Ops[5]; 6535 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6536 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6537 Ops[0] = DAG.getRoot(); 6538 Ops[1] = getValue(I.getArgOperand(0)); 6539 Ops[2] = getValue(I.getArgOperand(1)); 6540 Ops[3] = getValue(I.getArgOperand(2)); 6541 Ops[4] = getValue(I.getArgOperand(3)); 6542 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6543 DAG.getVTList(MVT::Other), Ops, 6544 EVT::getIntegerVT(*Context, 8), 6545 MachinePointerInfo(I.getArgOperand(0)), 6546 0, /* align */ 6547 Flags); 6548 6549 // Chain the prefetch in parallell with any pending loads, to stay out of 6550 // the way of later optimizations. 6551 PendingLoads.push_back(Result); 6552 Result = getRoot(); 6553 DAG.setRoot(Result); 6554 return; 6555 } 6556 case Intrinsic::lifetime_start: 6557 case Intrinsic::lifetime_end: { 6558 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6559 // Stack coloring is not enabled in O0, discard region information. 6560 if (TM.getOptLevel() == CodeGenOpt::None) 6561 return; 6562 6563 const int64_t ObjectSize = 6564 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6565 Value *const ObjectPtr = I.getArgOperand(1); 6566 SmallVector<const Value *, 4> Allocas; 6567 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6568 6569 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6570 E = Allocas.end(); Object != E; ++Object) { 6571 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6572 6573 // Could not find an Alloca. 6574 if (!LifetimeObject) 6575 continue; 6576 6577 // First check that the Alloca is static, otherwise it won't have a 6578 // valid frame index. 6579 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6580 if (SI == FuncInfo.StaticAllocaMap.end()) 6581 return; 6582 6583 const int FrameIndex = SI->second; 6584 int64_t Offset; 6585 if (GetPointerBaseWithConstantOffset( 6586 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6587 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6588 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6589 Offset); 6590 DAG.setRoot(Res); 6591 } 6592 return; 6593 } 6594 case Intrinsic::invariant_start: 6595 // Discard region information. 6596 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6597 return; 6598 case Intrinsic::invariant_end: 6599 // Discard region information. 6600 return; 6601 case Intrinsic::clear_cache: 6602 /// FunctionName may be null. 6603 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6604 lowerCallToExternalSymbol(I, FunctionName); 6605 return; 6606 case Intrinsic::donothing: 6607 // ignore 6608 return; 6609 case Intrinsic::experimental_stackmap: 6610 visitStackmap(I); 6611 return; 6612 case Intrinsic::experimental_patchpoint_void: 6613 case Intrinsic::experimental_patchpoint_i64: 6614 visitPatchpoint(&I); 6615 return; 6616 case Intrinsic::experimental_gc_statepoint: 6617 LowerStatepoint(ImmutableStatepoint(&I)); 6618 return; 6619 case Intrinsic::experimental_gc_result: 6620 visitGCResult(cast<GCResultInst>(I)); 6621 return; 6622 case Intrinsic::experimental_gc_relocate: 6623 visitGCRelocate(cast<GCRelocateInst>(I)); 6624 return; 6625 case Intrinsic::instrprof_increment: 6626 llvm_unreachable("instrprof failed to lower an increment"); 6627 case Intrinsic::instrprof_value_profile: 6628 llvm_unreachable("instrprof failed to lower a value profiling call"); 6629 case Intrinsic::localescape: { 6630 MachineFunction &MF = DAG.getMachineFunction(); 6631 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6632 6633 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6634 // is the same on all targets. 6635 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6636 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6637 if (isa<ConstantPointerNull>(Arg)) 6638 continue; // Skip null pointers. They represent a hole in index space. 6639 AllocaInst *Slot = cast<AllocaInst>(Arg); 6640 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6641 "can only escape static allocas"); 6642 int FI = FuncInfo.StaticAllocaMap[Slot]; 6643 MCSymbol *FrameAllocSym = 6644 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6645 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6646 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6647 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6648 .addSym(FrameAllocSym) 6649 .addFrameIndex(FI); 6650 } 6651 6652 return; 6653 } 6654 6655 case Intrinsic::localrecover: { 6656 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6657 MachineFunction &MF = DAG.getMachineFunction(); 6658 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6659 6660 // Get the symbol that defines the frame offset. 6661 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6662 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6663 unsigned IdxVal = 6664 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6665 MCSymbol *FrameAllocSym = 6666 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6667 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6668 6669 // Create a MCSymbol for the label to avoid any target lowering 6670 // that would make this PC relative. 6671 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6672 SDValue OffsetVal = 6673 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6674 6675 // Add the offset to the FP. 6676 Value *FP = I.getArgOperand(1); 6677 SDValue FPVal = getValue(FP); 6678 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6679 setValue(&I, Add); 6680 6681 return; 6682 } 6683 6684 case Intrinsic::eh_exceptionpointer: 6685 case Intrinsic::eh_exceptioncode: { 6686 // Get the exception pointer vreg, copy from it, and resize it to fit. 6687 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6688 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6689 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6690 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6691 SDValue N = 6692 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6693 if (Intrinsic == Intrinsic::eh_exceptioncode) 6694 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6695 setValue(&I, N); 6696 return; 6697 } 6698 case Intrinsic::xray_customevent: { 6699 // Here we want to make sure that the intrinsic behaves as if it has a 6700 // specific calling convention, and only for x86_64. 6701 // FIXME: Support other platforms later. 6702 const auto &Triple = DAG.getTarget().getTargetTriple(); 6703 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6704 return; 6705 6706 SDLoc DL = getCurSDLoc(); 6707 SmallVector<SDValue, 8> Ops; 6708 6709 // We want to say that we always want the arguments in registers. 6710 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6711 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6712 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6713 SDValue Chain = getRoot(); 6714 Ops.push_back(LogEntryVal); 6715 Ops.push_back(StrSizeVal); 6716 Ops.push_back(Chain); 6717 6718 // We need to enforce the calling convention for the callsite, so that 6719 // argument ordering is enforced correctly, and that register allocation can 6720 // see that some registers may be assumed clobbered and have to preserve 6721 // them across calls to the intrinsic. 6722 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6723 DL, NodeTys, Ops); 6724 SDValue patchableNode = SDValue(MN, 0); 6725 DAG.setRoot(patchableNode); 6726 setValue(&I, patchableNode); 6727 return; 6728 } 6729 case Intrinsic::xray_typedevent: { 6730 // Here we want to make sure that the intrinsic behaves as if it has a 6731 // specific calling convention, and only for x86_64. 6732 // FIXME: Support other platforms later. 6733 const auto &Triple = DAG.getTarget().getTargetTriple(); 6734 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6735 return; 6736 6737 SDLoc DL = getCurSDLoc(); 6738 SmallVector<SDValue, 8> Ops; 6739 6740 // We want to say that we always want the arguments in registers. 6741 // It's unclear to me how manipulating the selection DAG here forces callers 6742 // to provide arguments in registers instead of on the stack. 6743 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6744 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6745 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6746 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6747 SDValue Chain = getRoot(); 6748 Ops.push_back(LogTypeId); 6749 Ops.push_back(LogEntryVal); 6750 Ops.push_back(StrSizeVal); 6751 Ops.push_back(Chain); 6752 6753 // We need to enforce the calling convention for the callsite, so that 6754 // argument ordering is enforced correctly, and that register allocation can 6755 // see that some registers may be assumed clobbered and have to preserve 6756 // them across calls to the intrinsic. 6757 MachineSDNode *MN = DAG.getMachineNode( 6758 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6759 SDValue patchableNode = SDValue(MN, 0); 6760 DAG.setRoot(patchableNode); 6761 setValue(&I, patchableNode); 6762 return; 6763 } 6764 case Intrinsic::experimental_deoptimize: 6765 LowerDeoptimizeCall(&I); 6766 return; 6767 6768 case Intrinsic::experimental_vector_reduce_v2_fadd: 6769 case Intrinsic::experimental_vector_reduce_v2_fmul: 6770 case Intrinsic::experimental_vector_reduce_add: 6771 case Intrinsic::experimental_vector_reduce_mul: 6772 case Intrinsic::experimental_vector_reduce_and: 6773 case Intrinsic::experimental_vector_reduce_or: 6774 case Intrinsic::experimental_vector_reduce_xor: 6775 case Intrinsic::experimental_vector_reduce_smax: 6776 case Intrinsic::experimental_vector_reduce_smin: 6777 case Intrinsic::experimental_vector_reduce_umax: 6778 case Intrinsic::experimental_vector_reduce_umin: 6779 case Intrinsic::experimental_vector_reduce_fmax: 6780 case Intrinsic::experimental_vector_reduce_fmin: 6781 visitVectorReduce(I, Intrinsic); 6782 return; 6783 6784 case Intrinsic::icall_branch_funnel: { 6785 SmallVector<SDValue, 16> Ops; 6786 Ops.push_back(getValue(I.getArgOperand(0))); 6787 6788 int64_t Offset; 6789 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6790 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6791 if (!Base) 6792 report_fatal_error( 6793 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6794 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6795 6796 struct BranchFunnelTarget { 6797 int64_t Offset; 6798 SDValue Target; 6799 }; 6800 SmallVector<BranchFunnelTarget, 8> Targets; 6801 6802 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6803 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6804 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6805 if (ElemBase != Base) 6806 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6807 "to the same GlobalValue"); 6808 6809 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6810 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6811 if (!GA) 6812 report_fatal_error( 6813 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6814 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6815 GA->getGlobal(), getCurSDLoc(), 6816 Val.getValueType(), GA->getOffset())}); 6817 } 6818 llvm::sort(Targets, 6819 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6820 return T1.Offset < T2.Offset; 6821 }); 6822 6823 for (auto &T : Targets) { 6824 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6825 Ops.push_back(T.Target); 6826 } 6827 6828 Ops.push_back(DAG.getRoot()); // Chain 6829 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6830 getCurSDLoc(), MVT::Other, Ops), 6831 0); 6832 DAG.setRoot(N); 6833 setValue(&I, N); 6834 HasTailCall = true; 6835 return; 6836 } 6837 6838 case Intrinsic::wasm_landingpad_index: 6839 // Information this intrinsic contained has been transferred to 6840 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6841 // delete it now. 6842 return; 6843 6844 case Intrinsic::aarch64_settag: 6845 case Intrinsic::aarch64_settag_zero: { 6846 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6847 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6848 SDValue Val = TSI.EmitTargetCodeForSetTag( 6849 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6850 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6851 ZeroMemory); 6852 DAG.setRoot(Val); 6853 setValue(&I, Val); 6854 return; 6855 } 6856 case Intrinsic::ptrmask: { 6857 SDValue Ptr = getValue(I.getOperand(0)); 6858 SDValue Const = getValue(I.getOperand(1)); 6859 6860 EVT DestVT = 6861 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6862 6863 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6864 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6865 return; 6866 } 6867 } 6868 } 6869 6870 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6871 const ConstrainedFPIntrinsic &FPI) { 6872 SDLoc sdl = getCurSDLoc(); 6873 unsigned Opcode; 6874 switch (FPI.getIntrinsicID()) { 6875 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6876 case Intrinsic::experimental_constrained_fadd: 6877 Opcode = ISD::STRICT_FADD; 6878 break; 6879 case Intrinsic::experimental_constrained_fsub: 6880 Opcode = ISD::STRICT_FSUB; 6881 break; 6882 case Intrinsic::experimental_constrained_fmul: 6883 Opcode = ISD::STRICT_FMUL; 6884 break; 6885 case Intrinsic::experimental_constrained_fdiv: 6886 Opcode = ISD::STRICT_FDIV; 6887 break; 6888 case Intrinsic::experimental_constrained_frem: 6889 Opcode = ISD::STRICT_FREM; 6890 break; 6891 case Intrinsic::experimental_constrained_fma: 6892 Opcode = ISD::STRICT_FMA; 6893 break; 6894 case Intrinsic::experimental_constrained_fptosi: 6895 Opcode = ISD::STRICT_FP_TO_SINT; 6896 break; 6897 case Intrinsic::experimental_constrained_fptoui: 6898 Opcode = ISD::STRICT_FP_TO_UINT; 6899 break; 6900 case Intrinsic::experimental_constrained_fptrunc: 6901 Opcode = ISD::STRICT_FP_ROUND; 6902 break; 6903 case Intrinsic::experimental_constrained_fpext: 6904 Opcode = ISD::STRICT_FP_EXTEND; 6905 break; 6906 case Intrinsic::experimental_constrained_sqrt: 6907 Opcode = ISD::STRICT_FSQRT; 6908 break; 6909 case Intrinsic::experimental_constrained_pow: 6910 Opcode = ISD::STRICT_FPOW; 6911 break; 6912 case Intrinsic::experimental_constrained_powi: 6913 Opcode = ISD::STRICT_FPOWI; 6914 break; 6915 case Intrinsic::experimental_constrained_sin: 6916 Opcode = ISD::STRICT_FSIN; 6917 break; 6918 case Intrinsic::experimental_constrained_cos: 6919 Opcode = ISD::STRICT_FCOS; 6920 break; 6921 case Intrinsic::experimental_constrained_exp: 6922 Opcode = ISD::STRICT_FEXP; 6923 break; 6924 case Intrinsic::experimental_constrained_exp2: 6925 Opcode = ISD::STRICT_FEXP2; 6926 break; 6927 case Intrinsic::experimental_constrained_log: 6928 Opcode = ISD::STRICT_FLOG; 6929 break; 6930 case Intrinsic::experimental_constrained_log10: 6931 Opcode = ISD::STRICT_FLOG10; 6932 break; 6933 case Intrinsic::experimental_constrained_log2: 6934 Opcode = ISD::STRICT_FLOG2; 6935 break; 6936 case Intrinsic::experimental_constrained_rint: 6937 Opcode = ISD::STRICT_FRINT; 6938 break; 6939 case Intrinsic::experimental_constrained_nearbyint: 6940 Opcode = ISD::STRICT_FNEARBYINT; 6941 break; 6942 case Intrinsic::experimental_constrained_maxnum: 6943 Opcode = ISD::STRICT_FMAXNUM; 6944 break; 6945 case Intrinsic::experimental_constrained_minnum: 6946 Opcode = ISD::STRICT_FMINNUM; 6947 break; 6948 case Intrinsic::experimental_constrained_ceil: 6949 Opcode = ISD::STRICT_FCEIL; 6950 break; 6951 case Intrinsic::experimental_constrained_floor: 6952 Opcode = ISD::STRICT_FFLOOR; 6953 break; 6954 case Intrinsic::experimental_constrained_round: 6955 Opcode = ISD::STRICT_FROUND; 6956 break; 6957 case Intrinsic::experimental_constrained_trunc: 6958 Opcode = ISD::STRICT_FTRUNC; 6959 break; 6960 } 6961 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6962 SDValue Chain = getRoot(); 6963 SmallVector<EVT, 4> ValueVTs; 6964 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6965 ValueVTs.push_back(MVT::Other); // Out chain 6966 6967 SDVTList VTs = DAG.getVTList(ValueVTs); 6968 SDValue Result; 6969 if (Opcode == ISD::STRICT_FP_ROUND) 6970 Result = DAG.getNode(Opcode, sdl, VTs, 6971 { Chain, getValue(FPI.getArgOperand(0)), 6972 DAG.getTargetConstant(0, sdl, 6973 TLI.getPointerTy(DAG.getDataLayout())) }); 6974 else if (FPI.isUnaryOp()) 6975 Result = DAG.getNode(Opcode, sdl, VTs, 6976 { Chain, getValue(FPI.getArgOperand(0)) }); 6977 else if (FPI.isTernaryOp()) 6978 Result = DAG.getNode(Opcode, sdl, VTs, 6979 { Chain, getValue(FPI.getArgOperand(0)), 6980 getValue(FPI.getArgOperand(1)), 6981 getValue(FPI.getArgOperand(2)) }); 6982 else 6983 Result = DAG.getNode(Opcode, sdl, VTs, 6984 { Chain, getValue(FPI.getArgOperand(0)), 6985 getValue(FPI.getArgOperand(1)) }); 6986 6987 if (FPI.getExceptionBehavior() != 6988 ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) { 6989 SDNodeFlags Flags; 6990 Flags.setFPExcept(true); 6991 Result->setFlags(Flags); 6992 } 6993 6994 assert(Result.getNode()->getNumValues() == 2); 6995 SDValue OutChain = Result.getValue(1); 6996 DAG.setRoot(OutChain); 6997 SDValue FPResult = Result.getValue(0); 6998 setValue(&FPI, FPResult); 6999 } 7000 7001 std::pair<SDValue, SDValue> 7002 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7003 const BasicBlock *EHPadBB) { 7004 MachineFunction &MF = DAG.getMachineFunction(); 7005 MachineModuleInfo &MMI = MF.getMMI(); 7006 MCSymbol *BeginLabel = nullptr; 7007 7008 if (EHPadBB) { 7009 // Insert a label before the invoke call to mark the try range. This can be 7010 // used to detect deletion of the invoke via the MachineModuleInfo. 7011 BeginLabel = MMI.getContext().createTempSymbol(); 7012 7013 // For SjLj, keep track of which landing pads go with which invokes 7014 // so as to maintain the ordering of pads in the LSDA. 7015 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7016 if (CallSiteIndex) { 7017 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7018 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7019 7020 // Now that the call site is handled, stop tracking it. 7021 MMI.setCurrentCallSite(0); 7022 } 7023 7024 // Both PendingLoads and PendingExports must be flushed here; 7025 // this call might not return. 7026 (void)getRoot(); 7027 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7028 7029 CLI.setChain(getRoot()); 7030 } 7031 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7032 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7033 7034 assert((CLI.IsTailCall || Result.second.getNode()) && 7035 "Non-null chain expected with non-tail call!"); 7036 assert((Result.second.getNode() || !Result.first.getNode()) && 7037 "Null value expected with tail call!"); 7038 7039 if (!Result.second.getNode()) { 7040 // As a special case, a null chain means that a tail call has been emitted 7041 // and the DAG root is already updated. 7042 HasTailCall = true; 7043 7044 // Since there's no actual continuation from this block, nothing can be 7045 // relying on us setting vregs for them. 7046 PendingExports.clear(); 7047 } else { 7048 DAG.setRoot(Result.second); 7049 } 7050 7051 if (EHPadBB) { 7052 // Insert a label at the end of the invoke call to mark the try range. This 7053 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7054 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7055 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7056 7057 // Inform MachineModuleInfo of range. 7058 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7059 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7060 // actually use outlined funclets and their LSDA info style. 7061 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7062 assert(CLI.CS); 7063 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7064 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 7065 BeginLabel, EndLabel); 7066 } else if (!isScopedEHPersonality(Pers)) { 7067 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7068 } 7069 } 7070 7071 return Result; 7072 } 7073 7074 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7075 bool isTailCall, 7076 const BasicBlock *EHPadBB) { 7077 auto &DL = DAG.getDataLayout(); 7078 FunctionType *FTy = CS.getFunctionType(); 7079 Type *RetTy = CS.getType(); 7080 7081 TargetLowering::ArgListTy Args; 7082 Args.reserve(CS.arg_size()); 7083 7084 const Value *SwiftErrorVal = nullptr; 7085 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7086 7087 // We can't tail call inside a function with a swifterror argument. Lowering 7088 // does not support this yet. It would have to move into the swifterror 7089 // register before the call. 7090 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7091 if (TLI.supportSwiftError() && 7092 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7093 isTailCall = false; 7094 7095 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7096 i != e; ++i) { 7097 TargetLowering::ArgListEntry Entry; 7098 const Value *V = *i; 7099 7100 // Skip empty types 7101 if (V->getType()->isEmptyTy()) 7102 continue; 7103 7104 SDValue ArgNode = getValue(V); 7105 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7106 7107 Entry.setAttributes(&CS, i - CS.arg_begin()); 7108 7109 // Use swifterror virtual register as input to the call. 7110 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7111 SwiftErrorVal = V; 7112 // We find the virtual register for the actual swifterror argument. 7113 // Instead of using the Value, we use the virtual register instead. 7114 Entry.Node = DAG.getRegister( 7115 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7116 EVT(TLI.getPointerTy(DL))); 7117 } 7118 7119 Args.push_back(Entry); 7120 7121 // If we have an explicit sret argument that is an Instruction, (i.e., it 7122 // might point to function-local memory), we can't meaningfully tail-call. 7123 if (Entry.IsSRet && isa<Instruction>(V)) 7124 isTailCall = false; 7125 } 7126 7127 // Check if target-independent constraints permit a tail call here. 7128 // Target-dependent constraints are checked within TLI->LowerCallTo. 7129 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7130 isTailCall = false; 7131 7132 // Disable tail calls if there is an swifterror argument. Targets have not 7133 // been updated to support tail calls. 7134 if (TLI.supportSwiftError() && SwiftErrorVal) 7135 isTailCall = false; 7136 7137 TargetLowering::CallLoweringInfo CLI(DAG); 7138 CLI.setDebugLoc(getCurSDLoc()) 7139 .setChain(getRoot()) 7140 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7141 .setTailCall(isTailCall) 7142 .setConvergent(CS.isConvergent()); 7143 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7144 7145 if (Result.first.getNode()) { 7146 const Instruction *Inst = CS.getInstruction(); 7147 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7148 setValue(Inst, Result.first); 7149 } 7150 7151 // The last element of CLI.InVals has the SDValue for swifterror return. 7152 // Here we copy it to a virtual register and update SwiftErrorMap for 7153 // book-keeping. 7154 if (SwiftErrorVal && TLI.supportSwiftError()) { 7155 // Get the last element of InVals. 7156 SDValue Src = CLI.InVals.back(); 7157 Register VReg = SwiftError.getOrCreateVRegDefAt( 7158 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7159 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7160 DAG.setRoot(CopyNode); 7161 } 7162 } 7163 7164 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7165 SelectionDAGBuilder &Builder) { 7166 // Check to see if this load can be trivially constant folded, e.g. if the 7167 // input is from a string literal. 7168 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7169 // Cast pointer to the type we really want to load. 7170 Type *LoadTy = 7171 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7172 if (LoadVT.isVector()) 7173 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7174 7175 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7176 PointerType::getUnqual(LoadTy)); 7177 7178 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7179 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7180 return Builder.getValue(LoadCst); 7181 } 7182 7183 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7184 // still constant memory, the input chain can be the entry node. 7185 SDValue Root; 7186 bool ConstantMemory = false; 7187 7188 // Do not serialize (non-volatile) loads of constant memory with anything. 7189 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7190 Root = Builder.DAG.getEntryNode(); 7191 ConstantMemory = true; 7192 } else { 7193 // Do not serialize non-volatile loads against each other. 7194 Root = Builder.DAG.getRoot(); 7195 } 7196 7197 SDValue Ptr = Builder.getValue(PtrVal); 7198 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7199 Ptr, MachinePointerInfo(PtrVal), 7200 /* Alignment = */ 1); 7201 7202 if (!ConstantMemory) 7203 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7204 return LoadVal; 7205 } 7206 7207 /// Record the value for an instruction that produces an integer result, 7208 /// converting the type where necessary. 7209 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7210 SDValue Value, 7211 bool IsSigned) { 7212 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7213 I.getType(), true); 7214 if (IsSigned) 7215 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7216 else 7217 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7218 setValue(&I, Value); 7219 } 7220 7221 /// See if we can lower a memcmp call into an optimized form. If so, return 7222 /// true and lower it. Otherwise return false, and it will be lowered like a 7223 /// normal call. 7224 /// The caller already checked that \p I calls the appropriate LibFunc with a 7225 /// correct prototype. 7226 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7227 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7228 const Value *Size = I.getArgOperand(2); 7229 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7230 if (CSize && CSize->getZExtValue() == 0) { 7231 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7232 I.getType(), true); 7233 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7234 return true; 7235 } 7236 7237 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7238 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7239 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7240 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7241 if (Res.first.getNode()) { 7242 processIntegerCallValue(I, Res.first, true); 7243 PendingLoads.push_back(Res.second); 7244 return true; 7245 } 7246 7247 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7248 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7249 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7250 return false; 7251 7252 // If the target has a fast compare for the given size, it will return a 7253 // preferred load type for that size. Require that the load VT is legal and 7254 // that the target supports unaligned loads of that type. Otherwise, return 7255 // INVALID. 7256 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7257 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7258 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7259 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7260 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7261 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7262 // TODO: Check alignment of src and dest ptrs. 7263 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7264 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7265 if (!TLI.isTypeLegal(LVT) || 7266 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7267 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7268 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7269 } 7270 7271 return LVT; 7272 }; 7273 7274 // This turns into unaligned loads. We only do this if the target natively 7275 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7276 // we'll only produce a small number of byte loads. 7277 MVT LoadVT; 7278 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7279 switch (NumBitsToCompare) { 7280 default: 7281 return false; 7282 case 16: 7283 LoadVT = MVT::i16; 7284 break; 7285 case 32: 7286 LoadVT = MVT::i32; 7287 break; 7288 case 64: 7289 case 128: 7290 case 256: 7291 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7292 break; 7293 } 7294 7295 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7296 return false; 7297 7298 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7299 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7300 7301 // Bitcast to a wide integer type if the loads are vectors. 7302 if (LoadVT.isVector()) { 7303 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7304 LoadL = DAG.getBitcast(CmpVT, LoadL); 7305 LoadR = DAG.getBitcast(CmpVT, LoadR); 7306 } 7307 7308 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7309 processIntegerCallValue(I, Cmp, false); 7310 return true; 7311 } 7312 7313 /// See if we can lower a memchr call into an optimized form. If so, return 7314 /// true and lower it. Otherwise return false, and it will be lowered like a 7315 /// normal call. 7316 /// The caller already checked that \p I calls the appropriate LibFunc with a 7317 /// correct prototype. 7318 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7319 const Value *Src = I.getArgOperand(0); 7320 const Value *Char = I.getArgOperand(1); 7321 const Value *Length = I.getArgOperand(2); 7322 7323 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7324 std::pair<SDValue, SDValue> Res = 7325 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7326 getValue(Src), getValue(Char), getValue(Length), 7327 MachinePointerInfo(Src)); 7328 if (Res.first.getNode()) { 7329 setValue(&I, Res.first); 7330 PendingLoads.push_back(Res.second); 7331 return true; 7332 } 7333 7334 return false; 7335 } 7336 7337 /// See if we can lower a mempcpy call into an optimized form. If so, return 7338 /// true and lower it. Otherwise return false, and it will be lowered like a 7339 /// normal call. 7340 /// The caller already checked that \p I calls the appropriate LibFunc with a 7341 /// correct prototype. 7342 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7343 SDValue Dst = getValue(I.getArgOperand(0)); 7344 SDValue Src = getValue(I.getArgOperand(1)); 7345 SDValue Size = getValue(I.getArgOperand(2)); 7346 7347 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7348 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7349 unsigned Align = std::min(DstAlign, SrcAlign); 7350 if (Align == 0) // Alignment of one or both could not be inferred. 7351 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7352 7353 bool isVol = false; 7354 SDLoc sdl = getCurSDLoc(); 7355 7356 // In the mempcpy context we need to pass in a false value for isTailCall 7357 // because the return pointer needs to be adjusted by the size of 7358 // the copied memory. 7359 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7360 false, /*isTailCall=*/false, 7361 MachinePointerInfo(I.getArgOperand(0)), 7362 MachinePointerInfo(I.getArgOperand(1))); 7363 assert(MC.getNode() != nullptr && 7364 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7365 DAG.setRoot(MC); 7366 7367 // Check if Size needs to be truncated or extended. 7368 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7369 7370 // Adjust return pointer to point just past the last dst byte. 7371 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7372 Dst, Size); 7373 setValue(&I, DstPlusSize); 7374 return true; 7375 } 7376 7377 /// See if we can lower a strcpy call into an optimized form. If so, return 7378 /// true and lower it, otherwise return false and it will be lowered like a 7379 /// normal call. 7380 /// The caller already checked that \p I calls the appropriate LibFunc with a 7381 /// correct prototype. 7382 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7383 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7384 7385 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7386 std::pair<SDValue, SDValue> Res = 7387 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7388 getValue(Arg0), getValue(Arg1), 7389 MachinePointerInfo(Arg0), 7390 MachinePointerInfo(Arg1), isStpcpy); 7391 if (Res.first.getNode()) { 7392 setValue(&I, Res.first); 7393 DAG.setRoot(Res.second); 7394 return true; 7395 } 7396 7397 return false; 7398 } 7399 7400 /// See if we can lower a strcmp call into an optimized form. If so, return 7401 /// true and lower it, otherwise return false and it will be lowered like a 7402 /// normal call. 7403 /// The caller already checked that \p I calls the appropriate LibFunc with a 7404 /// correct prototype. 7405 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7406 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7407 7408 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7409 std::pair<SDValue, SDValue> Res = 7410 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7411 getValue(Arg0), getValue(Arg1), 7412 MachinePointerInfo(Arg0), 7413 MachinePointerInfo(Arg1)); 7414 if (Res.first.getNode()) { 7415 processIntegerCallValue(I, Res.first, true); 7416 PendingLoads.push_back(Res.second); 7417 return true; 7418 } 7419 7420 return false; 7421 } 7422 7423 /// See if we can lower a strlen call into an optimized form. If so, return 7424 /// true and lower it, otherwise return false and it will be lowered like a 7425 /// normal call. 7426 /// The caller already checked that \p I calls the appropriate LibFunc with a 7427 /// correct prototype. 7428 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7429 const Value *Arg0 = I.getArgOperand(0); 7430 7431 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7432 std::pair<SDValue, SDValue> Res = 7433 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7434 getValue(Arg0), MachinePointerInfo(Arg0)); 7435 if (Res.first.getNode()) { 7436 processIntegerCallValue(I, Res.first, false); 7437 PendingLoads.push_back(Res.second); 7438 return true; 7439 } 7440 7441 return false; 7442 } 7443 7444 /// See if we can lower a strnlen call into an optimized form. If so, return 7445 /// true and lower it, otherwise return false and it will be lowered like a 7446 /// normal call. 7447 /// The caller already checked that \p I calls the appropriate LibFunc with a 7448 /// correct prototype. 7449 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7450 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7451 7452 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7453 std::pair<SDValue, SDValue> Res = 7454 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7455 getValue(Arg0), getValue(Arg1), 7456 MachinePointerInfo(Arg0)); 7457 if (Res.first.getNode()) { 7458 processIntegerCallValue(I, Res.first, false); 7459 PendingLoads.push_back(Res.second); 7460 return true; 7461 } 7462 7463 return false; 7464 } 7465 7466 /// See if we can lower a unary floating-point operation into an SDNode with 7467 /// the specified Opcode. If so, return true and lower it, otherwise return 7468 /// false and it will be lowered like a normal call. 7469 /// The caller already checked that \p I calls the appropriate LibFunc with a 7470 /// correct prototype. 7471 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7472 unsigned Opcode) { 7473 // We already checked this call's prototype; verify it doesn't modify errno. 7474 if (!I.onlyReadsMemory()) 7475 return false; 7476 7477 SDValue Tmp = getValue(I.getArgOperand(0)); 7478 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7479 return true; 7480 } 7481 7482 /// See if we can lower a binary floating-point operation into an SDNode with 7483 /// the specified Opcode. If so, return true and lower it. Otherwise return 7484 /// false, and it will be lowered like a normal call. 7485 /// The caller already checked that \p I calls the appropriate LibFunc with a 7486 /// correct prototype. 7487 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7488 unsigned Opcode) { 7489 // We already checked this call's prototype; verify it doesn't modify errno. 7490 if (!I.onlyReadsMemory()) 7491 return false; 7492 7493 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7494 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7495 EVT VT = Tmp0.getValueType(); 7496 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7497 return true; 7498 } 7499 7500 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7501 // Handle inline assembly differently. 7502 if (isa<InlineAsm>(I.getCalledValue())) { 7503 visitInlineAsm(&I); 7504 return; 7505 } 7506 7507 if (Function *F = I.getCalledFunction()) { 7508 if (F->isDeclaration()) { 7509 // Is this an LLVM intrinsic or a target-specific intrinsic? 7510 unsigned IID = F->getIntrinsicID(); 7511 if (!IID) 7512 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7513 IID = II->getIntrinsicID(F); 7514 7515 if (IID) { 7516 visitIntrinsicCall(I, IID); 7517 return; 7518 } 7519 } 7520 7521 // Check for well-known libc/libm calls. If the function is internal, it 7522 // can't be a library call. Don't do the check if marked as nobuiltin for 7523 // some reason or the call site requires strict floating point semantics. 7524 LibFunc Func; 7525 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7526 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7527 LibInfo->hasOptimizedCodeGen(Func)) { 7528 switch (Func) { 7529 default: break; 7530 case LibFunc_copysign: 7531 case LibFunc_copysignf: 7532 case LibFunc_copysignl: 7533 // We already checked this call's prototype; verify it doesn't modify 7534 // errno. 7535 if (I.onlyReadsMemory()) { 7536 SDValue LHS = getValue(I.getArgOperand(0)); 7537 SDValue RHS = getValue(I.getArgOperand(1)); 7538 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7539 LHS.getValueType(), LHS, RHS)); 7540 return; 7541 } 7542 break; 7543 case LibFunc_fabs: 7544 case LibFunc_fabsf: 7545 case LibFunc_fabsl: 7546 if (visitUnaryFloatCall(I, ISD::FABS)) 7547 return; 7548 break; 7549 case LibFunc_fmin: 7550 case LibFunc_fminf: 7551 case LibFunc_fminl: 7552 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7553 return; 7554 break; 7555 case LibFunc_fmax: 7556 case LibFunc_fmaxf: 7557 case LibFunc_fmaxl: 7558 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7559 return; 7560 break; 7561 case LibFunc_sin: 7562 case LibFunc_sinf: 7563 case LibFunc_sinl: 7564 if (visitUnaryFloatCall(I, ISD::FSIN)) 7565 return; 7566 break; 7567 case LibFunc_cos: 7568 case LibFunc_cosf: 7569 case LibFunc_cosl: 7570 if (visitUnaryFloatCall(I, ISD::FCOS)) 7571 return; 7572 break; 7573 case LibFunc_sqrt: 7574 case LibFunc_sqrtf: 7575 case LibFunc_sqrtl: 7576 case LibFunc_sqrt_finite: 7577 case LibFunc_sqrtf_finite: 7578 case LibFunc_sqrtl_finite: 7579 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7580 return; 7581 break; 7582 case LibFunc_floor: 7583 case LibFunc_floorf: 7584 case LibFunc_floorl: 7585 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7586 return; 7587 break; 7588 case LibFunc_nearbyint: 7589 case LibFunc_nearbyintf: 7590 case LibFunc_nearbyintl: 7591 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7592 return; 7593 break; 7594 case LibFunc_ceil: 7595 case LibFunc_ceilf: 7596 case LibFunc_ceill: 7597 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7598 return; 7599 break; 7600 case LibFunc_rint: 7601 case LibFunc_rintf: 7602 case LibFunc_rintl: 7603 if (visitUnaryFloatCall(I, ISD::FRINT)) 7604 return; 7605 break; 7606 case LibFunc_round: 7607 case LibFunc_roundf: 7608 case LibFunc_roundl: 7609 if (visitUnaryFloatCall(I, ISD::FROUND)) 7610 return; 7611 break; 7612 case LibFunc_trunc: 7613 case LibFunc_truncf: 7614 case LibFunc_truncl: 7615 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7616 return; 7617 break; 7618 case LibFunc_log2: 7619 case LibFunc_log2f: 7620 case LibFunc_log2l: 7621 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7622 return; 7623 break; 7624 case LibFunc_exp2: 7625 case LibFunc_exp2f: 7626 case LibFunc_exp2l: 7627 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7628 return; 7629 break; 7630 case LibFunc_memcmp: 7631 if (visitMemCmpCall(I)) 7632 return; 7633 break; 7634 case LibFunc_mempcpy: 7635 if (visitMemPCpyCall(I)) 7636 return; 7637 break; 7638 case LibFunc_memchr: 7639 if (visitMemChrCall(I)) 7640 return; 7641 break; 7642 case LibFunc_strcpy: 7643 if (visitStrCpyCall(I, false)) 7644 return; 7645 break; 7646 case LibFunc_stpcpy: 7647 if (visitStrCpyCall(I, true)) 7648 return; 7649 break; 7650 case LibFunc_strcmp: 7651 if (visitStrCmpCall(I)) 7652 return; 7653 break; 7654 case LibFunc_strlen: 7655 if (visitStrLenCall(I)) 7656 return; 7657 break; 7658 case LibFunc_strnlen: 7659 if (visitStrNLenCall(I)) 7660 return; 7661 break; 7662 } 7663 } 7664 } 7665 7666 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7667 // have to do anything here to lower funclet bundles. 7668 assert(!I.hasOperandBundlesOtherThan( 7669 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7670 "Cannot lower calls with arbitrary operand bundles!"); 7671 7672 SDValue Callee = getValue(I.getCalledValue()); 7673 7674 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7675 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7676 else 7677 // Check if we can potentially perform a tail call. More detailed checking 7678 // is be done within LowerCallTo, after more information about the call is 7679 // known. 7680 LowerCallTo(&I, Callee, I.isTailCall()); 7681 } 7682 7683 namespace { 7684 7685 /// AsmOperandInfo - This contains information for each constraint that we are 7686 /// lowering. 7687 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7688 public: 7689 /// CallOperand - If this is the result output operand or a clobber 7690 /// this is null, otherwise it is the incoming operand to the CallInst. 7691 /// This gets modified as the asm is processed. 7692 SDValue CallOperand; 7693 7694 /// AssignedRegs - If this is a register or register class operand, this 7695 /// contains the set of register corresponding to the operand. 7696 RegsForValue AssignedRegs; 7697 7698 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7699 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7700 } 7701 7702 /// Whether or not this operand accesses memory 7703 bool hasMemory(const TargetLowering &TLI) const { 7704 // Indirect operand accesses access memory. 7705 if (isIndirect) 7706 return true; 7707 7708 for (const auto &Code : Codes) 7709 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7710 return true; 7711 7712 return false; 7713 } 7714 7715 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7716 /// corresponds to. If there is no Value* for this operand, it returns 7717 /// MVT::Other. 7718 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7719 const DataLayout &DL) const { 7720 if (!CallOperandVal) return MVT::Other; 7721 7722 if (isa<BasicBlock>(CallOperandVal)) 7723 return TLI.getPointerTy(DL); 7724 7725 llvm::Type *OpTy = CallOperandVal->getType(); 7726 7727 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7728 // If this is an indirect operand, the operand is a pointer to the 7729 // accessed type. 7730 if (isIndirect) { 7731 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7732 if (!PtrTy) 7733 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7734 OpTy = PtrTy->getElementType(); 7735 } 7736 7737 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7738 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7739 if (STy->getNumElements() == 1) 7740 OpTy = STy->getElementType(0); 7741 7742 // If OpTy is not a single value, it may be a struct/union that we 7743 // can tile with integers. 7744 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7745 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7746 switch (BitSize) { 7747 default: break; 7748 case 1: 7749 case 8: 7750 case 16: 7751 case 32: 7752 case 64: 7753 case 128: 7754 OpTy = IntegerType::get(Context, BitSize); 7755 break; 7756 } 7757 } 7758 7759 return TLI.getValueType(DL, OpTy, true); 7760 } 7761 }; 7762 7763 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7764 7765 } // end anonymous namespace 7766 7767 /// Make sure that the output operand \p OpInfo and its corresponding input 7768 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7769 /// out). 7770 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7771 SDISelAsmOperandInfo &MatchingOpInfo, 7772 SelectionDAG &DAG) { 7773 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7774 return; 7775 7776 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7777 const auto &TLI = DAG.getTargetLoweringInfo(); 7778 7779 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7780 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7781 OpInfo.ConstraintVT); 7782 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7783 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7784 MatchingOpInfo.ConstraintVT); 7785 if ((OpInfo.ConstraintVT.isInteger() != 7786 MatchingOpInfo.ConstraintVT.isInteger()) || 7787 (MatchRC.second != InputRC.second)) { 7788 // FIXME: error out in a more elegant fashion 7789 report_fatal_error("Unsupported asm: input constraint" 7790 " with a matching output constraint of" 7791 " incompatible type!"); 7792 } 7793 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7794 } 7795 7796 /// Get a direct memory input to behave well as an indirect operand. 7797 /// This may introduce stores, hence the need for a \p Chain. 7798 /// \return The (possibly updated) chain. 7799 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7800 SDISelAsmOperandInfo &OpInfo, 7801 SelectionDAG &DAG) { 7802 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7803 7804 // If we don't have an indirect input, put it in the constpool if we can, 7805 // otherwise spill it to a stack slot. 7806 // TODO: This isn't quite right. We need to handle these according to 7807 // the addressing mode that the constraint wants. Also, this may take 7808 // an additional register for the computation and we don't want that 7809 // either. 7810 7811 // If the operand is a float, integer, or vector constant, spill to a 7812 // constant pool entry to get its address. 7813 const Value *OpVal = OpInfo.CallOperandVal; 7814 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7815 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7816 OpInfo.CallOperand = DAG.getConstantPool( 7817 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7818 return Chain; 7819 } 7820 7821 // Otherwise, create a stack slot and emit a store to it before the asm. 7822 Type *Ty = OpVal->getType(); 7823 auto &DL = DAG.getDataLayout(); 7824 uint64_t TySize = DL.getTypeAllocSize(Ty); 7825 unsigned Align = DL.getPrefTypeAlignment(Ty); 7826 MachineFunction &MF = DAG.getMachineFunction(); 7827 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7828 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7829 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7830 MachinePointerInfo::getFixedStack(MF, SSFI), 7831 TLI.getMemValueType(DL, Ty)); 7832 OpInfo.CallOperand = StackSlot; 7833 7834 return Chain; 7835 } 7836 7837 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7838 /// specified operand. We prefer to assign virtual registers, to allow the 7839 /// register allocator to handle the assignment process. However, if the asm 7840 /// uses features that we can't model on machineinstrs, we have SDISel do the 7841 /// allocation. This produces generally horrible, but correct, code. 7842 /// 7843 /// OpInfo describes the operand 7844 /// RefOpInfo describes the matching operand if any, the operand otherwise 7845 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7846 SDISelAsmOperandInfo &OpInfo, 7847 SDISelAsmOperandInfo &RefOpInfo) { 7848 LLVMContext &Context = *DAG.getContext(); 7849 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7850 7851 MachineFunction &MF = DAG.getMachineFunction(); 7852 SmallVector<unsigned, 4> Regs; 7853 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7854 7855 // No work to do for memory operations. 7856 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7857 return; 7858 7859 // If this is a constraint for a single physreg, or a constraint for a 7860 // register class, find it. 7861 unsigned AssignedReg; 7862 const TargetRegisterClass *RC; 7863 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7864 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7865 // RC is unset only on failure. Return immediately. 7866 if (!RC) 7867 return; 7868 7869 // Get the actual register value type. This is important, because the user 7870 // may have asked for (e.g.) the AX register in i32 type. We need to 7871 // remember that AX is actually i16 to get the right extension. 7872 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7873 7874 if (OpInfo.ConstraintVT != MVT::Other) { 7875 // If this is an FP operand in an integer register (or visa versa), or more 7876 // generally if the operand value disagrees with the register class we plan 7877 // to stick it in, fix the operand type. 7878 // 7879 // If this is an input value, the bitcast to the new type is done now. 7880 // Bitcast for output value is done at the end of visitInlineAsm(). 7881 if ((OpInfo.Type == InlineAsm::isOutput || 7882 OpInfo.Type == InlineAsm::isInput) && 7883 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7884 // Try to convert to the first EVT that the reg class contains. If the 7885 // types are identical size, use a bitcast to convert (e.g. two differing 7886 // vector types). Note: output bitcast is done at the end of 7887 // visitInlineAsm(). 7888 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7889 // Exclude indirect inputs while they are unsupported because the code 7890 // to perform the load is missing and thus OpInfo.CallOperand still 7891 // refers to the input address rather than the pointed-to value. 7892 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7893 OpInfo.CallOperand = 7894 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7895 OpInfo.ConstraintVT = RegVT; 7896 // If the operand is an FP value and we want it in integer registers, 7897 // use the corresponding integer type. This turns an f64 value into 7898 // i64, which can be passed with two i32 values on a 32-bit machine. 7899 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7900 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7901 if (OpInfo.Type == InlineAsm::isInput) 7902 OpInfo.CallOperand = 7903 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7904 OpInfo.ConstraintVT = VT; 7905 } 7906 } 7907 } 7908 7909 // No need to allocate a matching input constraint since the constraint it's 7910 // matching to has already been allocated. 7911 if (OpInfo.isMatchingInputConstraint()) 7912 return; 7913 7914 EVT ValueVT = OpInfo.ConstraintVT; 7915 if (OpInfo.ConstraintVT == MVT::Other) 7916 ValueVT = RegVT; 7917 7918 // Initialize NumRegs. 7919 unsigned NumRegs = 1; 7920 if (OpInfo.ConstraintVT != MVT::Other) 7921 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7922 7923 // If this is a constraint for a specific physical register, like {r17}, 7924 // assign it now. 7925 7926 // If this associated to a specific register, initialize iterator to correct 7927 // place. If virtual, make sure we have enough registers 7928 7929 // Initialize iterator if necessary 7930 TargetRegisterClass::iterator I = RC->begin(); 7931 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7932 7933 // Do not check for single registers. 7934 if (AssignedReg) { 7935 for (; *I != AssignedReg; ++I) 7936 assert(I != RC->end() && "AssignedReg should be member of RC"); 7937 } 7938 7939 for (; NumRegs; --NumRegs, ++I) { 7940 assert(I != RC->end() && "Ran out of registers to allocate!"); 7941 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7942 Regs.push_back(R); 7943 } 7944 7945 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7946 } 7947 7948 static unsigned 7949 findMatchingInlineAsmOperand(unsigned OperandNo, 7950 const std::vector<SDValue> &AsmNodeOperands) { 7951 // Scan until we find the definition we already emitted of this operand. 7952 unsigned CurOp = InlineAsm::Op_FirstOperand; 7953 for (; OperandNo; --OperandNo) { 7954 // Advance to the next operand. 7955 unsigned OpFlag = 7956 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7957 assert((InlineAsm::isRegDefKind(OpFlag) || 7958 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7959 InlineAsm::isMemKind(OpFlag)) && 7960 "Skipped past definitions?"); 7961 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7962 } 7963 return CurOp; 7964 } 7965 7966 namespace { 7967 7968 class ExtraFlags { 7969 unsigned Flags = 0; 7970 7971 public: 7972 explicit ExtraFlags(ImmutableCallSite CS) { 7973 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7974 if (IA->hasSideEffects()) 7975 Flags |= InlineAsm::Extra_HasSideEffects; 7976 if (IA->isAlignStack()) 7977 Flags |= InlineAsm::Extra_IsAlignStack; 7978 if (CS.isConvergent()) 7979 Flags |= InlineAsm::Extra_IsConvergent; 7980 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7981 } 7982 7983 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7984 // Ideally, we would only check against memory constraints. However, the 7985 // meaning of an Other constraint can be target-specific and we can't easily 7986 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7987 // for Other constraints as well. 7988 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7989 OpInfo.ConstraintType == TargetLowering::C_Other) { 7990 if (OpInfo.Type == InlineAsm::isInput) 7991 Flags |= InlineAsm::Extra_MayLoad; 7992 else if (OpInfo.Type == InlineAsm::isOutput) 7993 Flags |= InlineAsm::Extra_MayStore; 7994 else if (OpInfo.Type == InlineAsm::isClobber) 7995 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7996 } 7997 } 7998 7999 unsigned get() const { return Flags; } 8000 }; 8001 8002 } // end anonymous namespace 8003 8004 /// visitInlineAsm - Handle a call to an InlineAsm object. 8005 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 8006 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8007 8008 /// ConstraintOperands - Information about all of the constraints. 8009 SDISelAsmOperandInfoVector ConstraintOperands; 8010 8011 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8012 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8013 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 8014 8015 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8016 // AsmDialect, MayLoad, MayStore). 8017 bool HasSideEffect = IA->hasSideEffects(); 8018 ExtraFlags ExtraInfo(CS); 8019 8020 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8021 unsigned ResNo = 0; // ResNo - The result number of the next output. 8022 for (auto &T : TargetConstraints) { 8023 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8024 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8025 8026 // Compute the value type for each operand. 8027 if (OpInfo.Type == InlineAsm::isInput || 8028 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8029 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 8030 8031 // Process the call argument. BasicBlocks are labels, currently appearing 8032 // only in asm's. 8033 const Instruction *I = CS.getInstruction(); 8034 if (isa<CallBrInst>(I) && 8035 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 8036 cast<CallBrInst>(I)->getNumIndirectDests())) { 8037 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8038 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8039 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8040 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8041 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8042 } else { 8043 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8044 } 8045 8046 OpInfo.ConstraintVT = 8047 OpInfo 8048 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8049 .getSimpleVT(); 8050 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8051 // The return value of the call is this value. As such, there is no 8052 // corresponding argument. 8053 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8054 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8055 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8056 DAG.getDataLayout(), STy->getElementType(ResNo)); 8057 } else { 8058 assert(ResNo == 0 && "Asm only has one result!"); 8059 OpInfo.ConstraintVT = 8060 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8061 } 8062 ++ResNo; 8063 } else { 8064 OpInfo.ConstraintVT = MVT::Other; 8065 } 8066 8067 if (!HasSideEffect) 8068 HasSideEffect = OpInfo.hasMemory(TLI); 8069 8070 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8071 // FIXME: Could we compute this on OpInfo rather than T? 8072 8073 // Compute the constraint code and ConstraintType to use. 8074 TLI.ComputeConstraintToUse(T, SDValue()); 8075 8076 if (T.ConstraintType == TargetLowering::C_Immediate && 8077 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8078 // We've delayed emitting a diagnostic like the "n" constraint because 8079 // inlining could cause an integer showing up. 8080 return emitInlineAsmError( 8081 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8082 "integer constant expression"); 8083 8084 ExtraInfo.update(T); 8085 } 8086 8087 8088 // We won't need to flush pending loads if this asm doesn't touch 8089 // memory and is nonvolatile. 8090 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8091 8092 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8093 if (IsCallBr) { 8094 // If this is a callbr we need to flush pending exports since inlineasm_br 8095 // is a terminator. We need to do this before nodes are glued to 8096 // the inlineasm_br node. 8097 Chain = getControlRoot(); 8098 } 8099 8100 // Second pass over the constraints: compute which constraint option to use. 8101 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8102 // If this is an output operand with a matching input operand, look up the 8103 // matching input. If their types mismatch, e.g. one is an integer, the 8104 // other is floating point, or their sizes are different, flag it as an 8105 // error. 8106 if (OpInfo.hasMatchingInput()) { 8107 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8108 patchMatchingInput(OpInfo, Input, DAG); 8109 } 8110 8111 // Compute the constraint code and ConstraintType to use. 8112 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8113 8114 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8115 OpInfo.Type == InlineAsm::isClobber) 8116 continue; 8117 8118 // If this is a memory input, and if the operand is not indirect, do what we 8119 // need to provide an address for the memory input. 8120 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8121 !OpInfo.isIndirect) { 8122 assert((OpInfo.isMultipleAlternative || 8123 (OpInfo.Type == InlineAsm::isInput)) && 8124 "Can only indirectify direct input operands!"); 8125 8126 // Memory operands really want the address of the value. 8127 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8128 8129 // There is no longer a Value* corresponding to this operand. 8130 OpInfo.CallOperandVal = nullptr; 8131 8132 // It is now an indirect operand. 8133 OpInfo.isIndirect = true; 8134 } 8135 8136 } 8137 8138 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8139 std::vector<SDValue> AsmNodeOperands; 8140 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8141 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8142 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8143 8144 // If we have a !srcloc metadata node associated with it, we want to attach 8145 // this to the ultimately generated inline asm machineinstr. To do this, we 8146 // pass in the third operand as this (potentially null) inline asm MDNode. 8147 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8148 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8149 8150 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8151 // bits as operand 3. 8152 AsmNodeOperands.push_back(DAG.getTargetConstant( 8153 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8154 8155 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8156 // this, assign virtual and physical registers for inputs and otput. 8157 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8158 // Assign Registers. 8159 SDISelAsmOperandInfo &RefOpInfo = 8160 OpInfo.isMatchingInputConstraint() 8161 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8162 : OpInfo; 8163 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8164 8165 switch (OpInfo.Type) { 8166 case InlineAsm::isOutput: 8167 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8168 ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8169 OpInfo.ConstraintType == TargetLowering::C_Other) && 8170 OpInfo.isIndirect)) { 8171 unsigned ConstraintID = 8172 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8173 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8174 "Failed to convert memory constraint code to constraint id."); 8175 8176 // Add information to the INLINEASM node to know about this output. 8177 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8178 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8179 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8180 MVT::i32)); 8181 AsmNodeOperands.push_back(OpInfo.CallOperand); 8182 break; 8183 } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8184 OpInfo.ConstraintType == TargetLowering::C_Other) && 8185 !OpInfo.isIndirect) || 8186 OpInfo.ConstraintType == TargetLowering::C_Register || 8187 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8188 // Otherwise, this outputs to a register (directly for C_Register / 8189 // C_RegisterClass, and a target-defined fashion for 8190 // C_Immediate/C_Other). Find a register that we can use. 8191 if (OpInfo.AssignedRegs.Regs.empty()) { 8192 emitInlineAsmError( 8193 CS, "couldn't allocate output register for constraint '" + 8194 Twine(OpInfo.ConstraintCode) + "'"); 8195 return; 8196 } 8197 8198 // Add information to the INLINEASM node to know that this register is 8199 // set. 8200 OpInfo.AssignedRegs.AddInlineAsmOperands( 8201 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8202 : InlineAsm::Kind_RegDef, 8203 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8204 } 8205 break; 8206 8207 case InlineAsm::isInput: { 8208 SDValue InOperandVal = OpInfo.CallOperand; 8209 8210 if (OpInfo.isMatchingInputConstraint()) { 8211 // If this is required to match an output register we have already set, 8212 // just use its register. 8213 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8214 AsmNodeOperands); 8215 unsigned OpFlag = 8216 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8217 if (InlineAsm::isRegDefKind(OpFlag) || 8218 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8219 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8220 if (OpInfo.isIndirect) { 8221 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8222 emitInlineAsmError(CS, "inline asm not supported yet:" 8223 " don't know how to handle tied " 8224 "indirect register inputs"); 8225 return; 8226 } 8227 8228 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8229 SmallVector<unsigned, 4> Regs; 8230 8231 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8232 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8233 MachineRegisterInfo &RegInfo = 8234 DAG.getMachineFunction().getRegInfo(); 8235 for (unsigned i = 0; i != NumRegs; ++i) 8236 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8237 } else { 8238 emitInlineAsmError(CS, "inline asm error: This value type register " 8239 "class is not natively supported!"); 8240 return; 8241 } 8242 8243 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8244 8245 SDLoc dl = getCurSDLoc(); 8246 // Use the produced MatchedRegs object to 8247 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8248 CS.getInstruction()); 8249 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8250 true, OpInfo.getMatchedOperand(), dl, 8251 DAG, AsmNodeOperands); 8252 break; 8253 } 8254 8255 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8256 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8257 "Unexpected number of operands"); 8258 // Add information to the INLINEASM node to know about this input. 8259 // See InlineAsm.h isUseOperandTiedToDef. 8260 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8261 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8262 OpInfo.getMatchedOperand()); 8263 AsmNodeOperands.push_back(DAG.getTargetConstant( 8264 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8265 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8266 break; 8267 } 8268 8269 // Treat indirect 'X' constraint as memory. 8270 if ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8271 OpInfo.ConstraintType == TargetLowering::C_Other) && 8272 OpInfo.isIndirect) 8273 OpInfo.ConstraintType = TargetLowering::C_Memory; 8274 8275 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8276 OpInfo.ConstraintType == TargetLowering::C_Other) { 8277 std::vector<SDValue> Ops; 8278 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8279 Ops, DAG); 8280 if (Ops.empty()) { 8281 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8282 if (isa<ConstantSDNode>(InOperandVal)) { 8283 emitInlineAsmError(CS, "value out of range for constraint '" + 8284 Twine(OpInfo.ConstraintCode) + "'"); 8285 return; 8286 } 8287 8288 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8289 Twine(OpInfo.ConstraintCode) + "'"); 8290 return; 8291 } 8292 8293 // Add information to the INLINEASM node to know about this input. 8294 unsigned ResOpType = 8295 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8296 AsmNodeOperands.push_back(DAG.getTargetConstant( 8297 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8298 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8299 break; 8300 } 8301 8302 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8303 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8304 assert(InOperandVal.getValueType() == 8305 TLI.getPointerTy(DAG.getDataLayout()) && 8306 "Memory operands expect pointer values"); 8307 8308 unsigned ConstraintID = 8309 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8310 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8311 "Failed to convert memory constraint code to constraint id."); 8312 8313 // Add information to the INLINEASM node to know about this input. 8314 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8315 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8316 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8317 getCurSDLoc(), 8318 MVT::i32)); 8319 AsmNodeOperands.push_back(InOperandVal); 8320 break; 8321 } 8322 8323 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8324 OpInfo.ConstraintType == TargetLowering::C_Register || 8325 OpInfo.ConstraintType == TargetLowering::C_Immediate) && 8326 "Unknown constraint type!"); 8327 8328 // TODO: Support this. 8329 if (OpInfo.isIndirect) { 8330 emitInlineAsmError( 8331 CS, "Don't know how to handle indirect register inputs yet " 8332 "for constraint '" + 8333 Twine(OpInfo.ConstraintCode) + "'"); 8334 return; 8335 } 8336 8337 // Copy the input into the appropriate registers. 8338 if (OpInfo.AssignedRegs.Regs.empty()) { 8339 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8340 Twine(OpInfo.ConstraintCode) + "'"); 8341 return; 8342 } 8343 8344 SDLoc dl = getCurSDLoc(); 8345 8346 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8347 Chain, &Flag, CS.getInstruction()); 8348 8349 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8350 dl, DAG, AsmNodeOperands); 8351 break; 8352 } 8353 case InlineAsm::isClobber: 8354 // Add the clobbered value to the operand list, so that the register 8355 // allocator is aware that the physreg got clobbered. 8356 if (!OpInfo.AssignedRegs.Regs.empty()) 8357 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8358 false, 0, getCurSDLoc(), DAG, 8359 AsmNodeOperands); 8360 break; 8361 } 8362 } 8363 8364 // Finish up input operands. Set the input chain and add the flag last. 8365 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8366 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8367 8368 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8369 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8370 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8371 Flag = Chain.getValue(1); 8372 8373 // Do additional work to generate outputs. 8374 8375 SmallVector<EVT, 1> ResultVTs; 8376 SmallVector<SDValue, 1> ResultValues; 8377 SmallVector<SDValue, 8> OutChains; 8378 8379 llvm::Type *CSResultType = CS.getType(); 8380 ArrayRef<Type *> ResultTypes; 8381 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8382 ResultTypes = StructResult->elements(); 8383 else if (!CSResultType->isVoidTy()) 8384 ResultTypes = makeArrayRef(CSResultType); 8385 8386 auto CurResultType = ResultTypes.begin(); 8387 auto handleRegAssign = [&](SDValue V) { 8388 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8389 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8390 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8391 ++CurResultType; 8392 // If the type of the inline asm call site return value is different but has 8393 // same size as the type of the asm output bitcast it. One example of this 8394 // is for vectors with different width / number of elements. This can 8395 // happen for register classes that can contain multiple different value 8396 // types. The preg or vreg allocated may not have the same VT as was 8397 // expected. 8398 // 8399 // This can also happen for a return value that disagrees with the register 8400 // class it is put in, eg. a double in a general-purpose register on a 8401 // 32-bit machine. 8402 if (ResultVT != V.getValueType() && 8403 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8404 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8405 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8406 V.getValueType().isInteger()) { 8407 // If a result value was tied to an input value, the computed result 8408 // may have a wider width than the expected result. Extract the 8409 // relevant portion. 8410 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8411 } 8412 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8413 ResultVTs.push_back(ResultVT); 8414 ResultValues.push_back(V); 8415 }; 8416 8417 // Deal with output operands. 8418 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8419 if (OpInfo.Type == InlineAsm::isOutput) { 8420 SDValue Val; 8421 // Skip trivial output operands. 8422 if (OpInfo.AssignedRegs.Regs.empty()) 8423 continue; 8424 8425 switch (OpInfo.ConstraintType) { 8426 case TargetLowering::C_Register: 8427 case TargetLowering::C_RegisterClass: 8428 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8429 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8430 break; 8431 case TargetLowering::C_Immediate: 8432 case TargetLowering::C_Other: 8433 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8434 OpInfo, DAG); 8435 break; 8436 case TargetLowering::C_Memory: 8437 break; // Already handled. 8438 case TargetLowering::C_Unknown: 8439 assert(false && "Unexpected unknown constraint"); 8440 } 8441 8442 // Indirect output manifest as stores. Record output chains. 8443 if (OpInfo.isIndirect) { 8444 const Value *Ptr = OpInfo.CallOperandVal; 8445 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8446 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8447 MachinePointerInfo(Ptr)); 8448 OutChains.push_back(Store); 8449 } else { 8450 // generate CopyFromRegs to associated registers. 8451 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8452 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8453 for (const SDValue &V : Val->op_values()) 8454 handleRegAssign(V); 8455 } else 8456 handleRegAssign(Val); 8457 } 8458 } 8459 } 8460 8461 // Set results. 8462 if (!ResultValues.empty()) { 8463 assert(CurResultType == ResultTypes.end() && 8464 "Mismatch in number of ResultTypes"); 8465 assert(ResultValues.size() == ResultTypes.size() && 8466 "Mismatch in number of output operands in asm result"); 8467 8468 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8469 DAG.getVTList(ResultVTs), ResultValues); 8470 setValue(CS.getInstruction(), V); 8471 } 8472 8473 // Collect store chains. 8474 if (!OutChains.empty()) 8475 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8476 8477 // Only Update Root if inline assembly has a memory effect. 8478 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8479 DAG.setRoot(Chain); 8480 } 8481 8482 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8483 const Twine &Message) { 8484 LLVMContext &Ctx = *DAG.getContext(); 8485 Ctx.emitError(CS.getInstruction(), Message); 8486 8487 // Make sure we leave the DAG in a valid state 8488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8489 SmallVector<EVT, 1> ValueVTs; 8490 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8491 8492 if (ValueVTs.empty()) 8493 return; 8494 8495 SmallVector<SDValue, 1> Ops; 8496 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8497 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8498 8499 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8500 } 8501 8502 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8503 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8504 MVT::Other, getRoot(), 8505 getValue(I.getArgOperand(0)), 8506 DAG.getSrcValue(I.getArgOperand(0)))); 8507 } 8508 8509 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8510 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8511 const DataLayout &DL = DAG.getDataLayout(); 8512 SDValue V = DAG.getVAArg( 8513 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8514 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8515 DL.getABITypeAlignment(I.getType())); 8516 DAG.setRoot(V.getValue(1)); 8517 8518 if (I.getType()->isPointerTy()) 8519 V = DAG.getPtrExtOrTrunc( 8520 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8521 setValue(&I, V); 8522 } 8523 8524 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8525 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8526 MVT::Other, getRoot(), 8527 getValue(I.getArgOperand(0)), 8528 DAG.getSrcValue(I.getArgOperand(0)))); 8529 } 8530 8531 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8532 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8533 MVT::Other, getRoot(), 8534 getValue(I.getArgOperand(0)), 8535 getValue(I.getArgOperand(1)), 8536 DAG.getSrcValue(I.getArgOperand(0)), 8537 DAG.getSrcValue(I.getArgOperand(1)))); 8538 } 8539 8540 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8541 const Instruction &I, 8542 SDValue Op) { 8543 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8544 if (!Range) 8545 return Op; 8546 8547 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8548 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8549 return Op; 8550 8551 APInt Lo = CR.getUnsignedMin(); 8552 if (!Lo.isMinValue()) 8553 return Op; 8554 8555 APInt Hi = CR.getUnsignedMax(); 8556 unsigned Bits = std::max(Hi.getActiveBits(), 8557 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8558 8559 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8560 8561 SDLoc SL = getCurSDLoc(); 8562 8563 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8564 DAG.getValueType(SmallVT)); 8565 unsigned NumVals = Op.getNode()->getNumValues(); 8566 if (NumVals == 1) 8567 return ZExt; 8568 8569 SmallVector<SDValue, 4> Ops; 8570 8571 Ops.push_back(ZExt); 8572 for (unsigned I = 1; I != NumVals; ++I) 8573 Ops.push_back(Op.getValue(I)); 8574 8575 return DAG.getMergeValues(Ops, SL); 8576 } 8577 8578 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8579 /// the call being lowered. 8580 /// 8581 /// This is a helper for lowering intrinsics that follow a target calling 8582 /// convention or require stack pointer adjustment. Only a subset of the 8583 /// intrinsic's operands need to participate in the calling convention. 8584 void SelectionDAGBuilder::populateCallLoweringInfo( 8585 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8586 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8587 bool IsPatchPoint) { 8588 TargetLowering::ArgListTy Args; 8589 Args.reserve(NumArgs); 8590 8591 // Populate the argument list. 8592 // Attributes for args start at offset 1, after the return attribute. 8593 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8594 ArgI != ArgE; ++ArgI) { 8595 const Value *V = Call->getOperand(ArgI); 8596 8597 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8598 8599 TargetLowering::ArgListEntry Entry; 8600 Entry.Node = getValue(V); 8601 Entry.Ty = V->getType(); 8602 Entry.setAttributes(Call, ArgI); 8603 Args.push_back(Entry); 8604 } 8605 8606 CLI.setDebugLoc(getCurSDLoc()) 8607 .setChain(getRoot()) 8608 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8609 .setDiscardResult(Call->use_empty()) 8610 .setIsPatchPoint(IsPatchPoint); 8611 } 8612 8613 /// Add a stack map intrinsic call's live variable operands to a stackmap 8614 /// or patchpoint target node's operand list. 8615 /// 8616 /// Constants are converted to TargetConstants purely as an optimization to 8617 /// avoid constant materialization and register allocation. 8618 /// 8619 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8620 /// generate addess computation nodes, and so FinalizeISel can convert the 8621 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8622 /// address materialization and register allocation, but may also be required 8623 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8624 /// alloca in the entry block, then the runtime may assume that the alloca's 8625 /// StackMap location can be read immediately after compilation and that the 8626 /// location is valid at any point during execution (this is similar to the 8627 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8628 /// only available in a register, then the runtime would need to trap when 8629 /// execution reaches the StackMap in order to read the alloca's location. 8630 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8631 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8632 SelectionDAGBuilder &Builder) { 8633 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8634 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8635 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8636 Ops.push_back( 8637 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8638 Ops.push_back( 8639 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8640 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8641 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8642 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8643 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8644 } else 8645 Ops.push_back(OpVal); 8646 } 8647 } 8648 8649 /// Lower llvm.experimental.stackmap directly to its target opcode. 8650 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8651 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8652 // [live variables...]) 8653 8654 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8655 8656 SDValue Chain, InFlag, Callee, NullPtr; 8657 SmallVector<SDValue, 32> Ops; 8658 8659 SDLoc DL = getCurSDLoc(); 8660 Callee = getValue(CI.getCalledValue()); 8661 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8662 8663 // The stackmap intrinsic only records the live variables (the arguemnts 8664 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8665 // intrinsic, this won't be lowered to a function call. This means we don't 8666 // have to worry about calling conventions and target specific lowering code. 8667 // Instead we perform the call lowering right here. 8668 // 8669 // chain, flag = CALLSEQ_START(chain, 0, 0) 8670 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8671 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8672 // 8673 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8674 InFlag = Chain.getValue(1); 8675 8676 // Add the <id> and <numBytes> constants. 8677 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8678 Ops.push_back(DAG.getTargetConstant( 8679 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8680 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8681 Ops.push_back(DAG.getTargetConstant( 8682 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8683 MVT::i32)); 8684 8685 // Push live variables for the stack map. 8686 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8687 8688 // We are not pushing any register mask info here on the operands list, 8689 // because the stackmap doesn't clobber anything. 8690 8691 // Push the chain and the glue flag. 8692 Ops.push_back(Chain); 8693 Ops.push_back(InFlag); 8694 8695 // Create the STACKMAP node. 8696 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8697 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8698 Chain = SDValue(SM, 0); 8699 InFlag = Chain.getValue(1); 8700 8701 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8702 8703 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8704 8705 // Set the root to the target-lowered call chain. 8706 DAG.setRoot(Chain); 8707 8708 // Inform the Frame Information that we have a stackmap in this function. 8709 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8710 } 8711 8712 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8713 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8714 const BasicBlock *EHPadBB) { 8715 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8716 // i32 <numBytes>, 8717 // i8* <target>, 8718 // i32 <numArgs>, 8719 // [Args...], 8720 // [live variables...]) 8721 8722 CallingConv::ID CC = CS.getCallingConv(); 8723 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8724 bool HasDef = !CS->getType()->isVoidTy(); 8725 SDLoc dl = getCurSDLoc(); 8726 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8727 8728 // Handle immediate and symbolic callees. 8729 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8730 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8731 /*isTarget=*/true); 8732 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8733 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8734 SDLoc(SymbolicCallee), 8735 SymbolicCallee->getValueType(0)); 8736 8737 // Get the real number of arguments participating in the call <numArgs> 8738 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8739 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8740 8741 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8742 // Intrinsics include all meta-operands up to but not including CC. 8743 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8744 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8745 "Not enough arguments provided to the patchpoint intrinsic"); 8746 8747 // For AnyRegCC the arguments are lowered later on manually. 8748 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8749 Type *ReturnTy = 8750 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8751 8752 TargetLowering::CallLoweringInfo CLI(DAG); 8753 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8754 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8755 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8756 8757 SDNode *CallEnd = Result.second.getNode(); 8758 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8759 CallEnd = CallEnd->getOperand(0).getNode(); 8760 8761 /// Get a call instruction from the call sequence chain. 8762 /// Tail calls are not allowed. 8763 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8764 "Expected a callseq node."); 8765 SDNode *Call = CallEnd->getOperand(0).getNode(); 8766 bool HasGlue = Call->getGluedNode(); 8767 8768 // Replace the target specific call node with the patchable intrinsic. 8769 SmallVector<SDValue, 8> Ops; 8770 8771 // Add the <id> and <numBytes> constants. 8772 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8773 Ops.push_back(DAG.getTargetConstant( 8774 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8775 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8776 Ops.push_back(DAG.getTargetConstant( 8777 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8778 MVT::i32)); 8779 8780 // Add the callee. 8781 Ops.push_back(Callee); 8782 8783 // Adjust <numArgs> to account for any arguments that have been passed on the 8784 // stack instead. 8785 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8786 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8787 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8788 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8789 8790 // Add the calling convention 8791 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8792 8793 // Add the arguments we omitted previously. The register allocator should 8794 // place these in any free register. 8795 if (IsAnyRegCC) 8796 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8797 Ops.push_back(getValue(CS.getArgument(i))); 8798 8799 // Push the arguments from the call instruction up to the register mask. 8800 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8801 Ops.append(Call->op_begin() + 2, e); 8802 8803 // Push live variables for the stack map. 8804 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8805 8806 // Push the register mask info. 8807 if (HasGlue) 8808 Ops.push_back(*(Call->op_end()-2)); 8809 else 8810 Ops.push_back(*(Call->op_end()-1)); 8811 8812 // Push the chain (this is originally the first operand of the call, but 8813 // becomes now the last or second to last operand). 8814 Ops.push_back(*(Call->op_begin())); 8815 8816 // Push the glue flag (last operand). 8817 if (HasGlue) 8818 Ops.push_back(*(Call->op_end()-1)); 8819 8820 SDVTList NodeTys; 8821 if (IsAnyRegCC && HasDef) { 8822 // Create the return types based on the intrinsic definition 8823 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8824 SmallVector<EVT, 3> ValueVTs; 8825 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8826 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8827 8828 // There is always a chain and a glue type at the end 8829 ValueVTs.push_back(MVT::Other); 8830 ValueVTs.push_back(MVT::Glue); 8831 NodeTys = DAG.getVTList(ValueVTs); 8832 } else 8833 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8834 8835 // Replace the target specific call node with a PATCHPOINT node. 8836 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8837 dl, NodeTys, Ops); 8838 8839 // Update the NodeMap. 8840 if (HasDef) { 8841 if (IsAnyRegCC) 8842 setValue(CS.getInstruction(), SDValue(MN, 0)); 8843 else 8844 setValue(CS.getInstruction(), Result.first); 8845 } 8846 8847 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8848 // call sequence. Furthermore the location of the chain and glue can change 8849 // when the AnyReg calling convention is used and the intrinsic returns a 8850 // value. 8851 if (IsAnyRegCC && HasDef) { 8852 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8853 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8854 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8855 } else 8856 DAG.ReplaceAllUsesWith(Call, MN); 8857 DAG.DeleteNode(Call); 8858 8859 // Inform the Frame Information that we have a patchpoint in this function. 8860 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8861 } 8862 8863 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8864 unsigned Intrinsic) { 8865 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8866 SDValue Op1 = getValue(I.getArgOperand(0)); 8867 SDValue Op2; 8868 if (I.getNumArgOperands() > 1) 8869 Op2 = getValue(I.getArgOperand(1)); 8870 SDLoc dl = getCurSDLoc(); 8871 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8872 SDValue Res; 8873 FastMathFlags FMF; 8874 if (isa<FPMathOperator>(I)) 8875 FMF = I.getFastMathFlags(); 8876 8877 switch (Intrinsic) { 8878 case Intrinsic::experimental_vector_reduce_v2_fadd: 8879 if (FMF.allowReassoc()) 8880 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8881 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8882 else 8883 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8884 break; 8885 case Intrinsic::experimental_vector_reduce_v2_fmul: 8886 if (FMF.allowReassoc()) 8887 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8888 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8889 else 8890 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8891 break; 8892 case Intrinsic::experimental_vector_reduce_add: 8893 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8894 break; 8895 case Intrinsic::experimental_vector_reduce_mul: 8896 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8897 break; 8898 case Intrinsic::experimental_vector_reduce_and: 8899 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8900 break; 8901 case Intrinsic::experimental_vector_reduce_or: 8902 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8903 break; 8904 case Intrinsic::experimental_vector_reduce_xor: 8905 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8906 break; 8907 case Intrinsic::experimental_vector_reduce_smax: 8908 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8909 break; 8910 case Intrinsic::experimental_vector_reduce_smin: 8911 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8912 break; 8913 case Intrinsic::experimental_vector_reduce_umax: 8914 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8915 break; 8916 case Intrinsic::experimental_vector_reduce_umin: 8917 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8918 break; 8919 case Intrinsic::experimental_vector_reduce_fmax: 8920 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8921 break; 8922 case Intrinsic::experimental_vector_reduce_fmin: 8923 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8924 break; 8925 default: 8926 llvm_unreachable("Unhandled vector reduce intrinsic"); 8927 } 8928 setValue(&I, Res); 8929 } 8930 8931 /// Returns an AttributeList representing the attributes applied to the return 8932 /// value of the given call. 8933 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8934 SmallVector<Attribute::AttrKind, 2> Attrs; 8935 if (CLI.RetSExt) 8936 Attrs.push_back(Attribute::SExt); 8937 if (CLI.RetZExt) 8938 Attrs.push_back(Attribute::ZExt); 8939 if (CLI.IsInReg) 8940 Attrs.push_back(Attribute::InReg); 8941 8942 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8943 Attrs); 8944 } 8945 8946 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8947 /// implementation, which just calls LowerCall. 8948 /// FIXME: When all targets are 8949 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8950 std::pair<SDValue, SDValue> 8951 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8952 // Handle the incoming return values from the call. 8953 CLI.Ins.clear(); 8954 Type *OrigRetTy = CLI.RetTy; 8955 SmallVector<EVT, 4> RetTys; 8956 SmallVector<uint64_t, 4> Offsets; 8957 auto &DL = CLI.DAG.getDataLayout(); 8958 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8959 8960 if (CLI.IsPostTypeLegalization) { 8961 // If we are lowering a libcall after legalization, split the return type. 8962 SmallVector<EVT, 4> OldRetTys; 8963 SmallVector<uint64_t, 4> OldOffsets; 8964 RetTys.swap(OldRetTys); 8965 Offsets.swap(OldOffsets); 8966 8967 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8968 EVT RetVT = OldRetTys[i]; 8969 uint64_t Offset = OldOffsets[i]; 8970 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8971 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8972 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8973 RetTys.append(NumRegs, RegisterVT); 8974 for (unsigned j = 0; j != NumRegs; ++j) 8975 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8976 } 8977 } 8978 8979 SmallVector<ISD::OutputArg, 4> Outs; 8980 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8981 8982 bool CanLowerReturn = 8983 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8984 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8985 8986 SDValue DemoteStackSlot; 8987 int DemoteStackIdx = -100; 8988 if (!CanLowerReturn) { 8989 // FIXME: equivalent assert? 8990 // assert(!CS.hasInAllocaArgument() && 8991 // "sret demotion is incompatible with inalloca"); 8992 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8993 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8994 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8995 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8996 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8997 DL.getAllocaAddrSpace()); 8998 8999 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9000 ArgListEntry Entry; 9001 Entry.Node = DemoteStackSlot; 9002 Entry.Ty = StackSlotPtrType; 9003 Entry.IsSExt = false; 9004 Entry.IsZExt = false; 9005 Entry.IsInReg = false; 9006 Entry.IsSRet = true; 9007 Entry.IsNest = false; 9008 Entry.IsByVal = false; 9009 Entry.IsReturned = false; 9010 Entry.IsSwiftSelf = false; 9011 Entry.IsSwiftError = false; 9012 Entry.Alignment = Align; 9013 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9014 CLI.NumFixedArgs += 1; 9015 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9016 9017 // sret demotion isn't compatible with tail-calls, since the sret argument 9018 // points into the callers stack frame. 9019 CLI.IsTailCall = false; 9020 } else { 9021 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9022 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9023 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9024 ISD::ArgFlagsTy Flags; 9025 if (NeedsRegBlock) { 9026 Flags.setInConsecutiveRegs(); 9027 if (I == RetTys.size() - 1) 9028 Flags.setInConsecutiveRegsLast(); 9029 } 9030 EVT VT = RetTys[I]; 9031 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9032 CLI.CallConv, VT); 9033 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9034 CLI.CallConv, VT); 9035 for (unsigned i = 0; i != NumRegs; ++i) { 9036 ISD::InputArg MyFlags; 9037 MyFlags.Flags = Flags; 9038 MyFlags.VT = RegisterVT; 9039 MyFlags.ArgVT = VT; 9040 MyFlags.Used = CLI.IsReturnValueUsed; 9041 if (CLI.RetTy->isPointerTy()) { 9042 MyFlags.Flags.setPointer(); 9043 MyFlags.Flags.setPointerAddrSpace( 9044 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9045 } 9046 if (CLI.RetSExt) 9047 MyFlags.Flags.setSExt(); 9048 if (CLI.RetZExt) 9049 MyFlags.Flags.setZExt(); 9050 if (CLI.IsInReg) 9051 MyFlags.Flags.setInReg(); 9052 CLI.Ins.push_back(MyFlags); 9053 } 9054 } 9055 } 9056 9057 // We push in swifterror return as the last element of CLI.Ins. 9058 ArgListTy &Args = CLI.getArgs(); 9059 if (supportSwiftError()) { 9060 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9061 if (Args[i].IsSwiftError) { 9062 ISD::InputArg MyFlags; 9063 MyFlags.VT = getPointerTy(DL); 9064 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9065 MyFlags.Flags.setSwiftError(); 9066 CLI.Ins.push_back(MyFlags); 9067 } 9068 } 9069 } 9070 9071 // Handle all of the outgoing arguments. 9072 CLI.Outs.clear(); 9073 CLI.OutVals.clear(); 9074 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9075 SmallVector<EVT, 4> ValueVTs; 9076 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9077 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9078 Type *FinalType = Args[i].Ty; 9079 if (Args[i].IsByVal) 9080 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9081 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9082 FinalType, CLI.CallConv, CLI.IsVarArg); 9083 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9084 ++Value) { 9085 EVT VT = ValueVTs[Value]; 9086 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9087 SDValue Op = SDValue(Args[i].Node.getNode(), 9088 Args[i].Node.getResNo() + Value); 9089 ISD::ArgFlagsTy Flags; 9090 9091 // Certain targets (such as MIPS), may have a different ABI alignment 9092 // for a type depending on the context. Give the target a chance to 9093 // specify the alignment it wants. 9094 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 9095 9096 if (Args[i].Ty->isPointerTy()) { 9097 Flags.setPointer(); 9098 Flags.setPointerAddrSpace( 9099 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9100 } 9101 if (Args[i].IsZExt) 9102 Flags.setZExt(); 9103 if (Args[i].IsSExt) 9104 Flags.setSExt(); 9105 if (Args[i].IsInReg) { 9106 // If we are using vectorcall calling convention, a structure that is 9107 // passed InReg - is surely an HVA 9108 if (CLI.CallConv == CallingConv::X86_VectorCall && 9109 isa<StructType>(FinalType)) { 9110 // The first value of a structure is marked 9111 if (0 == Value) 9112 Flags.setHvaStart(); 9113 Flags.setHva(); 9114 } 9115 // Set InReg Flag 9116 Flags.setInReg(); 9117 } 9118 if (Args[i].IsSRet) 9119 Flags.setSRet(); 9120 if (Args[i].IsSwiftSelf) 9121 Flags.setSwiftSelf(); 9122 if (Args[i].IsSwiftError) 9123 Flags.setSwiftError(); 9124 if (Args[i].IsByVal) 9125 Flags.setByVal(); 9126 if (Args[i].IsInAlloca) { 9127 Flags.setInAlloca(); 9128 // Set the byval flag for CCAssignFn callbacks that don't know about 9129 // inalloca. This way we can know how many bytes we should've allocated 9130 // and how many bytes a callee cleanup function will pop. If we port 9131 // inalloca to more targets, we'll have to add custom inalloca handling 9132 // in the various CC lowering callbacks. 9133 Flags.setByVal(); 9134 } 9135 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9136 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9137 Type *ElementTy = Ty->getElementType(); 9138 9139 unsigned FrameSize = DL.getTypeAllocSize( 9140 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9141 Flags.setByValSize(FrameSize); 9142 9143 // info is not there but there are cases it cannot get right. 9144 unsigned FrameAlign; 9145 if (Args[i].Alignment) 9146 FrameAlign = Args[i].Alignment; 9147 else 9148 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9149 Flags.setByValAlign(FrameAlign); 9150 } 9151 if (Args[i].IsNest) 9152 Flags.setNest(); 9153 if (NeedsRegBlock) 9154 Flags.setInConsecutiveRegs(); 9155 Flags.setOrigAlign(OriginalAlignment); 9156 9157 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9158 CLI.CallConv, VT); 9159 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9160 CLI.CallConv, VT); 9161 SmallVector<SDValue, 4> Parts(NumParts); 9162 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9163 9164 if (Args[i].IsSExt) 9165 ExtendKind = ISD::SIGN_EXTEND; 9166 else if (Args[i].IsZExt) 9167 ExtendKind = ISD::ZERO_EXTEND; 9168 9169 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9170 // for now. 9171 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9172 CanLowerReturn) { 9173 assert((CLI.RetTy == Args[i].Ty || 9174 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9175 CLI.RetTy->getPointerAddressSpace() == 9176 Args[i].Ty->getPointerAddressSpace())) && 9177 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9178 // Before passing 'returned' to the target lowering code, ensure that 9179 // either the register MVT and the actual EVT are the same size or that 9180 // the return value and argument are extended in the same way; in these 9181 // cases it's safe to pass the argument register value unchanged as the 9182 // return register value (although it's at the target's option whether 9183 // to do so) 9184 // TODO: allow code generation to take advantage of partially preserved 9185 // registers rather than clobbering the entire register when the 9186 // parameter extension method is not compatible with the return 9187 // extension method 9188 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9189 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9190 CLI.RetZExt == Args[i].IsZExt)) 9191 Flags.setReturned(); 9192 } 9193 9194 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9195 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9196 9197 for (unsigned j = 0; j != NumParts; ++j) { 9198 // if it isn't first piece, alignment must be 1 9199 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9200 i < CLI.NumFixedArgs, 9201 i, j*Parts[j].getValueType().getStoreSize()); 9202 if (NumParts > 1 && j == 0) 9203 MyFlags.Flags.setSplit(); 9204 else if (j != 0) { 9205 MyFlags.Flags.setOrigAlign(1); 9206 if (j == NumParts - 1) 9207 MyFlags.Flags.setSplitEnd(); 9208 } 9209 9210 CLI.Outs.push_back(MyFlags); 9211 CLI.OutVals.push_back(Parts[j]); 9212 } 9213 9214 if (NeedsRegBlock && Value == NumValues - 1) 9215 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9216 } 9217 } 9218 9219 SmallVector<SDValue, 4> InVals; 9220 CLI.Chain = LowerCall(CLI, InVals); 9221 9222 // Update CLI.InVals to use outside of this function. 9223 CLI.InVals = InVals; 9224 9225 // Verify that the target's LowerCall behaved as expected. 9226 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9227 "LowerCall didn't return a valid chain!"); 9228 assert((!CLI.IsTailCall || InVals.empty()) && 9229 "LowerCall emitted a return value for a tail call!"); 9230 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9231 "LowerCall didn't emit the correct number of values!"); 9232 9233 // For a tail call, the return value is merely live-out and there aren't 9234 // any nodes in the DAG representing it. Return a special value to 9235 // indicate that a tail call has been emitted and no more Instructions 9236 // should be processed in the current block. 9237 if (CLI.IsTailCall) { 9238 CLI.DAG.setRoot(CLI.Chain); 9239 return std::make_pair(SDValue(), SDValue()); 9240 } 9241 9242 #ifndef NDEBUG 9243 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9244 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9245 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9246 "LowerCall emitted a value with the wrong type!"); 9247 } 9248 #endif 9249 9250 SmallVector<SDValue, 4> ReturnValues; 9251 if (!CanLowerReturn) { 9252 // The instruction result is the result of loading from the 9253 // hidden sret parameter. 9254 SmallVector<EVT, 1> PVTs; 9255 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9256 9257 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9258 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9259 EVT PtrVT = PVTs[0]; 9260 9261 unsigned NumValues = RetTys.size(); 9262 ReturnValues.resize(NumValues); 9263 SmallVector<SDValue, 4> Chains(NumValues); 9264 9265 // An aggregate return value cannot wrap around the address space, so 9266 // offsets to its parts don't wrap either. 9267 SDNodeFlags Flags; 9268 Flags.setNoUnsignedWrap(true); 9269 9270 for (unsigned i = 0; i < NumValues; ++i) { 9271 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9272 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9273 PtrVT), Flags); 9274 SDValue L = CLI.DAG.getLoad( 9275 RetTys[i], CLI.DL, CLI.Chain, Add, 9276 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9277 DemoteStackIdx, Offsets[i]), 9278 /* Alignment = */ 1); 9279 ReturnValues[i] = L; 9280 Chains[i] = L.getValue(1); 9281 } 9282 9283 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9284 } else { 9285 // Collect the legal value parts into potentially illegal values 9286 // that correspond to the original function's return values. 9287 Optional<ISD::NodeType> AssertOp; 9288 if (CLI.RetSExt) 9289 AssertOp = ISD::AssertSext; 9290 else if (CLI.RetZExt) 9291 AssertOp = ISD::AssertZext; 9292 unsigned CurReg = 0; 9293 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9294 EVT VT = RetTys[I]; 9295 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9296 CLI.CallConv, VT); 9297 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9298 CLI.CallConv, VT); 9299 9300 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9301 NumRegs, RegisterVT, VT, nullptr, 9302 CLI.CallConv, AssertOp)); 9303 CurReg += NumRegs; 9304 } 9305 9306 // For a function returning void, there is no return value. We can't create 9307 // such a node, so we just return a null return value in that case. In 9308 // that case, nothing will actually look at the value. 9309 if (ReturnValues.empty()) 9310 return std::make_pair(SDValue(), CLI.Chain); 9311 } 9312 9313 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9314 CLI.DAG.getVTList(RetTys), ReturnValues); 9315 return std::make_pair(Res, CLI.Chain); 9316 } 9317 9318 void TargetLowering::LowerOperationWrapper(SDNode *N, 9319 SmallVectorImpl<SDValue> &Results, 9320 SelectionDAG &DAG) const { 9321 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9322 Results.push_back(Res); 9323 } 9324 9325 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9326 llvm_unreachable("LowerOperation not implemented for this target!"); 9327 } 9328 9329 void 9330 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9331 SDValue Op = getNonRegisterValue(V); 9332 assert((Op.getOpcode() != ISD::CopyFromReg || 9333 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9334 "Copy from a reg to the same reg!"); 9335 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9336 9337 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9338 // If this is an InlineAsm we have to match the registers required, not the 9339 // notional registers required by the type. 9340 9341 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9342 None); // This is not an ABI copy. 9343 SDValue Chain = DAG.getEntryNode(); 9344 9345 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9346 FuncInfo.PreferredExtendType.end()) 9347 ? ISD::ANY_EXTEND 9348 : FuncInfo.PreferredExtendType[V]; 9349 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9350 PendingExports.push_back(Chain); 9351 } 9352 9353 #include "llvm/CodeGen/SelectionDAGISel.h" 9354 9355 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9356 /// entry block, return true. This includes arguments used by switches, since 9357 /// the switch may expand into multiple basic blocks. 9358 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9359 // With FastISel active, we may be splitting blocks, so force creation 9360 // of virtual registers for all non-dead arguments. 9361 if (FastISel) 9362 return A->use_empty(); 9363 9364 const BasicBlock &Entry = A->getParent()->front(); 9365 for (const User *U : A->users()) 9366 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9367 return false; // Use not in entry block. 9368 9369 return true; 9370 } 9371 9372 using ArgCopyElisionMapTy = 9373 DenseMap<const Argument *, 9374 std::pair<const AllocaInst *, const StoreInst *>>; 9375 9376 /// Scan the entry block of the function in FuncInfo for arguments that look 9377 /// like copies into a local alloca. Record any copied arguments in 9378 /// ArgCopyElisionCandidates. 9379 static void 9380 findArgumentCopyElisionCandidates(const DataLayout &DL, 9381 FunctionLoweringInfo *FuncInfo, 9382 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9383 // Record the state of every static alloca used in the entry block. Argument 9384 // allocas are all used in the entry block, so we need approximately as many 9385 // entries as we have arguments. 9386 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9387 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9388 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9389 StaticAllocas.reserve(NumArgs * 2); 9390 9391 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9392 if (!V) 9393 return nullptr; 9394 V = V->stripPointerCasts(); 9395 const auto *AI = dyn_cast<AllocaInst>(V); 9396 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9397 return nullptr; 9398 auto Iter = StaticAllocas.insert({AI, Unknown}); 9399 return &Iter.first->second; 9400 }; 9401 9402 // Look for stores of arguments to static allocas. Look through bitcasts and 9403 // GEPs to handle type coercions, as long as the alloca is fully initialized 9404 // by the store. Any non-store use of an alloca escapes it and any subsequent 9405 // unanalyzed store might write it. 9406 // FIXME: Handle structs initialized with multiple stores. 9407 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9408 // Look for stores, and handle non-store uses conservatively. 9409 const auto *SI = dyn_cast<StoreInst>(&I); 9410 if (!SI) { 9411 // We will look through cast uses, so ignore them completely. 9412 if (I.isCast()) 9413 continue; 9414 // Ignore debug info intrinsics, they don't escape or store to allocas. 9415 if (isa<DbgInfoIntrinsic>(I)) 9416 continue; 9417 // This is an unknown instruction. Assume it escapes or writes to all 9418 // static alloca operands. 9419 for (const Use &U : I.operands()) { 9420 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9421 *Info = StaticAllocaInfo::Clobbered; 9422 } 9423 continue; 9424 } 9425 9426 // If the stored value is a static alloca, mark it as escaped. 9427 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9428 *Info = StaticAllocaInfo::Clobbered; 9429 9430 // Check if the destination is a static alloca. 9431 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9432 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9433 if (!Info) 9434 continue; 9435 const AllocaInst *AI = cast<AllocaInst>(Dst); 9436 9437 // Skip allocas that have been initialized or clobbered. 9438 if (*Info != StaticAllocaInfo::Unknown) 9439 continue; 9440 9441 // Check if the stored value is an argument, and that this store fully 9442 // initializes the alloca. Don't elide copies from the same argument twice. 9443 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9444 const auto *Arg = dyn_cast<Argument>(Val); 9445 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9446 Arg->getType()->isEmptyTy() || 9447 DL.getTypeStoreSize(Arg->getType()) != 9448 DL.getTypeAllocSize(AI->getAllocatedType()) || 9449 ArgCopyElisionCandidates.count(Arg)) { 9450 *Info = StaticAllocaInfo::Clobbered; 9451 continue; 9452 } 9453 9454 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9455 << '\n'); 9456 9457 // Mark this alloca and store for argument copy elision. 9458 *Info = StaticAllocaInfo::Elidable; 9459 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9460 9461 // Stop scanning if we've seen all arguments. This will happen early in -O0 9462 // builds, which is useful, because -O0 builds have large entry blocks and 9463 // many allocas. 9464 if (ArgCopyElisionCandidates.size() == NumArgs) 9465 break; 9466 } 9467 } 9468 9469 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9470 /// ArgVal is a load from a suitable fixed stack object. 9471 static void tryToElideArgumentCopy( 9472 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9473 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9474 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9475 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9476 SDValue ArgVal, bool &ArgHasUses) { 9477 // Check if this is a load from a fixed stack object. 9478 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9479 if (!LNode) 9480 return; 9481 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9482 if (!FINode) 9483 return; 9484 9485 // Check that the fixed stack object is the right size and alignment. 9486 // Look at the alignment that the user wrote on the alloca instead of looking 9487 // at the stack object. 9488 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9489 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9490 const AllocaInst *AI = ArgCopyIter->second.first; 9491 int FixedIndex = FINode->getIndex(); 9492 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9493 int OldIndex = AllocaIndex; 9494 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9495 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9496 LLVM_DEBUG( 9497 dbgs() << " argument copy elision failed due to bad fixed stack " 9498 "object size\n"); 9499 return; 9500 } 9501 unsigned RequiredAlignment = AI->getAlignment(); 9502 if (!RequiredAlignment) { 9503 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9504 AI->getAllocatedType()); 9505 } 9506 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9507 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9508 "greater than stack argument alignment (" 9509 << RequiredAlignment << " vs " 9510 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9511 return; 9512 } 9513 9514 // Perform the elision. Delete the old stack object and replace its only use 9515 // in the variable info map. Mark the stack object as mutable. 9516 LLVM_DEBUG({ 9517 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9518 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9519 << '\n'; 9520 }); 9521 MFI.RemoveStackObject(OldIndex); 9522 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9523 AllocaIndex = FixedIndex; 9524 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9525 Chains.push_back(ArgVal.getValue(1)); 9526 9527 // Avoid emitting code for the store implementing the copy. 9528 const StoreInst *SI = ArgCopyIter->second.second; 9529 ElidedArgCopyInstrs.insert(SI); 9530 9531 // Check for uses of the argument again so that we can avoid exporting ArgVal 9532 // if it is't used by anything other than the store. 9533 for (const Value *U : Arg.users()) { 9534 if (U != SI) { 9535 ArgHasUses = true; 9536 break; 9537 } 9538 } 9539 } 9540 9541 void SelectionDAGISel::LowerArguments(const Function &F) { 9542 SelectionDAG &DAG = SDB->DAG; 9543 SDLoc dl = SDB->getCurSDLoc(); 9544 const DataLayout &DL = DAG.getDataLayout(); 9545 SmallVector<ISD::InputArg, 16> Ins; 9546 9547 if (!FuncInfo->CanLowerReturn) { 9548 // Put in an sret pointer parameter before all the other parameters. 9549 SmallVector<EVT, 1> ValueVTs; 9550 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9551 F.getReturnType()->getPointerTo( 9552 DAG.getDataLayout().getAllocaAddrSpace()), 9553 ValueVTs); 9554 9555 // NOTE: Assuming that a pointer will never break down to more than one VT 9556 // or one register. 9557 ISD::ArgFlagsTy Flags; 9558 Flags.setSRet(); 9559 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9560 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9561 ISD::InputArg::NoArgIndex, 0); 9562 Ins.push_back(RetArg); 9563 } 9564 9565 // Look for stores of arguments to static allocas. Mark such arguments with a 9566 // flag to ask the target to give us the memory location of that argument if 9567 // available. 9568 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9569 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9570 9571 // Set up the incoming argument description vector. 9572 for (const Argument &Arg : F.args()) { 9573 unsigned ArgNo = Arg.getArgNo(); 9574 SmallVector<EVT, 4> ValueVTs; 9575 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9576 bool isArgValueUsed = !Arg.use_empty(); 9577 unsigned PartBase = 0; 9578 Type *FinalType = Arg.getType(); 9579 if (Arg.hasAttribute(Attribute::ByVal)) 9580 FinalType = Arg.getParamByValType(); 9581 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9582 FinalType, F.getCallingConv(), F.isVarArg()); 9583 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9584 Value != NumValues; ++Value) { 9585 EVT VT = ValueVTs[Value]; 9586 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9587 ISD::ArgFlagsTy Flags; 9588 9589 // Certain targets (such as MIPS), may have a different ABI alignment 9590 // for a type depending on the context. Give the target a chance to 9591 // specify the alignment it wants. 9592 unsigned OriginalAlignment = 9593 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9594 9595 if (Arg.getType()->isPointerTy()) { 9596 Flags.setPointer(); 9597 Flags.setPointerAddrSpace( 9598 cast<PointerType>(Arg.getType())->getAddressSpace()); 9599 } 9600 if (Arg.hasAttribute(Attribute::ZExt)) 9601 Flags.setZExt(); 9602 if (Arg.hasAttribute(Attribute::SExt)) 9603 Flags.setSExt(); 9604 if (Arg.hasAttribute(Attribute::InReg)) { 9605 // If we are using vectorcall calling convention, a structure that is 9606 // passed InReg - is surely an HVA 9607 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9608 isa<StructType>(Arg.getType())) { 9609 // The first value of a structure is marked 9610 if (0 == Value) 9611 Flags.setHvaStart(); 9612 Flags.setHva(); 9613 } 9614 // Set InReg Flag 9615 Flags.setInReg(); 9616 } 9617 if (Arg.hasAttribute(Attribute::StructRet)) 9618 Flags.setSRet(); 9619 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9620 Flags.setSwiftSelf(); 9621 if (Arg.hasAttribute(Attribute::SwiftError)) 9622 Flags.setSwiftError(); 9623 if (Arg.hasAttribute(Attribute::ByVal)) 9624 Flags.setByVal(); 9625 if (Arg.hasAttribute(Attribute::InAlloca)) { 9626 Flags.setInAlloca(); 9627 // Set the byval flag for CCAssignFn callbacks that don't know about 9628 // inalloca. This way we can know how many bytes we should've allocated 9629 // and how many bytes a callee cleanup function will pop. If we port 9630 // inalloca to more targets, we'll have to add custom inalloca handling 9631 // in the various CC lowering callbacks. 9632 Flags.setByVal(); 9633 } 9634 if (F.getCallingConv() == CallingConv::X86_INTR) { 9635 // IA Interrupt passes frame (1st parameter) by value in the stack. 9636 if (ArgNo == 0) 9637 Flags.setByVal(); 9638 } 9639 if (Flags.isByVal() || Flags.isInAlloca()) { 9640 Type *ElementTy = Arg.getParamByValType(); 9641 9642 // For ByVal, size and alignment should be passed from FE. BE will 9643 // guess if this info is not there but there are cases it cannot get 9644 // right. 9645 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9646 Flags.setByValSize(FrameSize); 9647 9648 unsigned FrameAlign; 9649 if (Arg.getParamAlignment()) 9650 FrameAlign = Arg.getParamAlignment(); 9651 else 9652 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9653 Flags.setByValAlign(FrameAlign); 9654 } 9655 if (Arg.hasAttribute(Attribute::Nest)) 9656 Flags.setNest(); 9657 if (NeedsRegBlock) 9658 Flags.setInConsecutiveRegs(); 9659 Flags.setOrigAlign(OriginalAlignment); 9660 if (ArgCopyElisionCandidates.count(&Arg)) 9661 Flags.setCopyElisionCandidate(); 9662 if (Arg.hasAttribute(Attribute::Returned)) 9663 Flags.setReturned(); 9664 9665 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9666 *CurDAG->getContext(), F.getCallingConv(), VT); 9667 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9668 *CurDAG->getContext(), F.getCallingConv(), VT); 9669 for (unsigned i = 0; i != NumRegs; ++i) { 9670 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9671 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9672 if (NumRegs > 1 && i == 0) 9673 MyFlags.Flags.setSplit(); 9674 // if it isn't first piece, alignment must be 1 9675 else if (i > 0) { 9676 MyFlags.Flags.setOrigAlign(1); 9677 if (i == NumRegs - 1) 9678 MyFlags.Flags.setSplitEnd(); 9679 } 9680 Ins.push_back(MyFlags); 9681 } 9682 if (NeedsRegBlock && Value == NumValues - 1) 9683 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9684 PartBase += VT.getStoreSize(); 9685 } 9686 } 9687 9688 // Call the target to set up the argument values. 9689 SmallVector<SDValue, 8> InVals; 9690 SDValue NewRoot = TLI->LowerFormalArguments( 9691 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9692 9693 // Verify that the target's LowerFormalArguments behaved as expected. 9694 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9695 "LowerFormalArguments didn't return a valid chain!"); 9696 assert(InVals.size() == Ins.size() && 9697 "LowerFormalArguments didn't emit the correct number of values!"); 9698 LLVM_DEBUG({ 9699 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9700 assert(InVals[i].getNode() && 9701 "LowerFormalArguments emitted a null value!"); 9702 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9703 "LowerFormalArguments emitted a value with the wrong type!"); 9704 } 9705 }); 9706 9707 // Update the DAG with the new chain value resulting from argument lowering. 9708 DAG.setRoot(NewRoot); 9709 9710 // Set up the argument values. 9711 unsigned i = 0; 9712 if (!FuncInfo->CanLowerReturn) { 9713 // Create a virtual register for the sret pointer, and put in a copy 9714 // from the sret argument into it. 9715 SmallVector<EVT, 1> ValueVTs; 9716 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9717 F.getReturnType()->getPointerTo( 9718 DAG.getDataLayout().getAllocaAddrSpace()), 9719 ValueVTs); 9720 MVT VT = ValueVTs[0].getSimpleVT(); 9721 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9722 Optional<ISD::NodeType> AssertOp = None; 9723 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9724 nullptr, F.getCallingConv(), AssertOp); 9725 9726 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9727 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9728 Register SRetReg = 9729 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9730 FuncInfo->DemoteRegister = SRetReg; 9731 NewRoot = 9732 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9733 DAG.setRoot(NewRoot); 9734 9735 // i indexes lowered arguments. Bump it past the hidden sret argument. 9736 ++i; 9737 } 9738 9739 SmallVector<SDValue, 4> Chains; 9740 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9741 for (const Argument &Arg : F.args()) { 9742 SmallVector<SDValue, 4> ArgValues; 9743 SmallVector<EVT, 4> ValueVTs; 9744 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9745 unsigned NumValues = ValueVTs.size(); 9746 if (NumValues == 0) 9747 continue; 9748 9749 bool ArgHasUses = !Arg.use_empty(); 9750 9751 // Elide the copying store if the target loaded this argument from a 9752 // suitable fixed stack object. 9753 if (Ins[i].Flags.isCopyElisionCandidate()) { 9754 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9755 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9756 InVals[i], ArgHasUses); 9757 } 9758 9759 // If this argument is unused then remember its value. It is used to generate 9760 // debugging information. 9761 bool isSwiftErrorArg = 9762 TLI->supportSwiftError() && 9763 Arg.hasAttribute(Attribute::SwiftError); 9764 if (!ArgHasUses && !isSwiftErrorArg) { 9765 SDB->setUnusedArgValue(&Arg, InVals[i]); 9766 9767 // Also remember any frame index for use in FastISel. 9768 if (FrameIndexSDNode *FI = 9769 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9770 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9771 } 9772 9773 for (unsigned Val = 0; Val != NumValues; ++Val) { 9774 EVT VT = ValueVTs[Val]; 9775 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9776 F.getCallingConv(), VT); 9777 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9778 *CurDAG->getContext(), F.getCallingConv(), VT); 9779 9780 // Even an apparant 'unused' swifterror argument needs to be returned. So 9781 // we do generate a copy for it that can be used on return from the 9782 // function. 9783 if (ArgHasUses || isSwiftErrorArg) { 9784 Optional<ISD::NodeType> AssertOp; 9785 if (Arg.hasAttribute(Attribute::SExt)) 9786 AssertOp = ISD::AssertSext; 9787 else if (Arg.hasAttribute(Attribute::ZExt)) 9788 AssertOp = ISD::AssertZext; 9789 9790 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9791 PartVT, VT, nullptr, 9792 F.getCallingConv(), AssertOp)); 9793 } 9794 9795 i += NumParts; 9796 } 9797 9798 // We don't need to do anything else for unused arguments. 9799 if (ArgValues.empty()) 9800 continue; 9801 9802 // Note down frame index. 9803 if (FrameIndexSDNode *FI = 9804 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9805 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9806 9807 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9808 SDB->getCurSDLoc()); 9809 9810 SDB->setValue(&Arg, Res); 9811 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9812 // We want to associate the argument with the frame index, among 9813 // involved operands, that correspond to the lowest address. The 9814 // getCopyFromParts function, called earlier, is swapping the order of 9815 // the operands to BUILD_PAIR depending on endianness. The result of 9816 // that swapping is that the least significant bits of the argument will 9817 // be in the first operand of the BUILD_PAIR node, and the most 9818 // significant bits will be in the second operand. 9819 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9820 if (LoadSDNode *LNode = 9821 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9822 if (FrameIndexSDNode *FI = 9823 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9824 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9825 } 9826 9827 // Analyses past this point are naive and don't expect an assertion. 9828 if (Res.getOpcode() == ISD::AssertZext) 9829 Res = Res.getOperand(0); 9830 9831 // Update the SwiftErrorVRegDefMap. 9832 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9833 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9834 if (Register::isVirtualRegister(Reg)) 9835 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9836 Reg); 9837 } 9838 9839 // If this argument is live outside of the entry block, insert a copy from 9840 // wherever we got it to the vreg that other BB's will reference it as. 9841 if (Res.getOpcode() == ISD::CopyFromReg) { 9842 // If we can, though, try to skip creating an unnecessary vreg. 9843 // FIXME: This isn't very clean... it would be nice to make this more 9844 // general. 9845 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9846 if (Register::isVirtualRegister(Reg)) { 9847 FuncInfo->ValueMap[&Arg] = Reg; 9848 continue; 9849 } 9850 } 9851 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9852 FuncInfo->InitializeRegForValue(&Arg); 9853 SDB->CopyToExportRegsIfNeeded(&Arg); 9854 } 9855 } 9856 9857 if (!Chains.empty()) { 9858 Chains.push_back(NewRoot); 9859 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9860 } 9861 9862 DAG.setRoot(NewRoot); 9863 9864 assert(i == InVals.size() && "Argument register count mismatch!"); 9865 9866 // If any argument copy elisions occurred and we have debug info, update the 9867 // stale frame indices used in the dbg.declare variable info table. 9868 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9869 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9870 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9871 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9872 if (I != ArgCopyElisionFrameIndexMap.end()) 9873 VI.Slot = I->second; 9874 } 9875 } 9876 9877 // Finally, if the target has anything special to do, allow it to do so. 9878 EmitFunctionEntryCode(); 9879 } 9880 9881 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9882 /// ensure constants are generated when needed. Remember the virtual registers 9883 /// that need to be added to the Machine PHI nodes as input. We cannot just 9884 /// directly add them, because expansion might result in multiple MBB's for one 9885 /// BB. As such, the start of the BB might correspond to a different MBB than 9886 /// the end. 9887 void 9888 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9889 const Instruction *TI = LLVMBB->getTerminator(); 9890 9891 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9892 9893 // Check PHI nodes in successors that expect a value to be available from this 9894 // block. 9895 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9896 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9897 if (!isa<PHINode>(SuccBB->begin())) continue; 9898 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9899 9900 // If this terminator has multiple identical successors (common for 9901 // switches), only handle each succ once. 9902 if (!SuccsHandled.insert(SuccMBB).second) 9903 continue; 9904 9905 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9906 9907 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9908 // nodes and Machine PHI nodes, but the incoming operands have not been 9909 // emitted yet. 9910 for (const PHINode &PN : SuccBB->phis()) { 9911 // Ignore dead phi's. 9912 if (PN.use_empty()) 9913 continue; 9914 9915 // Skip empty types 9916 if (PN.getType()->isEmptyTy()) 9917 continue; 9918 9919 unsigned Reg; 9920 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9921 9922 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9923 unsigned &RegOut = ConstantsOut[C]; 9924 if (RegOut == 0) { 9925 RegOut = FuncInfo.CreateRegs(C); 9926 CopyValueToVirtualRegister(C, RegOut); 9927 } 9928 Reg = RegOut; 9929 } else { 9930 DenseMap<const Value *, unsigned>::iterator I = 9931 FuncInfo.ValueMap.find(PHIOp); 9932 if (I != FuncInfo.ValueMap.end()) 9933 Reg = I->second; 9934 else { 9935 assert(isa<AllocaInst>(PHIOp) && 9936 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9937 "Didn't codegen value into a register!??"); 9938 Reg = FuncInfo.CreateRegs(PHIOp); 9939 CopyValueToVirtualRegister(PHIOp, Reg); 9940 } 9941 } 9942 9943 // Remember that this register needs to added to the machine PHI node as 9944 // the input for this MBB. 9945 SmallVector<EVT, 4> ValueVTs; 9946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9947 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9948 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9949 EVT VT = ValueVTs[vti]; 9950 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9951 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9952 FuncInfo.PHINodesToUpdate.push_back( 9953 std::make_pair(&*MBBI++, Reg + i)); 9954 Reg += NumRegisters; 9955 } 9956 } 9957 } 9958 9959 ConstantsOut.clear(); 9960 } 9961 9962 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9963 /// is 0. 9964 MachineBasicBlock * 9965 SelectionDAGBuilder::StackProtectorDescriptor:: 9966 AddSuccessorMBB(const BasicBlock *BB, 9967 MachineBasicBlock *ParentMBB, 9968 bool IsLikely, 9969 MachineBasicBlock *SuccMBB) { 9970 // If SuccBB has not been created yet, create it. 9971 if (!SuccMBB) { 9972 MachineFunction *MF = ParentMBB->getParent(); 9973 MachineFunction::iterator BBI(ParentMBB); 9974 SuccMBB = MF->CreateMachineBasicBlock(BB); 9975 MF->insert(++BBI, SuccMBB); 9976 } 9977 // Add it as a successor of ParentMBB. 9978 ParentMBB->addSuccessor( 9979 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9980 return SuccMBB; 9981 } 9982 9983 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9984 MachineFunction::iterator I(MBB); 9985 if (++I == FuncInfo.MF->end()) 9986 return nullptr; 9987 return &*I; 9988 } 9989 9990 /// During lowering new call nodes can be created (such as memset, etc.). 9991 /// Those will become new roots of the current DAG, but complications arise 9992 /// when they are tail calls. In such cases, the call lowering will update 9993 /// the root, but the builder still needs to know that a tail call has been 9994 /// lowered in order to avoid generating an additional return. 9995 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9996 // If the node is null, we do have a tail call. 9997 if (MaybeTC.getNode() != nullptr) 9998 DAG.setRoot(MaybeTC); 9999 else 10000 HasTailCall = true; 10001 } 10002 10003 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10004 MachineBasicBlock *SwitchMBB, 10005 MachineBasicBlock *DefaultMBB) { 10006 MachineFunction *CurMF = FuncInfo.MF; 10007 MachineBasicBlock *NextMBB = nullptr; 10008 MachineFunction::iterator BBI(W.MBB); 10009 if (++BBI != FuncInfo.MF->end()) 10010 NextMBB = &*BBI; 10011 10012 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10013 10014 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10015 10016 if (Size == 2 && W.MBB == SwitchMBB) { 10017 // If any two of the cases has the same destination, and if one value 10018 // is the same as the other, but has one bit unset that the other has set, 10019 // use bit manipulation to do two compares at once. For example: 10020 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10021 // TODO: This could be extended to merge any 2 cases in switches with 3 10022 // cases. 10023 // TODO: Handle cases where W.CaseBB != SwitchBB. 10024 CaseCluster &Small = *W.FirstCluster; 10025 CaseCluster &Big = *W.LastCluster; 10026 10027 if (Small.Low == Small.High && Big.Low == Big.High && 10028 Small.MBB == Big.MBB) { 10029 const APInt &SmallValue = Small.Low->getValue(); 10030 const APInt &BigValue = Big.Low->getValue(); 10031 10032 // Check that there is only one bit different. 10033 APInt CommonBit = BigValue ^ SmallValue; 10034 if (CommonBit.isPowerOf2()) { 10035 SDValue CondLHS = getValue(Cond); 10036 EVT VT = CondLHS.getValueType(); 10037 SDLoc DL = getCurSDLoc(); 10038 10039 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10040 DAG.getConstant(CommonBit, DL, VT)); 10041 SDValue Cond = DAG.getSetCC( 10042 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10043 ISD::SETEQ); 10044 10045 // Update successor info. 10046 // Both Small and Big will jump to Small.BB, so we sum up the 10047 // probabilities. 10048 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10049 if (BPI) 10050 addSuccessorWithProb( 10051 SwitchMBB, DefaultMBB, 10052 // The default destination is the first successor in IR. 10053 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10054 else 10055 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10056 10057 // Insert the true branch. 10058 SDValue BrCond = 10059 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10060 DAG.getBasicBlock(Small.MBB)); 10061 // Insert the false branch. 10062 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10063 DAG.getBasicBlock(DefaultMBB)); 10064 10065 DAG.setRoot(BrCond); 10066 return; 10067 } 10068 } 10069 } 10070 10071 if (TM.getOptLevel() != CodeGenOpt::None) { 10072 // Here, we order cases by probability so the most likely case will be 10073 // checked first. However, two clusters can have the same probability in 10074 // which case their relative ordering is non-deterministic. So we use Low 10075 // as a tie-breaker as clusters are guaranteed to never overlap. 10076 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10077 [](const CaseCluster &a, const CaseCluster &b) { 10078 return a.Prob != b.Prob ? 10079 a.Prob > b.Prob : 10080 a.Low->getValue().slt(b.Low->getValue()); 10081 }); 10082 10083 // Rearrange the case blocks so that the last one falls through if possible 10084 // without changing the order of probabilities. 10085 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10086 --I; 10087 if (I->Prob > W.LastCluster->Prob) 10088 break; 10089 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10090 std::swap(*I, *W.LastCluster); 10091 break; 10092 } 10093 } 10094 } 10095 10096 // Compute total probability. 10097 BranchProbability DefaultProb = W.DefaultProb; 10098 BranchProbability UnhandledProbs = DefaultProb; 10099 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10100 UnhandledProbs += I->Prob; 10101 10102 MachineBasicBlock *CurMBB = W.MBB; 10103 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10104 bool FallthroughUnreachable = false; 10105 MachineBasicBlock *Fallthrough; 10106 if (I == W.LastCluster) { 10107 // For the last cluster, fall through to the default destination. 10108 Fallthrough = DefaultMBB; 10109 FallthroughUnreachable = isa<UnreachableInst>( 10110 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10111 } else { 10112 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10113 CurMF->insert(BBI, Fallthrough); 10114 // Put Cond in a virtual register to make it available from the new blocks. 10115 ExportFromCurrentBlock(Cond); 10116 } 10117 UnhandledProbs -= I->Prob; 10118 10119 switch (I->Kind) { 10120 case CC_JumpTable: { 10121 // FIXME: Optimize away range check based on pivot comparisons. 10122 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10123 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10124 10125 // The jump block hasn't been inserted yet; insert it here. 10126 MachineBasicBlock *JumpMBB = JT->MBB; 10127 CurMF->insert(BBI, JumpMBB); 10128 10129 auto JumpProb = I->Prob; 10130 auto FallthroughProb = UnhandledProbs; 10131 10132 // If the default statement is a target of the jump table, we evenly 10133 // distribute the default probability to successors of CurMBB. Also 10134 // update the probability on the edge from JumpMBB to Fallthrough. 10135 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10136 SE = JumpMBB->succ_end(); 10137 SI != SE; ++SI) { 10138 if (*SI == DefaultMBB) { 10139 JumpProb += DefaultProb / 2; 10140 FallthroughProb -= DefaultProb / 2; 10141 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10142 JumpMBB->normalizeSuccProbs(); 10143 break; 10144 } 10145 } 10146 10147 if (FallthroughUnreachable) { 10148 // Skip the range check if the fallthrough block is unreachable. 10149 JTH->OmitRangeCheck = true; 10150 } 10151 10152 if (!JTH->OmitRangeCheck) 10153 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10154 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10155 CurMBB->normalizeSuccProbs(); 10156 10157 // The jump table header will be inserted in our current block, do the 10158 // range check, and fall through to our fallthrough block. 10159 JTH->HeaderBB = CurMBB; 10160 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10161 10162 // If we're in the right place, emit the jump table header right now. 10163 if (CurMBB == SwitchMBB) { 10164 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10165 JTH->Emitted = true; 10166 } 10167 break; 10168 } 10169 case CC_BitTests: { 10170 // FIXME: Optimize away range check based on pivot comparisons. 10171 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10172 10173 // The bit test blocks haven't been inserted yet; insert them here. 10174 for (BitTestCase &BTC : BTB->Cases) 10175 CurMF->insert(BBI, BTC.ThisBB); 10176 10177 // Fill in fields of the BitTestBlock. 10178 BTB->Parent = CurMBB; 10179 BTB->Default = Fallthrough; 10180 10181 BTB->DefaultProb = UnhandledProbs; 10182 // If the cases in bit test don't form a contiguous range, we evenly 10183 // distribute the probability on the edge to Fallthrough to two 10184 // successors of CurMBB. 10185 if (!BTB->ContiguousRange) { 10186 BTB->Prob += DefaultProb / 2; 10187 BTB->DefaultProb -= DefaultProb / 2; 10188 } 10189 10190 if (FallthroughUnreachable) { 10191 // Skip the range check if the fallthrough block is unreachable. 10192 BTB->OmitRangeCheck = true; 10193 } 10194 10195 // If we're in the right place, emit the bit test header right now. 10196 if (CurMBB == SwitchMBB) { 10197 visitBitTestHeader(*BTB, SwitchMBB); 10198 BTB->Emitted = true; 10199 } 10200 break; 10201 } 10202 case CC_Range: { 10203 const Value *RHS, *LHS, *MHS; 10204 ISD::CondCode CC; 10205 if (I->Low == I->High) { 10206 // Check Cond == I->Low. 10207 CC = ISD::SETEQ; 10208 LHS = Cond; 10209 RHS=I->Low; 10210 MHS = nullptr; 10211 } else { 10212 // Check I->Low <= Cond <= I->High. 10213 CC = ISD::SETLE; 10214 LHS = I->Low; 10215 MHS = Cond; 10216 RHS = I->High; 10217 } 10218 10219 // If Fallthrough is unreachable, fold away the comparison. 10220 if (FallthroughUnreachable) 10221 CC = ISD::SETTRUE; 10222 10223 // The false probability is the sum of all unhandled cases. 10224 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10225 getCurSDLoc(), I->Prob, UnhandledProbs); 10226 10227 if (CurMBB == SwitchMBB) 10228 visitSwitchCase(CB, SwitchMBB); 10229 else 10230 SL->SwitchCases.push_back(CB); 10231 10232 break; 10233 } 10234 } 10235 CurMBB = Fallthrough; 10236 } 10237 } 10238 10239 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10240 CaseClusterIt First, 10241 CaseClusterIt Last) { 10242 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10243 if (X.Prob != CC.Prob) 10244 return X.Prob > CC.Prob; 10245 10246 // Ties are broken by comparing the case value. 10247 return X.Low->getValue().slt(CC.Low->getValue()); 10248 }); 10249 } 10250 10251 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10252 const SwitchWorkListItem &W, 10253 Value *Cond, 10254 MachineBasicBlock *SwitchMBB) { 10255 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10256 "Clusters not sorted?"); 10257 10258 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10259 10260 // Balance the tree based on branch probabilities to create a near-optimal (in 10261 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10262 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10263 CaseClusterIt LastLeft = W.FirstCluster; 10264 CaseClusterIt FirstRight = W.LastCluster; 10265 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10266 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10267 10268 // Move LastLeft and FirstRight towards each other from opposite directions to 10269 // find a partitioning of the clusters which balances the probability on both 10270 // sides. If LeftProb and RightProb are equal, alternate which side is 10271 // taken to ensure 0-probability nodes are distributed evenly. 10272 unsigned I = 0; 10273 while (LastLeft + 1 < FirstRight) { 10274 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10275 LeftProb += (++LastLeft)->Prob; 10276 else 10277 RightProb += (--FirstRight)->Prob; 10278 I++; 10279 } 10280 10281 while (true) { 10282 // Our binary search tree differs from a typical BST in that ours can have up 10283 // to three values in each leaf. The pivot selection above doesn't take that 10284 // into account, which means the tree might require more nodes and be less 10285 // efficient. We compensate for this here. 10286 10287 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10288 unsigned NumRight = W.LastCluster - FirstRight + 1; 10289 10290 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10291 // If one side has less than 3 clusters, and the other has more than 3, 10292 // consider taking a cluster from the other side. 10293 10294 if (NumLeft < NumRight) { 10295 // Consider moving the first cluster on the right to the left side. 10296 CaseCluster &CC = *FirstRight; 10297 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10298 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10299 if (LeftSideRank <= RightSideRank) { 10300 // Moving the cluster to the left does not demote it. 10301 ++LastLeft; 10302 ++FirstRight; 10303 continue; 10304 } 10305 } else { 10306 assert(NumRight < NumLeft); 10307 // Consider moving the last element on the left to the right side. 10308 CaseCluster &CC = *LastLeft; 10309 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10310 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10311 if (RightSideRank <= LeftSideRank) { 10312 // Moving the cluster to the right does not demot it. 10313 --LastLeft; 10314 --FirstRight; 10315 continue; 10316 } 10317 } 10318 } 10319 break; 10320 } 10321 10322 assert(LastLeft + 1 == FirstRight); 10323 assert(LastLeft >= W.FirstCluster); 10324 assert(FirstRight <= W.LastCluster); 10325 10326 // Use the first element on the right as pivot since we will make less-than 10327 // comparisons against it. 10328 CaseClusterIt PivotCluster = FirstRight; 10329 assert(PivotCluster > W.FirstCluster); 10330 assert(PivotCluster <= W.LastCluster); 10331 10332 CaseClusterIt FirstLeft = W.FirstCluster; 10333 CaseClusterIt LastRight = W.LastCluster; 10334 10335 const ConstantInt *Pivot = PivotCluster->Low; 10336 10337 // New blocks will be inserted immediately after the current one. 10338 MachineFunction::iterator BBI(W.MBB); 10339 ++BBI; 10340 10341 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10342 // we can branch to its destination directly if it's squeezed exactly in 10343 // between the known lower bound and Pivot - 1. 10344 MachineBasicBlock *LeftMBB; 10345 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10346 FirstLeft->Low == W.GE && 10347 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10348 LeftMBB = FirstLeft->MBB; 10349 } else { 10350 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10351 FuncInfo.MF->insert(BBI, LeftMBB); 10352 WorkList.push_back( 10353 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10354 // Put Cond in a virtual register to make it available from the new blocks. 10355 ExportFromCurrentBlock(Cond); 10356 } 10357 10358 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10359 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10360 // directly if RHS.High equals the current upper bound. 10361 MachineBasicBlock *RightMBB; 10362 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10363 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10364 RightMBB = FirstRight->MBB; 10365 } else { 10366 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10367 FuncInfo.MF->insert(BBI, RightMBB); 10368 WorkList.push_back( 10369 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10370 // Put Cond in a virtual register to make it available from the new blocks. 10371 ExportFromCurrentBlock(Cond); 10372 } 10373 10374 // Create the CaseBlock record that will be used to lower the branch. 10375 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10376 getCurSDLoc(), LeftProb, RightProb); 10377 10378 if (W.MBB == SwitchMBB) 10379 visitSwitchCase(CB, SwitchMBB); 10380 else 10381 SL->SwitchCases.push_back(CB); 10382 } 10383 10384 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10385 // from the swith statement. 10386 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10387 BranchProbability PeeledCaseProb) { 10388 if (PeeledCaseProb == BranchProbability::getOne()) 10389 return BranchProbability::getZero(); 10390 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10391 10392 uint32_t Numerator = CaseProb.getNumerator(); 10393 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10394 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10395 } 10396 10397 // Try to peel the top probability case if it exceeds the threshold. 10398 // Return current MachineBasicBlock for the switch statement if the peeling 10399 // does not occur. 10400 // If the peeling is performed, return the newly created MachineBasicBlock 10401 // for the peeled switch statement. Also update Clusters to remove the peeled 10402 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10403 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10404 const SwitchInst &SI, CaseClusterVector &Clusters, 10405 BranchProbability &PeeledCaseProb) { 10406 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10407 // Don't perform if there is only one cluster or optimizing for size. 10408 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10409 TM.getOptLevel() == CodeGenOpt::None || 10410 SwitchMBB->getParent()->getFunction().hasMinSize()) 10411 return SwitchMBB; 10412 10413 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10414 unsigned PeeledCaseIndex = 0; 10415 bool SwitchPeeled = false; 10416 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10417 CaseCluster &CC = Clusters[Index]; 10418 if (CC.Prob < TopCaseProb) 10419 continue; 10420 TopCaseProb = CC.Prob; 10421 PeeledCaseIndex = Index; 10422 SwitchPeeled = true; 10423 } 10424 if (!SwitchPeeled) 10425 return SwitchMBB; 10426 10427 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10428 << TopCaseProb << "\n"); 10429 10430 // Record the MBB for the peeled switch statement. 10431 MachineFunction::iterator BBI(SwitchMBB); 10432 ++BBI; 10433 MachineBasicBlock *PeeledSwitchMBB = 10434 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10435 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10436 10437 ExportFromCurrentBlock(SI.getCondition()); 10438 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10439 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10440 nullptr, nullptr, TopCaseProb.getCompl()}; 10441 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10442 10443 Clusters.erase(PeeledCaseIt); 10444 for (CaseCluster &CC : Clusters) { 10445 LLVM_DEBUG( 10446 dbgs() << "Scale the probablity for one cluster, before scaling: " 10447 << CC.Prob << "\n"); 10448 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10449 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10450 } 10451 PeeledCaseProb = TopCaseProb; 10452 return PeeledSwitchMBB; 10453 } 10454 10455 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10456 // Extract cases from the switch. 10457 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10458 CaseClusterVector Clusters; 10459 Clusters.reserve(SI.getNumCases()); 10460 for (auto I : SI.cases()) { 10461 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10462 const ConstantInt *CaseVal = I.getCaseValue(); 10463 BranchProbability Prob = 10464 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10465 : BranchProbability(1, SI.getNumCases() + 1); 10466 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10467 } 10468 10469 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10470 10471 // Cluster adjacent cases with the same destination. We do this at all 10472 // optimization levels because it's cheap to do and will make codegen faster 10473 // if there are many clusters. 10474 sortAndRangeify(Clusters); 10475 10476 // The branch probablity of the peeled case. 10477 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10478 MachineBasicBlock *PeeledSwitchMBB = 10479 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10480 10481 // If there is only the default destination, jump there directly. 10482 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10483 if (Clusters.empty()) { 10484 assert(PeeledSwitchMBB == SwitchMBB); 10485 SwitchMBB->addSuccessor(DefaultMBB); 10486 if (DefaultMBB != NextBlock(SwitchMBB)) { 10487 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10488 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10489 } 10490 return; 10491 } 10492 10493 SL->findJumpTables(Clusters, &SI, DefaultMBB); 10494 SL->findBitTestClusters(Clusters, &SI); 10495 10496 LLVM_DEBUG({ 10497 dbgs() << "Case clusters: "; 10498 for (const CaseCluster &C : Clusters) { 10499 if (C.Kind == CC_JumpTable) 10500 dbgs() << "JT:"; 10501 if (C.Kind == CC_BitTests) 10502 dbgs() << "BT:"; 10503 10504 C.Low->getValue().print(dbgs(), true); 10505 if (C.Low != C.High) { 10506 dbgs() << '-'; 10507 C.High->getValue().print(dbgs(), true); 10508 } 10509 dbgs() << ' '; 10510 } 10511 dbgs() << '\n'; 10512 }); 10513 10514 assert(!Clusters.empty()); 10515 SwitchWorkList WorkList; 10516 CaseClusterIt First = Clusters.begin(); 10517 CaseClusterIt Last = Clusters.end() - 1; 10518 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10519 // Scale the branchprobability for DefaultMBB if the peel occurs and 10520 // DefaultMBB is not replaced. 10521 if (PeeledCaseProb != BranchProbability::getZero() && 10522 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10523 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10524 WorkList.push_back( 10525 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10526 10527 while (!WorkList.empty()) { 10528 SwitchWorkListItem W = WorkList.back(); 10529 WorkList.pop_back(); 10530 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10531 10532 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10533 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10534 // For optimized builds, lower large range as a balanced binary tree. 10535 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10536 continue; 10537 } 10538 10539 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10540 } 10541 } 10542