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/BitVector.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/MC/MCSymbol.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/MathExtras.h" 98 #include "llvm/Support/raw_ostream.h" 99 #include "llvm/Target/TargetIntrinsicInfo.h" 100 #include "llvm/Target/TargetMachine.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <cstring> 105 #include <iterator> 106 #include <limits> 107 #include <numeric> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 Optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 165 const SDValue *Parts, unsigned NumParts, 166 MVT PartVT, EVT ValueVT, const Value *V, 167 Optional<CallingConv::ID> CC = None, 168 Optional<ISD::NodeType> AssertOp = None) { 169 // Let the target assemble the parts if it wants to 170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 171 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 172 PartVT, ValueVT, CC)) 173 return Val; 174 175 if (ValueVT.isVector()) 176 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 177 CC); 178 179 assert(NumParts > 0 && "No parts to assemble!"); 180 SDValue Val = Parts[0]; 181 182 if (NumParts > 1) { 183 // Assemble the value from multiple parts. 184 if (ValueVT.isInteger()) { 185 unsigned PartBits = PartVT.getSizeInBits(); 186 unsigned ValueBits = ValueVT.getSizeInBits(); 187 188 // Assemble the power of 2 part. 189 unsigned RoundParts = 190 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 200 PartVT, HalfVT, V); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 202 RoundParts / 2, PartVT, HalfVT, V); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = 227 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getPointerTy(DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 249 } 250 } 251 252 // There is now one part, held in Val. Correct it to match ValueVT. 253 // PartEVT is the type of the register class that holds the value. 254 // ValueVT is the type of the inline asm operation. 255 EVT PartEVT = Val.getValueType(); 256 257 if (PartEVT == ValueVT) 258 return Val; 259 260 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 261 ValueVT.bitsLT(PartEVT)) { 262 // For an FP value in an integer part, we need to truncate to the right 263 // width first. 264 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 265 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 266 } 267 268 // Handle types that have the same size. 269 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 270 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 271 272 // Handle types with different sizes. 273 if (PartEVT.isInteger() && ValueVT.isInteger()) { 274 if (ValueVT.bitsLT(PartEVT)) { 275 // For a truncate, see if we have any information to 276 // indicate whether the truncated bits will always be 277 // zero or sign-extension. 278 if (AssertOp.hasValue()) 279 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 280 DAG.getValueType(ValueVT)); 281 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 282 } 283 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 284 } 285 286 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 287 // FP_ROUND's are always exact here. 288 if (ValueVT.bitsLT(Val.getValueType())) 289 return DAG.getNode( 290 ISD::FP_ROUND, DL, ValueVT, Val, 291 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 292 293 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 294 } 295 296 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 297 // then truncating. 298 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 299 ValueVT.bitsLT(PartEVT)) { 300 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 301 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 302 } 303 304 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 305 } 306 307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 308 const Twine &ErrMsg) { 309 const Instruction *I = dyn_cast_or_null<Instruction>(V); 310 if (!V) 311 return Ctx.emitError(ErrMsg); 312 313 const char *AsmError = ", possible invalid constraint for vector type"; 314 if (const CallInst *CI = dyn_cast<CallInst>(I)) 315 if (CI->isInlineAsm()) 316 return Ctx.emitError(I, ErrMsg + AsmError); 317 318 return Ctx.emitError(I, ErrMsg); 319 } 320 321 /// getCopyFromPartsVector - Create a value that contains the specified legal 322 /// parts combined into the value they represent. If the parts combine to a 323 /// type larger than ValueVT then AssertOp can be used to specify whether the 324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 325 /// ValueVT (ISD::AssertSext). 326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 327 const SDValue *Parts, unsigned NumParts, 328 MVT PartVT, EVT ValueVT, const Value *V, 329 Optional<CallingConv::ID> CallConv) { 330 assert(ValueVT.isVector() && "Not a vector value"); 331 assert(NumParts > 0 && "No parts to assemble!"); 332 const bool IsABIRegCopy = CallConv.hasValue(); 333 334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 335 SDValue Val = Parts[0]; 336 337 // Handle a multi-element vector. 338 if (NumParts > 1) { 339 EVT IntermediateVT; 340 MVT RegisterVT; 341 unsigned NumIntermediates; 342 unsigned NumRegs; 343 344 if (IsABIRegCopy) { 345 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 346 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } else { 349 NumRegs = 350 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 351 NumIntermediates, RegisterVT); 352 } 353 354 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 355 NumParts = NumRegs; // Silence a compiler warning. 356 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 357 assert(RegisterVT.getSizeInBits() == 358 Parts[0].getSimpleValueType().getSizeInBits() && 359 "Part type sizes don't match!"); 360 361 // Assemble the parts into intermediate operands. 362 SmallVector<SDValue, 8> Ops(NumIntermediates); 363 if (NumIntermediates == NumParts) { 364 // If the register was not expanded, truncate or copy the value, 365 // as appropriate. 366 for (unsigned i = 0; i != NumParts; ++i) 367 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 368 PartVT, IntermediateVT, V, CallConv); 369 } else if (NumParts > 0) { 370 // If the intermediate type was expanded, build the intermediate 371 // operands from the parts. 372 assert(NumParts % NumIntermediates == 0 && 373 "Must expand into a divisible number of parts!"); 374 unsigned Factor = NumParts / NumIntermediates; 375 for (unsigned i = 0; i != NumIntermediates; ++i) 376 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 377 PartVT, IntermediateVT, V, CallConv); 378 } 379 380 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 381 // intermediate operands. 382 EVT BuiltVectorTy = 383 IntermediateVT.isVector() 384 ? EVT::getVectorVT( 385 *DAG.getContext(), IntermediateVT.getScalarType(), 386 IntermediateVT.getVectorElementCount() * NumParts) 387 : EVT::getVectorVT(*DAG.getContext(), 388 IntermediateVT.getScalarType(), 389 NumIntermediates); 390 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 391 : ISD::BUILD_VECTOR, 392 DL, BuiltVectorTy, Ops); 393 } 394 395 // There is now one part, held in Val. Correct it to match ValueVT. 396 EVT PartEVT = Val.getValueType(); 397 398 if (PartEVT == ValueVT) 399 return Val; 400 401 if (PartEVT.isVector()) { 402 // Vector/Vector bitcast. 403 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 404 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 405 406 // If the element type of the source/dest vectors are the same, but the 407 // parts vector has more elements than the value vector, then we have a 408 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 409 // elements we want. 410 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 411 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 412 ValueVT.getVectorElementCount().getKnownMinValue()) && 413 (PartEVT.getVectorElementCount().isScalable() == 414 ValueVT.getVectorElementCount().isScalable()) && 415 "Cannot narrow, it would be a lossy transformation"); 416 PartEVT = 417 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 418 ValueVT.getVectorElementCount()); 419 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 420 DAG.getVectorIdxConstant(0, DL)); 421 if (PartEVT == ValueVT) 422 return Val; 423 } 424 425 // Promoted vector extract 426 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 427 } 428 429 // Trivial bitcast if the types are the same size and the destination 430 // vector type is legal. 431 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 432 TLI.isTypeLegal(ValueVT)) 433 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 434 435 if (ValueVT.getVectorNumElements() != 1) { 436 // Certain ABIs require that vectors are passed as integers. For vectors 437 // are the same size, this is an obvious bitcast. 438 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 439 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 440 } else if (ValueVT.bitsLT(PartEVT)) { 441 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 442 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 443 // Drop the extra bits. 444 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 445 return DAG.getBitcast(ValueVT, Val); 446 } 447 448 diagnosePossiblyInvalidConstraint( 449 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 450 return DAG.getUNDEF(ValueVT); 451 } 452 453 // Handle cases such as i8 -> <1 x i1> 454 EVT ValueSVT = ValueVT.getVectorElementType(); 455 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 456 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 457 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 458 else 459 Val = ValueVT.isFloatingPoint() 460 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 461 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 462 } 463 464 return DAG.getBuildVector(ValueVT, DL, Val); 465 } 466 467 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 468 SDValue Val, SDValue *Parts, unsigned NumParts, 469 MVT PartVT, const Value *V, 470 Optional<CallingConv::ID> CallConv); 471 472 /// getCopyToParts - Create a series of nodes that contain the specified value 473 /// split into legal parts. If the parts contain more bits than Val, then, for 474 /// integers, ExtendKind can be used to specify how to generate the extra bits. 475 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 476 SDValue *Parts, unsigned NumParts, MVT PartVT, 477 const Value *V, 478 Optional<CallingConv::ID> CallConv = None, 479 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 480 // Let the target split the parts if it wants to 481 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 482 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 483 CallConv)) 484 return; 485 EVT ValueVT = Val.getValueType(); 486 487 // Handle the vector case separately. 488 if (ValueVT.isVector()) 489 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 490 CallConv); 491 492 unsigned PartBits = PartVT.getSizeInBits(); 493 unsigned OrigNumParts = NumParts; 494 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 495 "Copying to an illegal type!"); 496 497 if (NumParts == 0) 498 return; 499 500 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 501 EVT PartEVT = PartVT; 502 if (PartEVT == ValueVT) { 503 assert(NumParts == 1 && "No-op copy with multiple parts!"); 504 Parts[0] = Val; 505 return; 506 } 507 508 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 509 // If the parts cover more bits than the value has, promote the value. 510 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 511 assert(NumParts == 1 && "Do not know what to promote to!"); 512 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 513 } else { 514 if (ValueVT.isFloatingPoint()) { 515 // FP values need to be bitcast, then extended if they are being put 516 // into a larger container. 517 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 518 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 519 } 520 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 521 ValueVT.isInteger() && 522 "Unknown mismatch!"); 523 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 524 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 525 if (PartVT == MVT::x86mmx) 526 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 527 } 528 } else if (PartBits == ValueVT.getSizeInBits()) { 529 // Different types of the same size. 530 assert(NumParts == 1 && PartEVT != ValueVT); 531 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 532 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 533 // If the parts cover less bits than value has, truncate the value. 534 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 535 ValueVT.isInteger() && 536 "Unknown mismatch!"); 537 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 538 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 539 if (PartVT == MVT::x86mmx) 540 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 541 } 542 543 // The value may have changed - recompute ValueVT. 544 ValueVT = Val.getValueType(); 545 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 546 "Failed to tile the value with PartVT!"); 547 548 if (NumParts == 1) { 549 if (PartEVT != ValueVT) { 550 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 551 "scalar-to-vector conversion failed"); 552 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 553 } 554 555 Parts[0] = Val; 556 return; 557 } 558 559 // Expand the value into multiple parts. 560 if (NumParts & (NumParts - 1)) { 561 // The number of parts is not a power of 2. Split off and copy the tail. 562 assert(PartVT.isInteger() && ValueVT.isInteger() && 563 "Do not know what to expand to!"); 564 unsigned RoundParts = 1 << Log2_32(NumParts); 565 unsigned RoundBits = RoundParts * PartBits; 566 unsigned OddParts = NumParts - RoundParts; 567 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 568 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 569 570 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 571 CallConv); 572 573 if (DAG.getDataLayout().isBigEndian()) 574 // The odd parts were reversed by getCopyToParts - unreverse them. 575 std::reverse(Parts + RoundParts, Parts + NumParts); 576 577 NumParts = RoundParts; 578 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 579 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 580 } 581 582 // The number of parts is a power of 2. Repeatedly bisect the value using 583 // EXTRACT_ELEMENT. 584 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 585 EVT::getIntegerVT(*DAG.getContext(), 586 ValueVT.getSizeInBits()), 587 Val); 588 589 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 590 for (unsigned i = 0; i < NumParts; i += StepSize) { 591 unsigned ThisBits = StepSize * PartBits / 2; 592 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 593 SDValue &Part0 = Parts[i]; 594 SDValue &Part1 = Parts[i+StepSize/2]; 595 596 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 597 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 598 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 599 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 600 601 if (ThisBits == PartBits && ThisVT != PartVT) { 602 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 603 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 604 } 605 } 606 } 607 608 if (DAG.getDataLayout().isBigEndian()) 609 std::reverse(Parts, Parts + OrigNumParts); 610 } 611 612 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 613 const SDLoc &DL, EVT PartVT) { 614 if (!PartVT.isVector()) 615 return SDValue(); 616 617 EVT ValueVT = Val.getValueType(); 618 ElementCount PartNumElts = PartVT.getVectorElementCount(); 619 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 620 621 // We only support widening vectors with equivalent element types and 622 // fixed/scalable properties. If a target needs to widen a fixed-length type 623 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 624 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 625 PartNumElts.isScalable() != ValueNumElts.isScalable() || 626 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 627 return SDValue(); 628 629 // Widening a scalable vector to another scalable vector is done by inserting 630 // the vector into a larger undef one. 631 if (PartNumElts.isScalable()) 632 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 633 Val, DAG.getVectorIdxConstant(0, DL)); 634 635 EVT ElementVT = PartVT.getVectorElementType(); 636 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 637 // undef elements. 638 SmallVector<SDValue, 16> Ops; 639 DAG.ExtractVectorElements(Val, Ops); 640 SDValue EltUndef = DAG.getUNDEF(ElementVT); 641 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 642 643 // FIXME: Use CONCAT for 2x -> 4x. 644 return DAG.getBuildVector(PartVT, DL, Ops); 645 } 646 647 /// getCopyToPartsVector - Create a series of nodes that contain the specified 648 /// value split into legal parts. 649 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 650 SDValue Val, SDValue *Parts, unsigned NumParts, 651 MVT PartVT, const Value *V, 652 Optional<CallingConv::ID> CallConv) { 653 EVT ValueVT = Val.getValueType(); 654 assert(ValueVT.isVector() && "Not a vector"); 655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 656 const bool IsABIRegCopy = CallConv.hasValue(); 657 658 if (NumParts == 1) { 659 EVT PartEVT = PartVT; 660 if (PartEVT == ValueVT) { 661 // Nothing to do. 662 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 663 // Bitconvert vector->vector case. 664 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 665 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 666 Val = Widened; 667 } else if (PartVT.isVector() && 668 PartEVT.getVectorElementType().bitsGE( 669 ValueVT.getVectorElementType()) && 670 PartEVT.getVectorElementCount() == 671 ValueVT.getVectorElementCount()) { 672 673 // Promoted vector extract 674 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 675 } else { 676 if (ValueVT.getVectorElementCount().isScalar()) { 677 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 678 DAG.getVectorIdxConstant(0, DL)); 679 } else { 680 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 681 assert(PartVT.getFixedSizeInBits() > ValueSize && 682 "lossy conversion of vector to scalar type"); 683 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 684 Val = DAG.getBitcast(IntermediateType, Val); 685 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 686 } 687 } 688 689 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 690 Parts[0] = Val; 691 return; 692 } 693 694 // Handle a multi-element vector. 695 EVT IntermediateVT; 696 MVT RegisterVT; 697 unsigned NumIntermediates; 698 unsigned NumRegs; 699 if (IsABIRegCopy) { 700 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 701 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 702 NumIntermediates, RegisterVT); 703 } else { 704 NumRegs = 705 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 706 NumIntermediates, RegisterVT); 707 } 708 709 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 710 NumParts = NumRegs; // Silence a compiler warning. 711 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 712 713 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 714 "Mixing scalable and fixed vectors when copying in parts"); 715 716 Optional<ElementCount> DestEltCnt; 717 718 if (IntermediateVT.isVector()) 719 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 720 else 721 DestEltCnt = ElementCount::getFixed(NumIntermediates); 722 723 EVT BuiltVectorTy = EVT::getVectorVT( 724 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 725 726 if (ValueVT == BuiltVectorTy) { 727 // Nothing to do. 728 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 729 // Bitconvert vector->vector case. 730 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 731 } else { 732 if (BuiltVectorTy.getVectorElementType().bitsGT( 733 ValueVT.getVectorElementType())) { 734 // Integer promotion. 735 ValueVT = EVT::getVectorVT(*DAG.getContext(), 736 BuiltVectorTy.getVectorElementType(), 737 ValueVT.getVectorElementCount()); 738 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 739 } 740 741 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 742 Val = Widened; 743 } 744 } 745 746 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 747 748 // Split the vector into intermediate operands. 749 SmallVector<SDValue, 8> Ops(NumIntermediates); 750 for (unsigned i = 0; i != NumIntermediates; ++i) { 751 if (IntermediateVT.isVector()) { 752 // This does something sensible for scalable vectors - see the 753 // definition of EXTRACT_SUBVECTOR for further details. 754 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 755 Ops[i] = 756 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 757 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 758 } else { 759 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 760 DAG.getVectorIdxConstant(i, DL)); 761 } 762 } 763 764 // Split the intermediate operands into legal parts. 765 if (NumParts == NumIntermediates) { 766 // If the register was not expanded, promote or copy the value, 767 // as appropriate. 768 for (unsigned i = 0; i != NumParts; ++i) 769 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 770 } else if (NumParts > 0) { 771 // If the intermediate type was expanded, split each the value into 772 // legal parts. 773 assert(NumIntermediates != 0 && "division by zero"); 774 assert(NumParts % NumIntermediates == 0 && 775 "Must expand into a divisible number of parts!"); 776 unsigned Factor = NumParts / NumIntermediates; 777 for (unsigned i = 0; i != NumIntermediates; ++i) 778 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 779 CallConv); 780 } 781 } 782 783 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 784 EVT valuevt, Optional<CallingConv::ID> CC) 785 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 786 RegCount(1, regs.size()), CallConv(CC) {} 787 788 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 789 const DataLayout &DL, unsigned Reg, Type *Ty, 790 Optional<CallingConv::ID> CC) { 791 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 792 793 CallConv = CC; 794 795 for (EVT ValueVT : ValueVTs) { 796 unsigned NumRegs = 797 isABIMangled() 798 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 799 : TLI.getNumRegisters(Context, ValueVT); 800 MVT RegisterVT = 801 isABIMangled() 802 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 803 : TLI.getRegisterType(Context, ValueVT); 804 for (unsigned i = 0; i != NumRegs; ++i) 805 Regs.push_back(Reg + i); 806 RegVTs.push_back(RegisterVT); 807 RegCount.push_back(NumRegs); 808 Reg += NumRegs; 809 } 810 } 811 812 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 813 FunctionLoweringInfo &FuncInfo, 814 const SDLoc &dl, SDValue &Chain, 815 SDValue *Flag, const Value *V) const { 816 // A Value with type {} or [0 x %t] needs no registers. 817 if (ValueVTs.empty()) 818 return SDValue(); 819 820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 821 822 // Assemble the legal parts into the final values. 823 SmallVector<SDValue, 4> Values(ValueVTs.size()); 824 SmallVector<SDValue, 8> Parts; 825 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 826 // Copy the legal parts from the registers. 827 EVT ValueVT = ValueVTs[Value]; 828 unsigned NumRegs = RegCount[Value]; 829 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 830 *DAG.getContext(), 831 CallConv.getValue(), RegVTs[Value]) 832 : RegVTs[Value]; 833 834 Parts.resize(NumRegs); 835 for (unsigned i = 0; i != NumRegs; ++i) { 836 SDValue P; 837 if (!Flag) { 838 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 839 } else { 840 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 841 *Flag = P.getValue(2); 842 } 843 844 Chain = P.getValue(1); 845 Parts[i] = P; 846 847 // If the source register was virtual and if we know something about it, 848 // add an assert node. 849 if (!Register::isVirtualRegister(Regs[Part + i]) || 850 !RegisterVT.isInteger()) 851 continue; 852 853 const FunctionLoweringInfo::LiveOutInfo *LOI = 854 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 855 if (!LOI) 856 continue; 857 858 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 859 unsigned NumSignBits = LOI->NumSignBits; 860 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 861 862 if (NumZeroBits == RegSize) { 863 // The current value is a zero. 864 // Explicitly express that as it would be easier for 865 // optimizations to kick in. 866 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 867 continue; 868 } 869 870 // FIXME: We capture more information than the dag can represent. For 871 // now, just use the tightest assertzext/assertsext possible. 872 bool isSExt; 873 EVT FromVT(MVT::Other); 874 if (NumZeroBits) { 875 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 876 isSExt = false; 877 } else if (NumSignBits > 1) { 878 FromVT = 879 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 880 isSExt = true; 881 } else { 882 continue; 883 } 884 // Add an assertion node. 885 assert(FromVT != MVT::Other); 886 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 887 RegisterVT, P, DAG.getValueType(FromVT)); 888 } 889 890 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 891 RegisterVT, ValueVT, V, CallConv); 892 Part += NumRegs; 893 Parts.clear(); 894 } 895 896 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 897 } 898 899 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 900 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 901 const Value *V, 902 ISD::NodeType PreferredExtendType) const { 903 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 904 ISD::NodeType ExtendKind = PreferredExtendType; 905 906 // Get the list of the values's legal parts. 907 unsigned NumRegs = Regs.size(); 908 SmallVector<SDValue, 8> Parts(NumRegs); 909 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 910 unsigned NumParts = RegCount[Value]; 911 912 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 913 *DAG.getContext(), 914 CallConv.getValue(), RegVTs[Value]) 915 : RegVTs[Value]; 916 917 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 918 ExtendKind = ISD::ZERO_EXTEND; 919 920 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 921 NumParts, RegisterVT, V, CallConv, ExtendKind); 922 Part += NumParts; 923 } 924 925 // Copy the parts into the registers. 926 SmallVector<SDValue, 8> Chains(NumRegs); 927 for (unsigned i = 0; i != NumRegs; ++i) { 928 SDValue Part; 929 if (!Flag) { 930 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 931 } else { 932 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 933 *Flag = Part.getValue(1); 934 } 935 936 Chains[i] = Part.getValue(0); 937 } 938 939 if (NumRegs == 1 || Flag) 940 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 941 // flagged to it. That is the CopyToReg nodes and the user are considered 942 // a single scheduling unit. If we create a TokenFactor and return it as 943 // chain, then the TokenFactor is both a predecessor (operand) of the 944 // user as well as a successor (the TF operands are flagged to the user). 945 // c1, f1 = CopyToReg 946 // c2, f2 = CopyToReg 947 // c3 = TokenFactor c1, c2 948 // ... 949 // = op c3, ..., f2 950 Chain = Chains[NumRegs-1]; 951 else 952 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 953 } 954 955 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 956 unsigned MatchingIdx, const SDLoc &dl, 957 SelectionDAG &DAG, 958 std::vector<SDValue> &Ops) const { 959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 960 961 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 962 if (HasMatching) 963 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 964 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 965 // Put the register class of the virtual registers in the flag word. That 966 // way, later passes can recompute register class constraints for inline 967 // assembly as well as normal instructions. 968 // Don't do this for tied operands that can use the regclass information 969 // from the def. 970 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 971 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 972 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 973 } 974 975 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 976 Ops.push_back(Res); 977 978 if (Code == InlineAsm::Kind_Clobber) { 979 // Clobbers should always have a 1:1 mapping with registers, and may 980 // reference registers that have illegal (e.g. vector) types. Hence, we 981 // shouldn't try to apply any sort of splitting logic to them. 982 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 983 "No 1:1 mapping from clobbers to regs?"); 984 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 985 (void)SP; 986 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 987 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 988 assert( 989 (Regs[I] != SP || 990 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 991 "If we clobbered the stack pointer, MFI should know about it."); 992 } 993 return; 994 } 995 996 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 997 MVT RegisterVT = RegVTs[Value]; 998 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 999 RegisterVT); 1000 for (unsigned i = 0; i != NumRegs; ++i) { 1001 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1002 unsigned TheReg = Regs[Reg++]; 1003 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1004 } 1005 } 1006 } 1007 1008 SmallVector<std::pair<unsigned, TypeSize>, 4> 1009 RegsForValue::getRegsAndSizes() const { 1010 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1011 unsigned I = 0; 1012 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1013 unsigned RegCount = std::get<0>(CountAndVT); 1014 MVT RegisterVT = std::get<1>(CountAndVT); 1015 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1016 for (unsigned E = I + RegCount; I != E; ++I) 1017 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1018 } 1019 return OutVec; 1020 } 1021 1022 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1023 const TargetLibraryInfo *li) { 1024 AA = aa; 1025 GFI = gfi; 1026 LibInfo = li; 1027 DL = &DAG.getDataLayout(); 1028 Context = DAG.getContext(); 1029 LPadToCallSiteMap.clear(); 1030 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1031 } 1032 1033 void SelectionDAGBuilder::clear() { 1034 NodeMap.clear(); 1035 UnusedArgNodeMap.clear(); 1036 PendingLoads.clear(); 1037 PendingExports.clear(); 1038 PendingConstrainedFP.clear(); 1039 PendingConstrainedFPStrict.clear(); 1040 CurInst = nullptr; 1041 HasTailCall = false; 1042 SDNodeOrder = LowestSDNodeOrder; 1043 StatepointLowering.clear(); 1044 } 1045 1046 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1047 DanglingDebugInfoMap.clear(); 1048 } 1049 1050 // Update DAG root to include dependencies on Pending chains. 1051 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1052 SDValue Root = DAG.getRoot(); 1053 1054 if (Pending.empty()) 1055 return Root; 1056 1057 // Add current root to PendingChains, unless we already indirectly 1058 // depend on it. 1059 if (Root.getOpcode() != ISD::EntryToken) { 1060 unsigned i = 0, e = Pending.size(); 1061 for (; i != e; ++i) { 1062 assert(Pending[i].getNode()->getNumOperands() > 1); 1063 if (Pending[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 Pending.push_back(Root); 1069 } 1070 1071 if (Pending.size() == 1) 1072 Root = Pending[0]; 1073 else 1074 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1075 1076 DAG.setRoot(Root); 1077 Pending.clear(); 1078 return Root; 1079 } 1080 1081 SDValue SelectionDAGBuilder::getMemoryRoot() { 1082 return updateRoot(PendingLoads); 1083 } 1084 1085 SDValue SelectionDAGBuilder::getRoot() { 1086 // Chain up all pending constrained intrinsics together with all 1087 // pending loads, by simply appending them to PendingLoads and 1088 // then calling getMemoryRoot(). 1089 PendingLoads.reserve(PendingLoads.size() + 1090 PendingConstrainedFP.size() + 1091 PendingConstrainedFPStrict.size()); 1092 PendingLoads.append(PendingConstrainedFP.begin(), 1093 PendingConstrainedFP.end()); 1094 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1095 PendingConstrainedFPStrict.end()); 1096 PendingConstrainedFP.clear(); 1097 PendingConstrainedFPStrict.clear(); 1098 return getMemoryRoot(); 1099 } 1100 1101 SDValue SelectionDAGBuilder::getControlRoot() { 1102 // We need to emit pending fpexcept.strict constrained intrinsics, 1103 // so append them to the PendingExports list. 1104 PendingExports.append(PendingConstrainedFPStrict.begin(), 1105 PendingConstrainedFPStrict.end()); 1106 PendingConstrainedFPStrict.clear(); 1107 return updateRoot(PendingExports); 1108 } 1109 1110 void SelectionDAGBuilder::visit(const Instruction &I) { 1111 // Set up outgoing PHI node register values before emitting the terminator. 1112 if (I.isTerminator()) { 1113 HandlePHINodesInSuccessorBlocks(I.getParent()); 1114 } 1115 1116 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1117 if (!isa<DbgInfoIntrinsic>(I)) 1118 ++SDNodeOrder; 1119 1120 CurInst = &I; 1121 1122 visit(I.getOpcode(), I); 1123 1124 if (!I.isTerminator() && !HasTailCall && 1125 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1126 CopyToExportRegsIfNeeded(&I); 1127 1128 CurInst = nullptr; 1129 } 1130 1131 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1132 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1133 } 1134 1135 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1136 // Note: this doesn't use InstVisitor, because it has to work with 1137 // ConstantExpr's in addition to instructions. 1138 switch (Opcode) { 1139 default: llvm_unreachable("Unknown instruction type encountered!"); 1140 // Build the switch statement using the Instruction.def file. 1141 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1142 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1143 #include "llvm/IR/Instruction.def" 1144 } 1145 } 1146 1147 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1148 DebugLoc DL, unsigned Order) { 1149 // We treat variadic dbg_values differently at this stage. 1150 if (DI->hasArgList()) { 1151 // For variadic dbg_values we will now insert an undef. 1152 // FIXME: We can potentially recover these! 1153 SmallVector<SDDbgOperand, 2> Locs; 1154 for (const Value *V : DI->getValues()) { 1155 auto Undef = UndefValue::get(V->getType()); 1156 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1157 } 1158 SDDbgValue *SDV = DAG.getDbgValueList( 1159 DI->getVariable(), DI->getExpression(), Locs, {}, 1160 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1161 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1162 } else { 1163 // TODO: Dangling debug info will eventually either be resolved or produce 1164 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1165 // between the original dbg.value location and its resolved DBG_VALUE, 1166 // which we should ideally fill with an extra Undef DBG_VALUE. 1167 assert(DI->getNumVariableLocationOps() == 1 && 1168 "DbgValueInst without an ArgList should have a single location " 1169 "operand."); 1170 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1171 } 1172 } 1173 1174 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1175 const DIExpression *Expr) { 1176 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1177 const DbgValueInst *DI = DDI.getDI(); 1178 DIVariable *DanglingVariable = DI->getVariable(); 1179 DIExpression *DanglingExpr = DI->getExpression(); 1180 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1181 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1182 return true; 1183 } 1184 return false; 1185 }; 1186 1187 for (auto &DDIMI : DanglingDebugInfoMap) { 1188 DanglingDebugInfoVector &DDIV = DDIMI.second; 1189 1190 // If debug info is to be dropped, run it through final checks to see 1191 // whether it can be salvaged. 1192 for (auto &DDI : DDIV) 1193 if (isMatchingDbgValue(DDI)) 1194 salvageUnresolvedDbgValue(DDI); 1195 1196 erase_if(DDIV, isMatchingDbgValue); 1197 } 1198 } 1199 1200 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1201 // generate the debug data structures now that we've seen its definition. 1202 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1203 SDValue Val) { 1204 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1205 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1206 return; 1207 1208 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1209 for (auto &DDI : DDIV) { 1210 const DbgValueInst *DI = DDI.getDI(); 1211 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1212 assert(DI && "Ill-formed DanglingDebugInfo"); 1213 DebugLoc dl = DDI.getdl(); 1214 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1215 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1216 DILocalVariable *Variable = DI->getVariable(); 1217 DIExpression *Expr = DI->getExpression(); 1218 assert(Variable->isValidLocationForIntrinsic(dl) && 1219 "Expected inlined-at fields to agree"); 1220 SDDbgValue *SDV; 1221 if (Val.getNode()) { 1222 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1223 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1224 // we couldn't resolve it directly when examining the DbgValue intrinsic 1225 // in the first place we should not be more successful here). Unless we 1226 // have some test case that prove this to be correct we should avoid 1227 // calling EmitFuncArgumentDbgValue here. 1228 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1229 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1230 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1231 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1232 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1233 // inserted after the definition of Val when emitting the instructions 1234 // after ISel. An alternative could be to teach 1235 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1236 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1237 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1238 << ValSDNodeOrder << "\n"); 1239 SDV = getDbgValue(Val, Variable, Expr, dl, 1240 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1241 DAG.AddDbgValue(SDV, false); 1242 } else 1243 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1244 << "in EmitFuncArgumentDbgValue\n"); 1245 } else { 1246 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1247 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1248 auto SDV = 1249 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1250 DAG.AddDbgValue(SDV, false); 1251 } 1252 } 1253 DDIV.clear(); 1254 } 1255 1256 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1257 // TODO: For the variadic implementation, instead of only checking the fail 1258 // state of `handleDebugValue`, we need know specifically which values were 1259 // invalid, so that we attempt to salvage only those values when processing 1260 // a DIArgList. 1261 assert(!DDI.getDI()->hasArgList() && 1262 "Not implemented for variadic dbg_values"); 1263 Value *V = DDI.getDI()->getValue(0); 1264 DILocalVariable *Var = DDI.getDI()->getVariable(); 1265 DIExpression *Expr = DDI.getDI()->getExpression(); 1266 DebugLoc DL = DDI.getdl(); 1267 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1268 unsigned SDOrder = DDI.getSDNodeOrder(); 1269 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1270 // that DW_OP_stack_value is desired. 1271 assert(isa<DbgValueInst>(DDI.getDI())); 1272 bool StackValue = true; 1273 1274 // Can this Value can be encoded without any further work? 1275 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1276 return; 1277 1278 // Attempt to salvage back through as many instructions as possible. Bail if 1279 // a non-instruction is seen, such as a constant expression or global 1280 // variable. FIXME: Further work could recover those too. 1281 while (isa<Instruction>(V)) { 1282 Instruction &VAsInst = *cast<Instruction>(V); 1283 // Temporary "0", awaiting real implementation. 1284 SmallVector<uint64_t, 16> Ops; 1285 SmallVector<Value *, 4> AdditionalValues; 1286 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1287 AdditionalValues); 1288 // If we cannot salvage any further, and haven't yet found a suitable debug 1289 // expression, bail out. 1290 if (!V) 1291 break; 1292 1293 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1294 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1295 // here for variadic dbg_values, remove that condition. 1296 if (!AdditionalValues.empty()) 1297 break; 1298 1299 // New value and expr now represent this debuginfo. 1300 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1301 1302 // Some kind of simplification occurred: check whether the operand of the 1303 // salvaged debug expression can be encoded in this DAG. 1304 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1305 /*IsVariadic=*/false)) { 1306 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1307 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1308 return; 1309 } 1310 } 1311 1312 // This was the final opportunity to salvage this debug information, and it 1313 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1314 // any earlier variable location. 1315 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1316 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1317 DAG.AddDbgValue(SDV, false); 1318 1319 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1320 << "\n"); 1321 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1322 << "\n"); 1323 } 1324 1325 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1326 DILocalVariable *Var, 1327 DIExpression *Expr, DebugLoc dl, 1328 DebugLoc InstDL, unsigned Order, 1329 bool IsVariadic) { 1330 if (Values.empty()) 1331 return true; 1332 SmallVector<SDDbgOperand> LocationOps; 1333 SmallVector<SDNode *> Dependencies; 1334 for (const Value *V : Values) { 1335 // Constant value. 1336 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1337 isa<ConstantPointerNull>(V)) { 1338 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1339 continue; 1340 } 1341 1342 // If the Value is a frame index, we can create a FrameIndex debug value 1343 // without relying on the DAG at all. 1344 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1345 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1346 if (SI != FuncInfo.StaticAllocaMap.end()) { 1347 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1348 continue; 1349 } 1350 } 1351 1352 // Do not use getValue() in here; we don't want to generate code at 1353 // this point if it hasn't been done yet. 1354 SDValue N = NodeMap[V]; 1355 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1356 N = UnusedArgNodeMap[V]; 1357 if (N.getNode()) { 1358 // Only emit func arg dbg value for non-variadic dbg.values for now. 1359 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1360 return true; 1361 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1362 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1363 // describe stack slot locations. 1364 // 1365 // Consider "int x = 0; int *px = &x;". There are two kinds of 1366 // interesting debug values here after optimization: 1367 // 1368 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1369 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1370 // 1371 // Both describe the direct values of their associated variables. 1372 Dependencies.push_back(N.getNode()); 1373 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1374 continue; 1375 } 1376 LocationOps.emplace_back( 1377 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1378 continue; 1379 } 1380 1381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1382 // Special rules apply for the first dbg.values of parameter variables in a 1383 // function. Identify them by the fact they reference Argument Values, that 1384 // they're parameters, and they are parameters of the current function. We 1385 // need to let them dangle until they get an SDNode. 1386 bool IsParamOfFunc = 1387 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1388 if (IsParamOfFunc) 1389 return false; 1390 1391 // The value is not used in this block yet (or it would have an SDNode). 1392 // We still want the value to appear for the user if possible -- if it has 1393 // an associated VReg, we can refer to that instead. 1394 auto VMI = FuncInfo.ValueMap.find(V); 1395 if (VMI != FuncInfo.ValueMap.end()) { 1396 unsigned Reg = VMI->second; 1397 // If this is a PHI node, it may be split up into several MI PHI nodes 1398 // (in FunctionLoweringInfo::set). 1399 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1400 V->getType(), None); 1401 if (RFV.occupiesMultipleRegs()) { 1402 // FIXME: We could potentially support variadic dbg_values here. 1403 if (IsVariadic) 1404 return false; 1405 unsigned Offset = 0; 1406 unsigned BitsToDescribe = 0; 1407 if (auto VarSize = Var->getSizeInBits()) 1408 BitsToDescribe = *VarSize; 1409 if (auto Fragment = Expr->getFragmentInfo()) 1410 BitsToDescribe = Fragment->SizeInBits; 1411 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1412 // Bail out if all bits are described already. 1413 if (Offset >= BitsToDescribe) 1414 break; 1415 // TODO: handle scalable vectors. 1416 unsigned RegisterSize = RegAndSize.second; 1417 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1418 ? BitsToDescribe - Offset 1419 : RegisterSize; 1420 auto FragmentExpr = DIExpression::createFragmentExpression( 1421 Expr, Offset, FragmentSize); 1422 if (!FragmentExpr) 1423 continue; 1424 SDDbgValue *SDV = DAG.getVRegDbgValue( 1425 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1426 DAG.AddDbgValue(SDV, false); 1427 Offset += RegisterSize; 1428 } 1429 return true; 1430 } 1431 // We can use simple vreg locations for variadic dbg_values as well. 1432 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1433 continue; 1434 } 1435 // We failed to create a SDDbgOperand for V. 1436 return false; 1437 } 1438 1439 // We have created a SDDbgOperand for each Value in Values. 1440 // Should use Order instead of SDNodeOrder? 1441 assert(!LocationOps.empty()); 1442 SDDbgValue *SDV = 1443 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1444 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1445 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1446 return true; 1447 } 1448 1449 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1450 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1451 for (auto &Pair : DanglingDebugInfoMap) 1452 for (auto &DDI : Pair.second) 1453 salvageUnresolvedDbgValue(DDI); 1454 clearDanglingDebugInfo(); 1455 } 1456 1457 /// getCopyFromRegs - If there was virtual register allocated for the value V 1458 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1459 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1460 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1461 SDValue Result; 1462 1463 if (It != FuncInfo.ValueMap.end()) { 1464 Register InReg = It->second; 1465 1466 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1467 DAG.getDataLayout(), InReg, Ty, 1468 None); // This is not an ABI copy. 1469 SDValue Chain = DAG.getEntryNode(); 1470 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1471 V); 1472 resolveDanglingDebugInfo(V, Result); 1473 } 1474 1475 return Result; 1476 } 1477 1478 /// getValue - Return an SDValue for the given Value. 1479 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1480 // If we already have an SDValue for this value, use it. It's important 1481 // to do this first, so that we don't create a CopyFromReg if we already 1482 // have a regular SDValue. 1483 SDValue &N = NodeMap[V]; 1484 if (N.getNode()) return N; 1485 1486 // If there's a virtual register allocated and initialized for this 1487 // value, use it. 1488 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1489 return copyFromReg; 1490 1491 // Otherwise create a new SDValue and remember it. 1492 SDValue Val = getValueImpl(V); 1493 NodeMap[V] = Val; 1494 resolveDanglingDebugInfo(V, Val); 1495 return Val; 1496 } 1497 1498 /// getNonRegisterValue - Return an SDValue for the given Value, but 1499 /// don't look in FuncInfo.ValueMap for a virtual register. 1500 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1501 // If we already have an SDValue for this value, use it. 1502 SDValue &N = NodeMap[V]; 1503 if (N.getNode()) { 1504 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1505 // Remove the debug location from the node as the node is about to be used 1506 // in a location which may differ from the original debug location. This 1507 // is relevant to Constant and ConstantFP nodes because they can appear 1508 // as constant expressions inside PHI nodes. 1509 N->setDebugLoc(DebugLoc()); 1510 } 1511 return N; 1512 } 1513 1514 // Otherwise create a new SDValue and remember it. 1515 SDValue Val = getValueImpl(V); 1516 NodeMap[V] = Val; 1517 resolveDanglingDebugInfo(V, Val); 1518 return Val; 1519 } 1520 1521 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1522 /// Create an SDValue for the given value. 1523 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1524 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1525 1526 if (const Constant *C = dyn_cast<Constant>(V)) { 1527 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1528 1529 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1530 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1531 1532 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1533 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1534 1535 if (isa<ConstantPointerNull>(C)) { 1536 unsigned AS = V->getType()->getPointerAddressSpace(); 1537 return DAG.getConstant(0, getCurSDLoc(), 1538 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1539 } 1540 1541 if (match(C, m_VScale(DAG.getDataLayout()))) 1542 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1543 1544 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1545 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1546 1547 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1548 return DAG.getUNDEF(VT); 1549 1550 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1551 visit(CE->getOpcode(), *CE); 1552 SDValue N1 = NodeMap[V]; 1553 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1554 return N1; 1555 } 1556 1557 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1558 SmallVector<SDValue, 4> Constants; 1559 for (const Use &U : C->operands()) { 1560 SDNode *Val = getValue(U).getNode(); 1561 // If the operand is an empty aggregate, there are no values. 1562 if (!Val) continue; 1563 // Add each leaf value from the operand to the Constants list 1564 // to form a flattened list of all the values. 1565 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1566 Constants.push_back(SDValue(Val, i)); 1567 } 1568 1569 return DAG.getMergeValues(Constants, getCurSDLoc()); 1570 } 1571 1572 if (const ConstantDataSequential *CDS = 1573 dyn_cast<ConstantDataSequential>(C)) { 1574 SmallVector<SDValue, 4> Ops; 1575 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1576 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1577 // Add each leaf value from the operand to the Constants list 1578 // to form a flattened list of all the values. 1579 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1580 Ops.push_back(SDValue(Val, i)); 1581 } 1582 1583 if (isa<ArrayType>(CDS->getType())) 1584 return DAG.getMergeValues(Ops, getCurSDLoc()); 1585 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1586 } 1587 1588 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1589 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1590 "Unknown struct or array constant!"); 1591 1592 SmallVector<EVT, 4> ValueVTs; 1593 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1594 unsigned NumElts = ValueVTs.size(); 1595 if (NumElts == 0) 1596 return SDValue(); // empty struct 1597 SmallVector<SDValue, 4> Constants(NumElts); 1598 for (unsigned i = 0; i != NumElts; ++i) { 1599 EVT EltVT = ValueVTs[i]; 1600 if (isa<UndefValue>(C)) 1601 Constants[i] = DAG.getUNDEF(EltVT); 1602 else if (EltVT.isFloatingPoint()) 1603 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1604 else 1605 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1606 } 1607 1608 return DAG.getMergeValues(Constants, getCurSDLoc()); 1609 } 1610 1611 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1612 return DAG.getBlockAddress(BA, VT); 1613 1614 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1615 return getValue(Equiv->getGlobalValue()); 1616 1617 VectorType *VecTy = cast<VectorType>(V->getType()); 1618 1619 // Now that we know the number and type of the elements, get that number of 1620 // elements into the Ops array based on what kind of constant it is. 1621 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1622 SmallVector<SDValue, 16> Ops; 1623 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1624 for (unsigned i = 0; i != NumElements; ++i) 1625 Ops.push_back(getValue(CV->getOperand(i))); 1626 1627 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1628 } else if (isa<ConstantAggregateZero>(C)) { 1629 EVT EltVT = 1630 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1631 1632 SDValue Op; 1633 if (EltVT.isFloatingPoint()) 1634 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1635 else 1636 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1637 1638 if (isa<ScalableVectorType>(VecTy)) 1639 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1640 else { 1641 SmallVector<SDValue, 16> Ops; 1642 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1643 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1644 } 1645 } 1646 llvm_unreachable("Unknown vector constant"); 1647 } 1648 1649 // If this is a static alloca, generate it as the frameindex instead of 1650 // computation. 1651 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1652 DenseMap<const AllocaInst*, int>::iterator SI = 1653 FuncInfo.StaticAllocaMap.find(AI); 1654 if (SI != FuncInfo.StaticAllocaMap.end()) 1655 return DAG.getFrameIndex(SI->second, 1656 TLI.getFrameIndexTy(DAG.getDataLayout())); 1657 } 1658 1659 // If this is an instruction which fast-isel has deferred, select it now. 1660 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1661 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1662 1663 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1664 Inst->getType(), None); 1665 SDValue Chain = DAG.getEntryNode(); 1666 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1667 } 1668 1669 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1670 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1671 } 1672 llvm_unreachable("Can't get register for value!"); 1673 } 1674 1675 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1676 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1677 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1678 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1679 bool IsSEH = isAsynchronousEHPersonality(Pers); 1680 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1681 if (!IsSEH) 1682 CatchPadMBB->setIsEHScopeEntry(); 1683 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1684 if (IsMSVCCXX || IsCoreCLR) 1685 CatchPadMBB->setIsEHFuncletEntry(); 1686 } 1687 1688 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1689 // Update machine-CFG edge. 1690 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1691 FuncInfo.MBB->addSuccessor(TargetMBB); 1692 TargetMBB->setIsEHCatchretTarget(true); 1693 DAG.getMachineFunction().setHasEHCatchret(true); 1694 1695 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1696 bool IsSEH = isAsynchronousEHPersonality(Pers); 1697 if (IsSEH) { 1698 // If this is not a fall-through branch or optimizations are switched off, 1699 // emit the branch. 1700 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1701 TM.getOptLevel() == CodeGenOpt::None) 1702 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1703 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1704 return; 1705 } 1706 1707 // Figure out the funclet membership for the catchret's successor. 1708 // This will be used by the FuncletLayout pass to determine how to order the 1709 // BB's. 1710 // A 'catchret' returns to the outer scope's color. 1711 Value *ParentPad = I.getCatchSwitchParentPad(); 1712 const BasicBlock *SuccessorColor; 1713 if (isa<ConstantTokenNone>(ParentPad)) 1714 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1715 else 1716 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1717 assert(SuccessorColor && "No parent funclet for catchret!"); 1718 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1719 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1720 1721 // Create the terminator node. 1722 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1723 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1724 DAG.getBasicBlock(SuccessorColorMBB)); 1725 DAG.setRoot(Ret); 1726 } 1727 1728 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1729 // Don't emit any special code for the cleanuppad instruction. It just marks 1730 // the start of an EH scope/funclet. 1731 FuncInfo.MBB->setIsEHScopeEntry(); 1732 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1733 if (Pers != EHPersonality::Wasm_CXX) { 1734 FuncInfo.MBB->setIsEHFuncletEntry(); 1735 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1736 } 1737 } 1738 1739 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1740 // not match, it is OK to add only the first unwind destination catchpad to the 1741 // successors, because there will be at least one invoke instruction within the 1742 // catch scope that points to the next unwind destination, if one exists, so 1743 // CFGSort cannot mess up with BB sorting order. 1744 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1745 // call within them, and catchpads only consisting of 'catch (...)' have a 1746 // '__cxa_end_catch' call within them, both of which generate invokes in case 1747 // the next unwind destination exists, i.e., the next unwind destination is not 1748 // the caller.) 1749 // 1750 // Having at most one EH pad successor is also simpler and helps later 1751 // transformations. 1752 // 1753 // For example, 1754 // current: 1755 // invoke void @foo to ... unwind label %catch.dispatch 1756 // catch.dispatch: 1757 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1758 // catch.start: 1759 // ... 1760 // ... in this BB or some other child BB dominated by this BB there will be an 1761 // invoke that points to 'next' BB as an unwind destination 1762 // 1763 // next: ; We don't need to add this to 'current' BB's successor 1764 // ... 1765 static void findWasmUnwindDestinations( 1766 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1767 BranchProbability Prob, 1768 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1769 &UnwindDests) { 1770 while (EHPadBB) { 1771 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1772 if (isa<CleanupPadInst>(Pad)) { 1773 // Stop on cleanup pads. 1774 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1775 UnwindDests.back().first->setIsEHScopeEntry(); 1776 break; 1777 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1778 // Add the catchpad handlers to the possible destinations. We don't 1779 // continue to the unwind destination of the catchswitch for wasm. 1780 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1781 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1782 UnwindDests.back().first->setIsEHScopeEntry(); 1783 } 1784 break; 1785 } else { 1786 continue; 1787 } 1788 } 1789 } 1790 1791 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1792 /// many places it could ultimately go. In the IR, we have a single unwind 1793 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1794 /// This function skips over imaginary basic blocks that hold catchswitch 1795 /// instructions, and finds all the "real" machine 1796 /// basic block destinations. As those destinations may not be successors of 1797 /// EHPadBB, here we also calculate the edge probability to those destinations. 1798 /// The passed-in Prob is the edge probability to EHPadBB. 1799 static void findUnwindDestinations( 1800 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1801 BranchProbability Prob, 1802 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1803 &UnwindDests) { 1804 EHPersonality Personality = 1805 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1806 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1807 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1808 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1809 bool IsSEH = isAsynchronousEHPersonality(Personality); 1810 1811 if (IsWasmCXX) { 1812 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1813 assert(UnwindDests.size() <= 1 && 1814 "There should be at most one unwind destination for wasm"); 1815 return; 1816 } 1817 1818 while (EHPadBB) { 1819 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1820 BasicBlock *NewEHPadBB = nullptr; 1821 if (isa<LandingPadInst>(Pad)) { 1822 // Stop on landingpads. They are not funclets. 1823 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1824 break; 1825 } else if (isa<CleanupPadInst>(Pad)) { 1826 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1827 // personalities. 1828 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1829 UnwindDests.back().first->setIsEHScopeEntry(); 1830 UnwindDests.back().first->setIsEHFuncletEntry(); 1831 break; 1832 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1833 // Add the catchpad handlers to the possible destinations. 1834 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1835 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1836 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1837 if (IsMSVCCXX || IsCoreCLR) 1838 UnwindDests.back().first->setIsEHFuncletEntry(); 1839 if (!IsSEH) 1840 UnwindDests.back().first->setIsEHScopeEntry(); 1841 } 1842 NewEHPadBB = CatchSwitch->getUnwindDest(); 1843 } else { 1844 continue; 1845 } 1846 1847 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1848 if (BPI && NewEHPadBB) 1849 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1850 EHPadBB = NewEHPadBB; 1851 } 1852 } 1853 1854 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1855 // Update successor info. 1856 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1857 auto UnwindDest = I.getUnwindDest(); 1858 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1859 BranchProbability UnwindDestProb = 1860 (BPI && UnwindDest) 1861 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1862 : BranchProbability::getZero(); 1863 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1864 for (auto &UnwindDest : UnwindDests) { 1865 UnwindDest.first->setIsEHPad(); 1866 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1867 } 1868 FuncInfo.MBB->normalizeSuccProbs(); 1869 1870 // Create the terminator node. 1871 SDValue Ret = 1872 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1873 DAG.setRoot(Ret); 1874 } 1875 1876 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1877 report_fatal_error("visitCatchSwitch not yet implemented!"); 1878 } 1879 1880 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1881 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1882 auto &DL = DAG.getDataLayout(); 1883 SDValue Chain = getControlRoot(); 1884 SmallVector<ISD::OutputArg, 8> Outs; 1885 SmallVector<SDValue, 8> OutVals; 1886 1887 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1888 // lower 1889 // 1890 // %val = call <ty> @llvm.experimental.deoptimize() 1891 // ret <ty> %val 1892 // 1893 // differently. 1894 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1895 LowerDeoptimizingReturn(); 1896 return; 1897 } 1898 1899 if (!FuncInfo.CanLowerReturn) { 1900 unsigned DemoteReg = FuncInfo.DemoteRegister; 1901 const Function *F = I.getParent()->getParent(); 1902 1903 // Emit a store of the return value through the virtual register. 1904 // Leave Outs empty so that LowerReturn won't try to load return 1905 // registers the usual way. 1906 SmallVector<EVT, 1> PtrValueVTs; 1907 ComputeValueVTs(TLI, DL, 1908 F->getReturnType()->getPointerTo( 1909 DAG.getDataLayout().getAllocaAddrSpace()), 1910 PtrValueVTs); 1911 1912 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1913 DemoteReg, PtrValueVTs[0]); 1914 SDValue RetOp = getValue(I.getOperand(0)); 1915 1916 SmallVector<EVT, 4> ValueVTs, MemVTs; 1917 SmallVector<uint64_t, 4> Offsets; 1918 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1919 &Offsets); 1920 unsigned NumValues = ValueVTs.size(); 1921 1922 SmallVector<SDValue, 4> Chains(NumValues); 1923 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1924 for (unsigned i = 0; i != NumValues; ++i) { 1925 // An aggregate return value cannot wrap around the address space, so 1926 // offsets to its parts don't wrap either. 1927 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1928 TypeSize::Fixed(Offsets[i])); 1929 1930 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1931 if (MemVTs[i] != ValueVTs[i]) 1932 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1933 Chains[i] = DAG.getStore( 1934 Chain, getCurSDLoc(), Val, 1935 // FIXME: better loc info would be nice. 1936 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1937 commonAlignment(BaseAlign, Offsets[i])); 1938 } 1939 1940 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1941 MVT::Other, Chains); 1942 } else if (I.getNumOperands() != 0) { 1943 SmallVector<EVT, 4> ValueVTs; 1944 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1945 unsigned NumValues = ValueVTs.size(); 1946 if (NumValues) { 1947 SDValue RetOp = getValue(I.getOperand(0)); 1948 1949 const Function *F = I.getParent()->getParent(); 1950 1951 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1952 I.getOperand(0)->getType(), F->getCallingConv(), 1953 /*IsVarArg*/ false, DL); 1954 1955 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1956 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 1957 ExtendKind = ISD::SIGN_EXTEND; 1958 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 1959 ExtendKind = ISD::ZERO_EXTEND; 1960 1961 LLVMContext &Context = F->getContext(); 1962 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 1963 1964 for (unsigned j = 0; j != NumValues; ++j) { 1965 EVT VT = ValueVTs[j]; 1966 1967 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1968 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1969 1970 CallingConv::ID CC = F->getCallingConv(); 1971 1972 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1973 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1974 SmallVector<SDValue, 4> Parts(NumParts); 1975 getCopyToParts(DAG, getCurSDLoc(), 1976 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1977 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1978 1979 // 'inreg' on function refers to return value 1980 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1981 if (RetInReg) 1982 Flags.setInReg(); 1983 1984 if (I.getOperand(0)->getType()->isPointerTy()) { 1985 Flags.setPointer(); 1986 Flags.setPointerAddrSpace( 1987 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1988 } 1989 1990 if (NeedsRegBlock) { 1991 Flags.setInConsecutiveRegs(); 1992 if (j == NumValues - 1) 1993 Flags.setInConsecutiveRegsLast(); 1994 } 1995 1996 // Propagate extension type if any 1997 if (ExtendKind == ISD::SIGN_EXTEND) 1998 Flags.setSExt(); 1999 else if (ExtendKind == ISD::ZERO_EXTEND) 2000 Flags.setZExt(); 2001 2002 for (unsigned i = 0; i < NumParts; ++i) { 2003 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 2004 VT, /*isfixed=*/true, 0, 0)); 2005 OutVals.push_back(Parts[i]); 2006 } 2007 } 2008 } 2009 } 2010 2011 // Push in swifterror virtual register as the last element of Outs. This makes 2012 // sure swifterror virtual register will be returned in the swifterror 2013 // physical register. 2014 const Function *F = I.getParent()->getParent(); 2015 if (TLI.supportSwiftError() && 2016 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2017 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2018 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2019 Flags.setSwiftError(); 2020 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 2021 EVT(TLI.getPointerTy(DL)) /*argvt*/, 2022 true /*isfixed*/, 1 /*origidx*/, 2023 0 /*partOffs*/)); 2024 // Create SDNode for the swifterror virtual register. 2025 OutVals.push_back( 2026 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2027 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2028 EVT(TLI.getPointerTy(DL)))); 2029 } 2030 2031 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2032 CallingConv::ID CallConv = 2033 DAG.getMachineFunction().getFunction().getCallingConv(); 2034 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2035 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2036 2037 // Verify that the target's LowerReturn behaved as expected. 2038 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2039 "LowerReturn didn't return a valid chain!"); 2040 2041 // Update the DAG with the new chain value resulting from return lowering. 2042 DAG.setRoot(Chain); 2043 } 2044 2045 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2046 /// created for it, emit nodes to copy the value into the virtual 2047 /// registers. 2048 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2049 // Skip empty types 2050 if (V->getType()->isEmptyTy()) 2051 return; 2052 2053 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2054 if (VMI != FuncInfo.ValueMap.end()) { 2055 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2056 CopyValueToVirtualRegister(V, VMI->second); 2057 } 2058 } 2059 2060 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2061 /// the current basic block, add it to ValueMap now so that we'll get a 2062 /// CopyTo/FromReg. 2063 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2064 // No need to export constants. 2065 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2066 2067 // Already exported? 2068 if (FuncInfo.isExportedInst(V)) return; 2069 2070 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2071 CopyValueToVirtualRegister(V, Reg); 2072 } 2073 2074 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2075 const BasicBlock *FromBB) { 2076 // The operands of the setcc have to be in this block. We don't know 2077 // how to export them from some other block. 2078 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2079 // Can export from current BB. 2080 if (VI->getParent() == FromBB) 2081 return true; 2082 2083 // Is already exported, noop. 2084 return FuncInfo.isExportedInst(V); 2085 } 2086 2087 // If this is an argument, we can export it if the BB is the entry block or 2088 // if it is already exported. 2089 if (isa<Argument>(V)) { 2090 if (FromBB->isEntryBlock()) 2091 return true; 2092 2093 // Otherwise, can only export this if it is already exported. 2094 return FuncInfo.isExportedInst(V); 2095 } 2096 2097 // Otherwise, constants can always be exported. 2098 return true; 2099 } 2100 2101 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2102 BranchProbability 2103 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2104 const MachineBasicBlock *Dst) const { 2105 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2106 const BasicBlock *SrcBB = Src->getBasicBlock(); 2107 const BasicBlock *DstBB = Dst->getBasicBlock(); 2108 if (!BPI) { 2109 // If BPI is not available, set the default probability as 1 / N, where N is 2110 // the number of successors. 2111 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2112 return BranchProbability(1, SuccSize); 2113 } 2114 return BPI->getEdgeProbability(SrcBB, DstBB); 2115 } 2116 2117 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2118 MachineBasicBlock *Dst, 2119 BranchProbability Prob) { 2120 if (!FuncInfo.BPI) 2121 Src->addSuccessorWithoutProb(Dst); 2122 else { 2123 if (Prob.isUnknown()) 2124 Prob = getEdgeProbability(Src, Dst); 2125 Src->addSuccessor(Dst, Prob); 2126 } 2127 } 2128 2129 static bool InBlock(const Value *V, const BasicBlock *BB) { 2130 if (const Instruction *I = dyn_cast<Instruction>(V)) 2131 return I->getParent() == BB; 2132 return true; 2133 } 2134 2135 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2136 /// This function emits a branch and is used at the leaves of an OR or an 2137 /// AND operator tree. 2138 void 2139 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2140 MachineBasicBlock *TBB, 2141 MachineBasicBlock *FBB, 2142 MachineBasicBlock *CurBB, 2143 MachineBasicBlock *SwitchBB, 2144 BranchProbability TProb, 2145 BranchProbability FProb, 2146 bool InvertCond) { 2147 const BasicBlock *BB = CurBB->getBasicBlock(); 2148 2149 // If the leaf of the tree is a comparison, merge the condition into 2150 // the caseblock. 2151 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2152 // The operands of the cmp have to be in this block. We don't know 2153 // how to export them from some other block. If this is the first block 2154 // of the sequence, no exporting is needed. 2155 if (CurBB == SwitchBB || 2156 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2157 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2158 ISD::CondCode Condition; 2159 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2160 ICmpInst::Predicate Pred = 2161 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2162 Condition = getICmpCondCode(Pred); 2163 } else { 2164 const FCmpInst *FC = cast<FCmpInst>(Cond); 2165 FCmpInst::Predicate Pred = 2166 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2167 Condition = getFCmpCondCode(Pred); 2168 if (TM.Options.NoNaNsFPMath) 2169 Condition = getFCmpCodeWithoutNaN(Condition); 2170 } 2171 2172 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2173 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2174 SL->SwitchCases.push_back(CB); 2175 return; 2176 } 2177 } 2178 2179 // Create a CaseBlock record representing this branch. 2180 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2181 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2182 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2183 SL->SwitchCases.push_back(CB); 2184 } 2185 2186 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2187 MachineBasicBlock *TBB, 2188 MachineBasicBlock *FBB, 2189 MachineBasicBlock *CurBB, 2190 MachineBasicBlock *SwitchBB, 2191 Instruction::BinaryOps Opc, 2192 BranchProbability TProb, 2193 BranchProbability FProb, 2194 bool InvertCond) { 2195 // Skip over not part of the tree and remember to invert op and operands at 2196 // next level. 2197 Value *NotCond; 2198 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2199 InBlock(NotCond, CurBB->getBasicBlock())) { 2200 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2201 !InvertCond); 2202 return; 2203 } 2204 2205 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2206 const Value *BOpOp0, *BOpOp1; 2207 // Compute the effective opcode for Cond, taking into account whether it needs 2208 // to be inverted, e.g. 2209 // and (not (or A, B)), C 2210 // gets lowered as 2211 // and (and (not A, not B), C) 2212 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2213 if (BOp) { 2214 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2215 ? Instruction::And 2216 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2217 ? Instruction::Or 2218 : (Instruction::BinaryOps)0); 2219 if (InvertCond) { 2220 if (BOpc == Instruction::And) 2221 BOpc = Instruction::Or; 2222 else if (BOpc == Instruction::Or) 2223 BOpc = Instruction::And; 2224 } 2225 } 2226 2227 // If this node is not part of the or/and tree, emit it as a branch. 2228 // Note that all nodes in the tree should have same opcode. 2229 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2230 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2231 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2232 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2233 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2234 TProb, FProb, InvertCond); 2235 return; 2236 } 2237 2238 // Create TmpBB after CurBB. 2239 MachineFunction::iterator BBI(CurBB); 2240 MachineFunction &MF = DAG.getMachineFunction(); 2241 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2242 CurBB->getParent()->insert(++BBI, TmpBB); 2243 2244 if (Opc == Instruction::Or) { 2245 // Codegen X | Y as: 2246 // BB1: 2247 // jmp_if_X TBB 2248 // jmp TmpBB 2249 // TmpBB: 2250 // jmp_if_Y TBB 2251 // jmp FBB 2252 // 2253 2254 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2255 // The requirement is that 2256 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2257 // = TrueProb for original BB. 2258 // Assuming the original probabilities are A and B, one choice is to set 2259 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2260 // A/(1+B) and 2B/(1+B). This choice assumes that 2261 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2262 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2263 // TmpBB, but the math is more complicated. 2264 2265 auto NewTrueProb = TProb / 2; 2266 auto NewFalseProb = TProb / 2 + FProb; 2267 // Emit the LHS condition. 2268 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2269 NewFalseProb, InvertCond); 2270 2271 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2272 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2273 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2274 // Emit the RHS condition into TmpBB. 2275 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2276 Probs[1], InvertCond); 2277 } else { 2278 assert(Opc == Instruction::And && "Unknown merge op!"); 2279 // Codegen X & Y as: 2280 // BB1: 2281 // jmp_if_X TmpBB 2282 // jmp FBB 2283 // TmpBB: 2284 // jmp_if_Y TBB 2285 // jmp FBB 2286 // 2287 // This requires creation of TmpBB after CurBB. 2288 2289 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2290 // The requirement is that 2291 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2292 // = FalseProb for original BB. 2293 // Assuming the original probabilities are A and B, one choice is to set 2294 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2295 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2296 // TrueProb for BB1 * FalseProb for TmpBB. 2297 2298 auto NewTrueProb = TProb + FProb / 2; 2299 auto NewFalseProb = FProb / 2; 2300 // Emit the LHS condition. 2301 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2302 NewFalseProb, InvertCond); 2303 2304 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2305 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2306 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2307 // Emit the RHS condition into TmpBB. 2308 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2309 Probs[1], InvertCond); 2310 } 2311 } 2312 2313 /// If the set of cases should be emitted as a series of branches, return true. 2314 /// If we should emit this as a bunch of and/or'd together conditions, return 2315 /// false. 2316 bool 2317 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2318 if (Cases.size() != 2) return true; 2319 2320 // If this is two comparisons of the same values or'd or and'd together, they 2321 // will get folded into a single comparison, so don't emit two blocks. 2322 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2323 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2324 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2325 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2326 return false; 2327 } 2328 2329 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2330 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2331 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2332 Cases[0].CC == Cases[1].CC && 2333 isa<Constant>(Cases[0].CmpRHS) && 2334 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2335 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2336 return false; 2337 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2338 return false; 2339 } 2340 2341 return true; 2342 } 2343 2344 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2345 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2346 2347 // Update machine-CFG edges. 2348 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2349 2350 if (I.isUnconditional()) { 2351 // Update machine-CFG edges. 2352 BrMBB->addSuccessor(Succ0MBB); 2353 2354 // If this is not a fall-through branch or optimizations are switched off, 2355 // emit the branch. 2356 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2357 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2358 MVT::Other, getControlRoot(), 2359 DAG.getBasicBlock(Succ0MBB))); 2360 2361 return; 2362 } 2363 2364 // If this condition is one of the special cases we handle, do special stuff 2365 // now. 2366 const Value *CondVal = I.getCondition(); 2367 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2368 2369 // If this is a series of conditions that are or'd or and'd together, emit 2370 // this as a sequence of branches instead of setcc's with and/or operations. 2371 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2372 // unpredictable branches, and vector extracts because those jumps are likely 2373 // expensive for any target), this should improve performance. 2374 // For example, instead of something like: 2375 // cmp A, B 2376 // C = seteq 2377 // cmp D, E 2378 // F = setle 2379 // or C, F 2380 // jnz foo 2381 // Emit: 2382 // cmp A, B 2383 // je foo 2384 // cmp D, E 2385 // jle foo 2386 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2387 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2388 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2389 Value *Vec; 2390 const Value *BOp0, *BOp1; 2391 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2392 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2393 Opcode = Instruction::And; 2394 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2395 Opcode = Instruction::Or; 2396 2397 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2398 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2399 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2400 getEdgeProbability(BrMBB, Succ0MBB), 2401 getEdgeProbability(BrMBB, Succ1MBB), 2402 /*InvertCond=*/false); 2403 // If the compares in later blocks need to use values not currently 2404 // exported from this block, export them now. This block should always 2405 // be the first entry. 2406 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2407 2408 // Allow some cases to be rejected. 2409 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2410 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2411 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2412 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2413 } 2414 2415 // Emit the branch for this block. 2416 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2417 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2418 return; 2419 } 2420 2421 // Okay, we decided not to do this, remove any inserted MBB's and clear 2422 // SwitchCases. 2423 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2424 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2425 2426 SL->SwitchCases.clear(); 2427 } 2428 } 2429 2430 // Create a CaseBlock record representing this branch. 2431 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2432 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2433 2434 // Use visitSwitchCase to actually insert the fast branch sequence for this 2435 // cond branch. 2436 visitSwitchCase(CB, BrMBB); 2437 } 2438 2439 /// visitSwitchCase - Emits the necessary code to represent a single node in 2440 /// the binary search tree resulting from lowering a switch instruction. 2441 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2442 MachineBasicBlock *SwitchBB) { 2443 SDValue Cond; 2444 SDValue CondLHS = getValue(CB.CmpLHS); 2445 SDLoc dl = CB.DL; 2446 2447 if (CB.CC == ISD::SETTRUE) { 2448 // Branch or fall through to TrueBB. 2449 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2450 SwitchBB->normalizeSuccProbs(); 2451 if (CB.TrueBB != NextBlock(SwitchBB)) { 2452 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2453 DAG.getBasicBlock(CB.TrueBB))); 2454 } 2455 return; 2456 } 2457 2458 auto &TLI = DAG.getTargetLoweringInfo(); 2459 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2460 2461 // Build the setcc now. 2462 if (!CB.CmpMHS) { 2463 // Fold "(X == true)" to X and "(X == false)" to !X to 2464 // handle common cases produced by branch lowering. 2465 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2466 CB.CC == ISD::SETEQ) 2467 Cond = CondLHS; 2468 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2469 CB.CC == ISD::SETEQ) { 2470 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2471 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2472 } else { 2473 SDValue CondRHS = getValue(CB.CmpRHS); 2474 2475 // If a pointer's DAG type is larger than its memory type then the DAG 2476 // values are zero-extended. This breaks signed comparisons so truncate 2477 // back to the underlying type before doing the compare. 2478 if (CondLHS.getValueType() != MemVT) { 2479 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2480 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2481 } 2482 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2483 } 2484 } else { 2485 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2486 2487 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2488 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2489 2490 SDValue CmpOp = getValue(CB.CmpMHS); 2491 EVT VT = CmpOp.getValueType(); 2492 2493 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2494 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2495 ISD::SETLE); 2496 } else { 2497 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2498 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2499 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2500 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2501 } 2502 } 2503 2504 // Update successor info 2505 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2506 // TrueBB and FalseBB are always different unless the incoming IR is 2507 // degenerate. This only happens when running llc on weird IR. 2508 if (CB.TrueBB != CB.FalseBB) 2509 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2510 SwitchBB->normalizeSuccProbs(); 2511 2512 // If the lhs block is the next block, invert the condition so that we can 2513 // fall through to the lhs instead of the rhs block. 2514 if (CB.TrueBB == NextBlock(SwitchBB)) { 2515 std::swap(CB.TrueBB, CB.FalseBB); 2516 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2517 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2518 } 2519 2520 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2521 MVT::Other, getControlRoot(), Cond, 2522 DAG.getBasicBlock(CB.TrueBB)); 2523 2524 // Insert the false branch. Do this even if it's a fall through branch, 2525 // this makes it easier to do DAG optimizations which require inverting 2526 // the branch condition. 2527 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2528 DAG.getBasicBlock(CB.FalseBB)); 2529 2530 DAG.setRoot(BrCond); 2531 } 2532 2533 /// visitJumpTable - Emit JumpTable node in the current MBB 2534 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2535 // Emit the code for the jump table 2536 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2537 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2538 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2539 JT.Reg, PTy); 2540 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2541 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2542 MVT::Other, Index.getValue(1), 2543 Table, Index); 2544 DAG.setRoot(BrJumpTable); 2545 } 2546 2547 /// visitJumpTableHeader - This function emits necessary code to produce index 2548 /// in the JumpTable from switch case. 2549 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2550 JumpTableHeader &JTH, 2551 MachineBasicBlock *SwitchBB) { 2552 SDLoc dl = getCurSDLoc(); 2553 2554 // Subtract the lowest switch case value from the value being switched on. 2555 SDValue SwitchOp = getValue(JTH.SValue); 2556 EVT VT = SwitchOp.getValueType(); 2557 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2558 DAG.getConstant(JTH.First, dl, VT)); 2559 2560 // The SDNode we just created, which holds the value being switched on minus 2561 // the smallest case value, needs to be copied to a virtual register so it 2562 // can be used as an index into the jump table in a subsequent basic block. 2563 // This value may be smaller or larger than the target's pointer type, and 2564 // therefore require extension or truncating. 2565 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2566 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2567 2568 unsigned JumpTableReg = 2569 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2570 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2571 JumpTableReg, SwitchOp); 2572 JT.Reg = JumpTableReg; 2573 2574 if (!JTH.OmitRangeCheck) { 2575 // Emit the range check for the jump table, and branch to the default block 2576 // for the switch statement if the value being switched on exceeds the 2577 // largest case in the switch. 2578 SDValue CMP = DAG.getSetCC( 2579 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2580 Sub.getValueType()), 2581 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2582 2583 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2584 MVT::Other, CopyTo, CMP, 2585 DAG.getBasicBlock(JT.Default)); 2586 2587 // Avoid emitting unnecessary branches to the next block. 2588 if (JT.MBB != NextBlock(SwitchBB)) 2589 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2590 DAG.getBasicBlock(JT.MBB)); 2591 2592 DAG.setRoot(BrCond); 2593 } else { 2594 // Avoid emitting unnecessary branches to the next block. 2595 if (JT.MBB != NextBlock(SwitchBB)) 2596 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2597 DAG.getBasicBlock(JT.MBB))); 2598 else 2599 DAG.setRoot(CopyTo); 2600 } 2601 } 2602 2603 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2604 /// variable if there exists one. 2605 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2606 SDValue &Chain) { 2607 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2608 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2609 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2610 MachineFunction &MF = DAG.getMachineFunction(); 2611 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2612 MachineSDNode *Node = 2613 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2614 if (Global) { 2615 MachinePointerInfo MPInfo(Global); 2616 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2617 MachineMemOperand::MODereferenceable; 2618 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2619 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2620 DAG.setNodeMemRefs(Node, {MemRef}); 2621 } 2622 if (PtrTy != PtrMemTy) 2623 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2624 return SDValue(Node, 0); 2625 } 2626 2627 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2628 /// tail spliced into a stack protector check success bb. 2629 /// 2630 /// For a high level explanation of how this fits into the stack protector 2631 /// generation see the comment on the declaration of class 2632 /// StackProtectorDescriptor. 2633 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2634 MachineBasicBlock *ParentBB) { 2635 2636 // First create the loads to the guard/stack slot for the comparison. 2637 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2638 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2639 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2640 2641 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2642 int FI = MFI.getStackProtectorIndex(); 2643 2644 SDValue Guard; 2645 SDLoc dl = getCurSDLoc(); 2646 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2647 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2648 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2649 2650 // Generate code to load the content of the guard slot. 2651 SDValue GuardVal = DAG.getLoad( 2652 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2653 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2654 MachineMemOperand::MOVolatile); 2655 2656 if (TLI.useStackGuardXorFP()) 2657 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2658 2659 // Retrieve guard check function, nullptr if instrumentation is inlined. 2660 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2661 // The target provides a guard check function to validate the guard value. 2662 // Generate a call to that function with the content of the guard slot as 2663 // argument. 2664 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2665 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2666 2667 TargetLowering::ArgListTy Args; 2668 TargetLowering::ArgListEntry Entry; 2669 Entry.Node = GuardVal; 2670 Entry.Ty = FnTy->getParamType(0); 2671 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2672 Entry.IsInReg = true; 2673 Args.push_back(Entry); 2674 2675 TargetLowering::CallLoweringInfo CLI(DAG); 2676 CLI.setDebugLoc(getCurSDLoc()) 2677 .setChain(DAG.getEntryNode()) 2678 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2679 getValue(GuardCheckFn), std::move(Args)); 2680 2681 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2682 DAG.setRoot(Result.second); 2683 return; 2684 } 2685 2686 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2687 // Otherwise, emit a volatile load to retrieve the stack guard value. 2688 SDValue Chain = DAG.getEntryNode(); 2689 if (TLI.useLoadStackGuardNode()) { 2690 Guard = getLoadStackGuard(DAG, dl, Chain); 2691 } else { 2692 const Value *IRGuard = TLI.getSDagStackGuard(M); 2693 SDValue GuardPtr = getValue(IRGuard); 2694 2695 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2696 MachinePointerInfo(IRGuard, 0), Align, 2697 MachineMemOperand::MOVolatile); 2698 } 2699 2700 // Perform the comparison via a getsetcc. 2701 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2702 *DAG.getContext(), 2703 Guard.getValueType()), 2704 Guard, GuardVal, ISD::SETNE); 2705 2706 // If the guard/stackslot do not equal, branch to failure MBB. 2707 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2708 MVT::Other, GuardVal.getOperand(0), 2709 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2710 // Otherwise branch to success MBB. 2711 SDValue Br = DAG.getNode(ISD::BR, dl, 2712 MVT::Other, BrCond, 2713 DAG.getBasicBlock(SPD.getSuccessMBB())); 2714 2715 DAG.setRoot(Br); 2716 } 2717 2718 /// Codegen the failure basic block for a stack protector check. 2719 /// 2720 /// A failure stack protector machine basic block consists simply of a call to 2721 /// __stack_chk_fail(). 2722 /// 2723 /// For a high level explanation of how this fits into the stack protector 2724 /// generation see the comment on the declaration of class 2725 /// StackProtectorDescriptor. 2726 void 2727 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2728 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2729 TargetLowering::MakeLibCallOptions CallOptions; 2730 CallOptions.setDiscardResult(true); 2731 SDValue Chain = 2732 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2733 None, CallOptions, getCurSDLoc()).second; 2734 // On PS4, the "return address" must still be within the calling function, 2735 // even if it's at the very end, so emit an explicit TRAP here. 2736 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2737 if (TM.getTargetTriple().isPS4CPU()) 2738 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2739 // WebAssembly needs an unreachable instruction after a non-returning call, 2740 // because the function return type can be different from __stack_chk_fail's 2741 // return type (void). 2742 if (TM.getTargetTriple().isWasm()) 2743 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2744 2745 DAG.setRoot(Chain); 2746 } 2747 2748 /// visitBitTestHeader - This function emits necessary code to produce value 2749 /// suitable for "bit tests" 2750 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2751 MachineBasicBlock *SwitchBB) { 2752 SDLoc dl = getCurSDLoc(); 2753 2754 // Subtract the minimum value. 2755 SDValue SwitchOp = getValue(B.SValue); 2756 EVT VT = SwitchOp.getValueType(); 2757 SDValue RangeSub = 2758 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2759 2760 // Determine the type of the test operands. 2761 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2762 bool UsePtrType = false; 2763 if (!TLI.isTypeLegal(VT)) { 2764 UsePtrType = true; 2765 } else { 2766 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2767 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2768 // Switch table case range are encoded into series of masks. 2769 // Just use pointer type, it's guaranteed to fit. 2770 UsePtrType = true; 2771 break; 2772 } 2773 } 2774 SDValue Sub = RangeSub; 2775 if (UsePtrType) { 2776 VT = TLI.getPointerTy(DAG.getDataLayout()); 2777 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2778 } 2779 2780 B.RegVT = VT.getSimpleVT(); 2781 B.Reg = FuncInfo.CreateReg(B.RegVT); 2782 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2783 2784 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2785 2786 if (!B.OmitRangeCheck) 2787 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2788 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2789 SwitchBB->normalizeSuccProbs(); 2790 2791 SDValue Root = CopyTo; 2792 if (!B.OmitRangeCheck) { 2793 // Conditional branch to the default block. 2794 SDValue RangeCmp = DAG.getSetCC(dl, 2795 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2796 RangeSub.getValueType()), 2797 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2798 ISD::SETUGT); 2799 2800 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2801 DAG.getBasicBlock(B.Default)); 2802 } 2803 2804 // Avoid emitting unnecessary branches to the next block. 2805 if (MBB != NextBlock(SwitchBB)) 2806 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2807 2808 DAG.setRoot(Root); 2809 } 2810 2811 /// visitBitTestCase - this function produces one "bit test" 2812 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2813 MachineBasicBlock* NextMBB, 2814 BranchProbability BranchProbToNext, 2815 unsigned Reg, 2816 BitTestCase &B, 2817 MachineBasicBlock *SwitchBB) { 2818 SDLoc dl = getCurSDLoc(); 2819 MVT VT = BB.RegVT; 2820 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2821 SDValue Cmp; 2822 unsigned PopCount = countPopulation(B.Mask); 2823 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2824 if (PopCount == 1) { 2825 // Testing for a single bit; just compare the shift count with what it 2826 // would need to be to shift a 1 bit in that position. 2827 Cmp = DAG.getSetCC( 2828 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2829 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2830 ISD::SETEQ); 2831 } else if (PopCount == BB.Range) { 2832 // There is only one zero bit in the range, test for it directly. 2833 Cmp = DAG.getSetCC( 2834 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2835 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2836 ISD::SETNE); 2837 } else { 2838 // Make desired shift 2839 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2840 DAG.getConstant(1, dl, VT), ShiftOp); 2841 2842 // Emit bit tests and jumps 2843 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2844 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2845 Cmp = DAG.getSetCC( 2846 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2847 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2848 } 2849 2850 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2851 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2852 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2853 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2854 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2855 // one as they are relative probabilities (and thus work more like weights), 2856 // and hence we need to normalize them to let the sum of them become one. 2857 SwitchBB->normalizeSuccProbs(); 2858 2859 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2860 MVT::Other, getControlRoot(), 2861 Cmp, DAG.getBasicBlock(B.TargetBB)); 2862 2863 // Avoid emitting unnecessary branches to the next block. 2864 if (NextMBB != NextBlock(SwitchBB)) 2865 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2866 DAG.getBasicBlock(NextMBB)); 2867 2868 DAG.setRoot(BrAnd); 2869 } 2870 2871 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2872 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2873 2874 // Retrieve successors. Look through artificial IR level blocks like 2875 // catchswitch for successors. 2876 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2877 const BasicBlock *EHPadBB = I.getSuccessor(1); 2878 2879 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2880 // have to do anything here to lower funclet bundles. 2881 assert(!I.hasOperandBundlesOtherThan( 2882 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2883 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2884 LLVMContext::OB_cfguardtarget, 2885 LLVMContext::OB_clang_arc_attachedcall}) && 2886 "Cannot lower invokes with arbitrary operand bundles yet!"); 2887 2888 const Value *Callee(I.getCalledOperand()); 2889 const Function *Fn = dyn_cast<Function>(Callee); 2890 if (isa<InlineAsm>(Callee)) 2891 visitInlineAsm(I, EHPadBB); 2892 else if (Fn && Fn->isIntrinsic()) { 2893 switch (Fn->getIntrinsicID()) { 2894 default: 2895 llvm_unreachable("Cannot invoke this intrinsic"); 2896 case Intrinsic::donothing: 2897 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2898 case Intrinsic::seh_try_begin: 2899 case Intrinsic::seh_scope_begin: 2900 case Intrinsic::seh_try_end: 2901 case Intrinsic::seh_scope_end: 2902 break; 2903 case Intrinsic::experimental_patchpoint_void: 2904 case Intrinsic::experimental_patchpoint_i64: 2905 visitPatchpoint(I, EHPadBB); 2906 break; 2907 case Intrinsic::experimental_gc_statepoint: 2908 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2909 break; 2910 case Intrinsic::wasm_rethrow: { 2911 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2912 // special because it can be invoked, so we manually lower it to a DAG 2913 // node here. 2914 SmallVector<SDValue, 8> Ops; 2915 Ops.push_back(getRoot()); // inchain 2916 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2917 Ops.push_back( 2918 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2919 TLI.getPointerTy(DAG.getDataLayout()))); 2920 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2921 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2922 break; 2923 } 2924 } 2925 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2926 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2927 // Eventually we will support lowering the @llvm.experimental.deoptimize 2928 // intrinsic, and right now there are no plans to support other intrinsics 2929 // with deopt state. 2930 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2931 } else { 2932 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2933 } 2934 2935 // If the value of the invoke is used outside of its defining block, make it 2936 // available as a virtual register. 2937 // We already took care of the exported value for the statepoint instruction 2938 // during call to the LowerStatepoint. 2939 if (!isa<GCStatepointInst>(I)) { 2940 CopyToExportRegsIfNeeded(&I); 2941 } 2942 2943 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2944 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2945 BranchProbability EHPadBBProb = 2946 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2947 : BranchProbability::getZero(); 2948 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2949 2950 // Update successor info. 2951 addSuccessorWithProb(InvokeMBB, Return); 2952 for (auto &UnwindDest : UnwindDests) { 2953 UnwindDest.first->setIsEHPad(); 2954 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2955 } 2956 InvokeMBB->normalizeSuccProbs(); 2957 2958 // Drop into normal successor. 2959 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2960 DAG.getBasicBlock(Return))); 2961 } 2962 2963 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2964 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2965 2966 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2967 // have to do anything here to lower funclet bundles. 2968 assert(!I.hasOperandBundlesOtherThan( 2969 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2970 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2971 2972 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2973 visitInlineAsm(I); 2974 CopyToExportRegsIfNeeded(&I); 2975 2976 // Retrieve successors. 2977 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2978 2979 // Update successor info. 2980 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2981 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2982 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2983 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2984 Target->setIsInlineAsmBrIndirectTarget(); 2985 } 2986 CallBrMBB->normalizeSuccProbs(); 2987 2988 // Drop into default successor. 2989 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2990 MVT::Other, getControlRoot(), 2991 DAG.getBasicBlock(Return))); 2992 } 2993 2994 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2995 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2996 } 2997 2998 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2999 assert(FuncInfo.MBB->isEHPad() && 3000 "Call to landingpad not in landing pad!"); 3001 3002 // If there aren't registers to copy the values into (e.g., during SjLj 3003 // exceptions), then don't bother to create these DAG nodes. 3004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3005 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3006 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3007 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3008 return; 3009 3010 // If landingpad's return type is token type, we don't create DAG nodes 3011 // for its exception pointer and selector value. The extraction of exception 3012 // pointer or selector value from token type landingpads is not currently 3013 // supported. 3014 if (LP.getType()->isTokenTy()) 3015 return; 3016 3017 SmallVector<EVT, 2> ValueVTs; 3018 SDLoc dl = getCurSDLoc(); 3019 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3020 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3021 3022 // Get the two live-in registers as SDValues. The physregs have already been 3023 // copied into virtual registers. 3024 SDValue Ops[2]; 3025 if (FuncInfo.ExceptionPointerVirtReg) { 3026 Ops[0] = DAG.getZExtOrTrunc( 3027 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3028 FuncInfo.ExceptionPointerVirtReg, 3029 TLI.getPointerTy(DAG.getDataLayout())), 3030 dl, ValueVTs[0]); 3031 } else { 3032 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3033 } 3034 Ops[1] = DAG.getZExtOrTrunc( 3035 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3036 FuncInfo.ExceptionSelectorVirtReg, 3037 TLI.getPointerTy(DAG.getDataLayout())), 3038 dl, ValueVTs[1]); 3039 3040 // Merge into one. 3041 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3042 DAG.getVTList(ValueVTs), Ops); 3043 setValue(&LP, Res); 3044 } 3045 3046 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3047 MachineBasicBlock *Last) { 3048 // Update JTCases. 3049 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3050 if (SL->JTCases[i].first.HeaderBB == First) 3051 SL->JTCases[i].first.HeaderBB = Last; 3052 3053 // Update BitTestCases. 3054 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3055 if (SL->BitTestCases[i].Parent == First) 3056 SL->BitTestCases[i].Parent = Last; 3057 } 3058 3059 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3060 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3061 3062 // Update machine-CFG edges with unique successors. 3063 SmallSet<BasicBlock*, 32> Done; 3064 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3065 BasicBlock *BB = I.getSuccessor(i); 3066 bool Inserted = Done.insert(BB).second; 3067 if (!Inserted) 3068 continue; 3069 3070 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3071 addSuccessorWithProb(IndirectBrMBB, Succ); 3072 } 3073 IndirectBrMBB->normalizeSuccProbs(); 3074 3075 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3076 MVT::Other, getControlRoot(), 3077 getValue(I.getAddress()))); 3078 } 3079 3080 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3081 if (!DAG.getTarget().Options.TrapUnreachable) 3082 return; 3083 3084 // We may be able to ignore unreachable behind a noreturn call. 3085 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3086 const BasicBlock &BB = *I.getParent(); 3087 if (&I != &BB.front()) { 3088 BasicBlock::const_iterator PredI = 3089 std::prev(BasicBlock::const_iterator(&I)); 3090 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3091 if (Call->doesNotReturn()) 3092 return; 3093 } 3094 } 3095 } 3096 3097 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 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 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3118 Flags.copyFMF(*FPOp); 3119 3120 SDValue Op1 = getValue(I.getOperand(0)); 3121 SDValue Op2 = getValue(I.getOperand(1)); 3122 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3123 Op1, Op2, Flags); 3124 setValue(&I, BinNodeValue); 3125 } 3126 3127 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3128 SDValue Op1 = getValue(I.getOperand(0)); 3129 SDValue Op2 = getValue(I.getOperand(1)); 3130 3131 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3132 Op1.getValueType(), DAG.getDataLayout()); 3133 3134 // Coerce the shift amount to the right type if we can. 3135 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3136 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3137 unsigned Op2Size = Op2.getValueSizeInBits(); 3138 SDLoc DL = getCurSDLoc(); 3139 3140 // If the operand is smaller than the shift count type, promote it. 3141 if (ShiftSize > Op2Size) 3142 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3143 3144 // If the operand is larger than the shift count type but the shift 3145 // count type has enough bits to represent any shift value, truncate 3146 // it now. This is a common case and it exposes the truncate to 3147 // optimization early. 3148 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3149 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3150 // Otherwise we'll need to temporarily settle for some other convenient 3151 // type. Type legalization will make adjustments once the shiftee is split. 3152 else 3153 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3154 } 3155 3156 bool nuw = false; 3157 bool nsw = false; 3158 bool exact = false; 3159 3160 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3161 3162 if (const OverflowingBinaryOperator *OFBinOp = 3163 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3164 nuw = OFBinOp->hasNoUnsignedWrap(); 3165 nsw = OFBinOp->hasNoSignedWrap(); 3166 } 3167 if (const PossiblyExactOperator *ExactOp = 3168 dyn_cast<const PossiblyExactOperator>(&I)) 3169 exact = ExactOp->isExact(); 3170 } 3171 SDNodeFlags Flags; 3172 Flags.setExact(exact); 3173 Flags.setNoSignedWrap(nsw); 3174 Flags.setNoUnsignedWrap(nuw); 3175 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3176 Flags); 3177 setValue(&I, Res); 3178 } 3179 3180 void SelectionDAGBuilder::visitSDiv(const User &I) { 3181 SDValue Op1 = getValue(I.getOperand(0)); 3182 SDValue Op2 = getValue(I.getOperand(1)); 3183 3184 SDNodeFlags Flags; 3185 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3186 cast<PossiblyExactOperator>(&I)->isExact()); 3187 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3188 Op2, Flags)); 3189 } 3190 3191 void SelectionDAGBuilder::visitICmp(const User &I) { 3192 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3193 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3194 predicate = IC->getPredicate(); 3195 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3196 predicate = ICmpInst::Predicate(IC->getPredicate()); 3197 SDValue Op1 = getValue(I.getOperand(0)); 3198 SDValue Op2 = getValue(I.getOperand(1)); 3199 ISD::CondCode Opcode = getICmpCondCode(predicate); 3200 3201 auto &TLI = DAG.getTargetLoweringInfo(); 3202 EVT MemVT = 3203 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3204 3205 // If a pointer's DAG type is larger than its memory type then the DAG values 3206 // are zero-extended. This breaks signed comparisons so truncate back to the 3207 // underlying type before doing the compare. 3208 if (Op1.getValueType() != MemVT) { 3209 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3210 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3211 } 3212 3213 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3214 I.getType()); 3215 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3216 } 3217 3218 void SelectionDAGBuilder::visitFCmp(const User &I) { 3219 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3220 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3221 predicate = FC->getPredicate(); 3222 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3223 predicate = FCmpInst::Predicate(FC->getPredicate()); 3224 SDValue Op1 = getValue(I.getOperand(0)); 3225 SDValue Op2 = getValue(I.getOperand(1)); 3226 3227 ISD::CondCode Condition = getFCmpCondCode(predicate); 3228 auto *FPMO = cast<FPMathOperator>(&I); 3229 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3230 Condition = getFCmpCodeWithoutNaN(Condition); 3231 3232 SDNodeFlags Flags; 3233 Flags.copyFMF(*FPMO); 3234 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3235 3236 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3237 I.getType()); 3238 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3239 } 3240 3241 // Check if the condition of the select has one use or two users that are both 3242 // selects with the same condition. 3243 static bool hasOnlySelectUsers(const Value *Cond) { 3244 return llvm::all_of(Cond->users(), [](const Value *V) { 3245 return isa<SelectInst>(V); 3246 }); 3247 } 3248 3249 void SelectionDAGBuilder::visitSelect(const User &I) { 3250 SmallVector<EVT, 4> ValueVTs; 3251 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3252 ValueVTs); 3253 unsigned NumValues = ValueVTs.size(); 3254 if (NumValues == 0) return; 3255 3256 SmallVector<SDValue, 4> Values(NumValues); 3257 SDValue Cond = getValue(I.getOperand(0)); 3258 SDValue LHSVal = getValue(I.getOperand(1)); 3259 SDValue RHSVal = getValue(I.getOperand(2)); 3260 SmallVector<SDValue, 1> BaseOps(1, Cond); 3261 ISD::NodeType OpCode = 3262 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3263 3264 bool IsUnaryAbs = false; 3265 bool Negate = false; 3266 3267 SDNodeFlags Flags; 3268 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3269 Flags.copyFMF(*FPOp); 3270 3271 // Min/max matching is only viable if all output VTs are the same. 3272 if (is_splat(ValueVTs)) { 3273 EVT VT = ValueVTs[0]; 3274 LLVMContext &Ctx = *DAG.getContext(); 3275 auto &TLI = DAG.getTargetLoweringInfo(); 3276 3277 // We care about the legality of the operation after it has been type 3278 // legalized. 3279 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3280 VT = TLI.getTypeToTransformTo(Ctx, VT); 3281 3282 // If the vselect is legal, assume we want to leave this as a vector setcc + 3283 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3284 // min/max is legal on the scalar type. 3285 bool UseScalarMinMax = VT.isVector() && 3286 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3287 3288 Value *LHS, *RHS; 3289 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3290 ISD::NodeType Opc = ISD::DELETED_NODE; 3291 switch (SPR.Flavor) { 3292 case SPF_UMAX: Opc = ISD::UMAX; break; 3293 case SPF_UMIN: Opc = ISD::UMIN; break; 3294 case SPF_SMAX: Opc = ISD::SMAX; break; 3295 case SPF_SMIN: Opc = ISD::SMIN; break; 3296 case SPF_FMINNUM: 3297 switch (SPR.NaNBehavior) { 3298 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3299 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3300 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3301 case SPNB_RETURNS_ANY: { 3302 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3303 Opc = ISD::FMINNUM; 3304 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3305 Opc = ISD::FMINIMUM; 3306 else if (UseScalarMinMax) 3307 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3308 ISD::FMINNUM : ISD::FMINIMUM; 3309 break; 3310 } 3311 } 3312 break; 3313 case SPF_FMAXNUM: 3314 switch (SPR.NaNBehavior) { 3315 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3316 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3317 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3318 case SPNB_RETURNS_ANY: 3319 3320 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3321 Opc = ISD::FMAXNUM; 3322 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3323 Opc = ISD::FMAXIMUM; 3324 else if (UseScalarMinMax) 3325 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3326 ISD::FMAXNUM : ISD::FMAXIMUM; 3327 break; 3328 } 3329 break; 3330 case SPF_NABS: 3331 Negate = true; 3332 LLVM_FALLTHROUGH; 3333 case SPF_ABS: 3334 IsUnaryAbs = true; 3335 Opc = ISD::ABS; 3336 break; 3337 default: break; 3338 } 3339 3340 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3341 (TLI.isOperationLegalOrCustom(Opc, VT) || 3342 (UseScalarMinMax && 3343 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3344 // If the underlying comparison instruction is used by any other 3345 // instruction, the consumed instructions won't be destroyed, so it is 3346 // not profitable to convert to a min/max. 3347 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3348 OpCode = Opc; 3349 LHSVal = getValue(LHS); 3350 RHSVal = getValue(RHS); 3351 BaseOps.clear(); 3352 } 3353 3354 if (IsUnaryAbs) { 3355 OpCode = Opc; 3356 LHSVal = getValue(LHS); 3357 BaseOps.clear(); 3358 } 3359 } 3360 3361 if (IsUnaryAbs) { 3362 for (unsigned i = 0; i != NumValues; ++i) { 3363 SDLoc dl = getCurSDLoc(); 3364 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3365 Values[i] = 3366 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3367 if (Negate) 3368 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3369 Values[i]); 3370 } 3371 } else { 3372 for (unsigned i = 0; i != NumValues; ++i) { 3373 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3374 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3375 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3376 Values[i] = DAG.getNode( 3377 OpCode, getCurSDLoc(), 3378 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3379 } 3380 } 3381 3382 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3383 DAG.getVTList(ValueVTs), Values)); 3384 } 3385 3386 void SelectionDAGBuilder::visitTrunc(const User &I) { 3387 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3388 SDValue N = getValue(I.getOperand(0)); 3389 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3390 I.getType()); 3391 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3392 } 3393 3394 void SelectionDAGBuilder::visitZExt(const User &I) { 3395 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3396 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3397 SDValue N = getValue(I.getOperand(0)); 3398 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3399 I.getType()); 3400 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3401 } 3402 3403 void SelectionDAGBuilder::visitSExt(const User &I) { 3404 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3405 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3406 SDValue N = getValue(I.getOperand(0)); 3407 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3408 I.getType()); 3409 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3410 } 3411 3412 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3413 // FPTrunc is never a no-op cast, no need to check 3414 SDValue N = getValue(I.getOperand(0)); 3415 SDLoc dl = getCurSDLoc(); 3416 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3417 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3418 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3419 DAG.getTargetConstant( 3420 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3421 } 3422 3423 void SelectionDAGBuilder::visitFPExt(const User &I) { 3424 // FPExt is never a no-op cast, no need to check 3425 SDValue N = getValue(I.getOperand(0)); 3426 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3427 I.getType()); 3428 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3429 } 3430 3431 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3432 // FPToUI is never a no-op cast, no need to check 3433 SDValue N = getValue(I.getOperand(0)); 3434 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3435 I.getType()); 3436 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3437 } 3438 3439 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3440 // FPToSI is never a no-op cast, no need to check 3441 SDValue N = getValue(I.getOperand(0)); 3442 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3443 I.getType()); 3444 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3445 } 3446 3447 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3448 // UIToFP is never a no-op cast, no need to check 3449 SDValue N = getValue(I.getOperand(0)); 3450 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3451 I.getType()); 3452 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3453 } 3454 3455 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3456 // SIToFP is never a no-op cast, no need to check 3457 SDValue N = getValue(I.getOperand(0)); 3458 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3459 I.getType()); 3460 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3461 } 3462 3463 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3464 // What to do depends on the size of the integer and the size of the pointer. 3465 // We can either truncate, zero extend, or no-op, accordingly. 3466 SDValue N = getValue(I.getOperand(0)); 3467 auto &TLI = DAG.getTargetLoweringInfo(); 3468 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3469 I.getType()); 3470 EVT PtrMemVT = 3471 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3472 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3473 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3474 setValue(&I, N); 3475 } 3476 3477 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3478 // What to do depends on the size of the integer and the size of the pointer. 3479 // We can either truncate, zero extend, or no-op, accordingly. 3480 SDValue N = getValue(I.getOperand(0)); 3481 auto &TLI = DAG.getTargetLoweringInfo(); 3482 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3483 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3484 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3485 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3486 setValue(&I, N); 3487 } 3488 3489 void SelectionDAGBuilder::visitBitCast(const User &I) { 3490 SDValue N = getValue(I.getOperand(0)); 3491 SDLoc dl = getCurSDLoc(); 3492 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3493 I.getType()); 3494 3495 // BitCast assures us that source and destination are the same size so this is 3496 // either a BITCAST or a no-op. 3497 if (DestVT != N.getValueType()) 3498 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3499 DestVT, N)); // convert types. 3500 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3501 // might fold any kind of constant expression to an integer constant and that 3502 // is not what we are looking for. Only recognize a bitcast of a genuine 3503 // constant integer as an opaque constant. 3504 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3505 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3506 /*isOpaque*/true)); 3507 else 3508 setValue(&I, N); // noop cast. 3509 } 3510 3511 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3513 const Value *SV = I.getOperand(0); 3514 SDValue N = getValue(SV); 3515 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3516 3517 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3518 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3519 3520 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3521 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3522 3523 setValue(&I, N); 3524 } 3525 3526 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3527 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3528 SDValue InVec = getValue(I.getOperand(0)); 3529 SDValue InVal = getValue(I.getOperand(1)); 3530 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3531 TLI.getVectorIdxTy(DAG.getDataLayout())); 3532 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3533 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3534 InVec, InVal, InIdx)); 3535 } 3536 3537 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3538 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3539 SDValue InVec = getValue(I.getOperand(0)); 3540 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3541 TLI.getVectorIdxTy(DAG.getDataLayout())); 3542 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3543 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3544 InVec, InIdx)); 3545 } 3546 3547 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3548 SDValue Src1 = getValue(I.getOperand(0)); 3549 SDValue Src2 = getValue(I.getOperand(1)); 3550 ArrayRef<int> Mask; 3551 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3552 Mask = SVI->getShuffleMask(); 3553 else 3554 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3555 SDLoc DL = getCurSDLoc(); 3556 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3557 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3558 EVT SrcVT = Src1.getValueType(); 3559 3560 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3561 VT.isScalableVector()) { 3562 // Canonical splat form of first element of first input vector. 3563 SDValue FirstElt = 3564 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3565 DAG.getVectorIdxConstant(0, DL)); 3566 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3567 return; 3568 } 3569 3570 // For now, we only handle splats for scalable vectors. 3571 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3572 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3573 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3574 3575 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3576 unsigned MaskNumElts = Mask.size(); 3577 3578 if (SrcNumElts == MaskNumElts) { 3579 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3580 return; 3581 } 3582 3583 // Normalize the shuffle vector since mask and vector length don't match. 3584 if (SrcNumElts < MaskNumElts) { 3585 // Mask is longer than the source vectors. We can use concatenate vector to 3586 // make the mask and vectors lengths match. 3587 3588 if (MaskNumElts % SrcNumElts == 0) { 3589 // Mask length is a multiple of the source vector length. 3590 // Check if the shuffle is some kind of concatenation of the input 3591 // vectors. 3592 unsigned NumConcat = MaskNumElts / SrcNumElts; 3593 bool IsConcat = true; 3594 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3595 for (unsigned i = 0; i != MaskNumElts; ++i) { 3596 int Idx = Mask[i]; 3597 if (Idx < 0) 3598 continue; 3599 // Ensure the indices in each SrcVT sized piece are sequential and that 3600 // the same source is used for the whole piece. 3601 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3602 (ConcatSrcs[i / SrcNumElts] >= 0 && 3603 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3604 IsConcat = false; 3605 break; 3606 } 3607 // Remember which source this index came from. 3608 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3609 } 3610 3611 // The shuffle is concatenating multiple vectors together. Just emit 3612 // a CONCAT_VECTORS operation. 3613 if (IsConcat) { 3614 SmallVector<SDValue, 8> ConcatOps; 3615 for (auto Src : ConcatSrcs) { 3616 if (Src < 0) 3617 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3618 else if (Src == 0) 3619 ConcatOps.push_back(Src1); 3620 else 3621 ConcatOps.push_back(Src2); 3622 } 3623 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3624 return; 3625 } 3626 } 3627 3628 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3629 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3630 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3631 PaddedMaskNumElts); 3632 3633 // Pad both vectors with undefs to make them the same length as the mask. 3634 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3635 3636 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3637 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3638 MOps1[0] = Src1; 3639 MOps2[0] = Src2; 3640 3641 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3642 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3643 3644 // Readjust mask for new input vector length. 3645 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3646 for (unsigned i = 0; i != MaskNumElts; ++i) { 3647 int Idx = Mask[i]; 3648 if (Idx >= (int)SrcNumElts) 3649 Idx -= SrcNumElts - PaddedMaskNumElts; 3650 MappedOps[i] = Idx; 3651 } 3652 3653 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3654 3655 // If the concatenated vector was padded, extract a subvector with the 3656 // correct number of elements. 3657 if (MaskNumElts != PaddedMaskNumElts) 3658 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3659 DAG.getVectorIdxConstant(0, DL)); 3660 3661 setValue(&I, Result); 3662 return; 3663 } 3664 3665 if (SrcNumElts > MaskNumElts) { 3666 // Analyze the access pattern of the vector to see if we can extract 3667 // two subvectors and do the shuffle. 3668 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3669 bool CanExtract = true; 3670 for (int Idx : Mask) { 3671 unsigned Input = 0; 3672 if (Idx < 0) 3673 continue; 3674 3675 if (Idx >= (int)SrcNumElts) { 3676 Input = 1; 3677 Idx -= SrcNumElts; 3678 } 3679 3680 // If all the indices come from the same MaskNumElts sized portion of 3681 // the sources we can use extract. Also make sure the extract wouldn't 3682 // extract past the end of the source. 3683 int NewStartIdx = alignDown(Idx, MaskNumElts); 3684 if (NewStartIdx + MaskNumElts > SrcNumElts || 3685 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3686 CanExtract = false; 3687 // Make sure we always update StartIdx as we use it to track if all 3688 // elements are undef. 3689 StartIdx[Input] = NewStartIdx; 3690 } 3691 3692 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3693 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3694 return; 3695 } 3696 if (CanExtract) { 3697 // Extract appropriate subvector and generate a vector shuffle 3698 for (unsigned Input = 0; Input < 2; ++Input) { 3699 SDValue &Src = Input == 0 ? Src1 : Src2; 3700 if (StartIdx[Input] < 0) 3701 Src = DAG.getUNDEF(VT); 3702 else { 3703 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3704 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3705 } 3706 } 3707 3708 // Calculate new mask. 3709 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3710 for (int &Idx : MappedOps) { 3711 if (Idx >= (int)SrcNumElts) 3712 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3713 else if (Idx >= 0) 3714 Idx -= StartIdx[0]; 3715 } 3716 3717 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3718 return; 3719 } 3720 } 3721 3722 // We can't use either concat vectors or extract subvectors so fall back to 3723 // replacing the shuffle with extract and build vector. 3724 // to insert and build vector. 3725 EVT EltVT = VT.getVectorElementType(); 3726 SmallVector<SDValue,8> Ops; 3727 for (int Idx : Mask) { 3728 SDValue Res; 3729 3730 if (Idx < 0) { 3731 Res = DAG.getUNDEF(EltVT); 3732 } else { 3733 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3734 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3735 3736 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3737 DAG.getVectorIdxConstant(Idx, DL)); 3738 } 3739 3740 Ops.push_back(Res); 3741 } 3742 3743 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3744 } 3745 3746 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3747 ArrayRef<unsigned> Indices; 3748 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3749 Indices = IV->getIndices(); 3750 else 3751 Indices = cast<ConstantExpr>(&I)->getIndices(); 3752 3753 const Value *Op0 = I.getOperand(0); 3754 const Value *Op1 = I.getOperand(1); 3755 Type *AggTy = I.getType(); 3756 Type *ValTy = Op1->getType(); 3757 bool IntoUndef = isa<UndefValue>(Op0); 3758 bool FromUndef = isa<UndefValue>(Op1); 3759 3760 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3761 3762 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3763 SmallVector<EVT, 4> AggValueVTs; 3764 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3765 SmallVector<EVT, 4> ValValueVTs; 3766 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3767 3768 unsigned NumAggValues = AggValueVTs.size(); 3769 unsigned NumValValues = ValValueVTs.size(); 3770 SmallVector<SDValue, 4> Values(NumAggValues); 3771 3772 // Ignore an insertvalue that produces an empty object 3773 if (!NumAggValues) { 3774 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3775 return; 3776 } 3777 3778 SDValue Agg = getValue(Op0); 3779 unsigned i = 0; 3780 // Copy the beginning value(s) from the original aggregate. 3781 for (; i != LinearIndex; ++i) 3782 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3783 SDValue(Agg.getNode(), Agg.getResNo() + i); 3784 // Copy values from the inserted value(s). 3785 if (NumValValues) { 3786 SDValue Val = getValue(Op1); 3787 for (; i != LinearIndex + NumValValues; ++i) 3788 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3789 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3790 } 3791 // Copy remaining value(s) from the original aggregate. 3792 for (; i != NumAggValues; ++i) 3793 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3794 SDValue(Agg.getNode(), Agg.getResNo() + i); 3795 3796 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3797 DAG.getVTList(AggValueVTs), Values)); 3798 } 3799 3800 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3801 ArrayRef<unsigned> Indices; 3802 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3803 Indices = EV->getIndices(); 3804 else 3805 Indices = cast<ConstantExpr>(&I)->getIndices(); 3806 3807 const Value *Op0 = I.getOperand(0); 3808 Type *AggTy = Op0->getType(); 3809 Type *ValTy = I.getType(); 3810 bool OutOfUndef = isa<UndefValue>(Op0); 3811 3812 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3813 3814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3815 SmallVector<EVT, 4> ValValueVTs; 3816 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3817 3818 unsigned NumValValues = ValValueVTs.size(); 3819 3820 // Ignore a extractvalue that produces an empty object 3821 if (!NumValValues) { 3822 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3823 return; 3824 } 3825 3826 SmallVector<SDValue, 4> Values(NumValValues); 3827 3828 SDValue Agg = getValue(Op0); 3829 // Copy out the selected value(s). 3830 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3831 Values[i - LinearIndex] = 3832 OutOfUndef ? 3833 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3834 SDValue(Agg.getNode(), Agg.getResNo() + i); 3835 3836 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3837 DAG.getVTList(ValValueVTs), Values)); 3838 } 3839 3840 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3841 Value *Op0 = I.getOperand(0); 3842 // Note that the pointer operand may be a vector of pointers. Take the scalar 3843 // element which holds a pointer. 3844 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3845 SDValue N = getValue(Op0); 3846 SDLoc dl = getCurSDLoc(); 3847 auto &TLI = DAG.getTargetLoweringInfo(); 3848 3849 // Normalize Vector GEP - all scalar operands should be converted to the 3850 // splat vector. 3851 bool IsVectorGEP = I.getType()->isVectorTy(); 3852 ElementCount VectorElementCount = 3853 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3854 : ElementCount::getFixed(0); 3855 3856 if (IsVectorGEP && !N.getValueType().isVector()) { 3857 LLVMContext &Context = *DAG.getContext(); 3858 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3859 if (VectorElementCount.isScalable()) 3860 N = DAG.getSplatVector(VT, dl, N); 3861 else 3862 N = DAG.getSplatBuildVector(VT, dl, N); 3863 } 3864 3865 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3866 GTI != E; ++GTI) { 3867 const Value *Idx = GTI.getOperand(); 3868 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3869 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3870 if (Field) { 3871 // N = N + Offset 3872 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3873 3874 // In an inbounds GEP with an offset that is nonnegative even when 3875 // interpreted as signed, assume there is no unsigned overflow. 3876 SDNodeFlags Flags; 3877 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3878 Flags.setNoUnsignedWrap(true); 3879 3880 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3881 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3882 } 3883 } else { 3884 // IdxSize is the width of the arithmetic according to IR semantics. 3885 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3886 // (and fix up the result later). 3887 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3888 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3889 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3890 // We intentionally mask away the high bits here; ElementSize may not 3891 // fit in IdxTy. 3892 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3893 bool ElementScalable = ElementSize.isScalable(); 3894 3895 // If this is a scalar constant or a splat vector of constants, 3896 // handle it quickly. 3897 const auto *C = dyn_cast<Constant>(Idx); 3898 if (C && isa<VectorType>(C->getType())) 3899 C = C->getSplatValue(); 3900 3901 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3902 if (CI && CI->isZero()) 3903 continue; 3904 if (CI && !ElementScalable) { 3905 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3906 LLVMContext &Context = *DAG.getContext(); 3907 SDValue OffsVal; 3908 if (IsVectorGEP) 3909 OffsVal = DAG.getConstant( 3910 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3911 else 3912 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3913 3914 // In an inbounds GEP with an offset that is nonnegative even when 3915 // interpreted as signed, assume there is no unsigned overflow. 3916 SDNodeFlags Flags; 3917 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3918 Flags.setNoUnsignedWrap(true); 3919 3920 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3921 3922 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3923 continue; 3924 } 3925 3926 // N = N + Idx * ElementMul; 3927 SDValue IdxN = getValue(Idx); 3928 3929 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3930 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3931 VectorElementCount); 3932 if (VectorElementCount.isScalable()) 3933 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3934 else 3935 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3936 } 3937 3938 // If the index is smaller or larger than intptr_t, truncate or extend 3939 // it. 3940 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3941 3942 if (ElementScalable) { 3943 EVT VScaleTy = N.getValueType().getScalarType(); 3944 SDValue VScale = DAG.getNode( 3945 ISD::VSCALE, dl, VScaleTy, 3946 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3947 if (IsVectorGEP) 3948 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3949 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3950 } else { 3951 // If this is a multiply by a power of two, turn it into a shl 3952 // immediately. This is a very common case. 3953 if (ElementMul != 1) { 3954 if (ElementMul.isPowerOf2()) { 3955 unsigned Amt = ElementMul.logBase2(); 3956 IdxN = DAG.getNode(ISD::SHL, dl, 3957 N.getValueType(), IdxN, 3958 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3959 } else { 3960 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3961 IdxN.getValueType()); 3962 IdxN = DAG.getNode(ISD::MUL, dl, 3963 N.getValueType(), IdxN, Scale); 3964 } 3965 } 3966 } 3967 3968 N = DAG.getNode(ISD::ADD, dl, 3969 N.getValueType(), N, IdxN); 3970 } 3971 } 3972 3973 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3974 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3975 if (IsVectorGEP) { 3976 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3977 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3978 } 3979 3980 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3981 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3982 3983 setValue(&I, N); 3984 } 3985 3986 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3987 // If this is a fixed sized alloca in the entry block of the function, 3988 // allocate it statically on the stack. 3989 if (FuncInfo.StaticAllocaMap.count(&I)) 3990 return; // getValue will auto-populate this. 3991 3992 SDLoc dl = getCurSDLoc(); 3993 Type *Ty = I.getAllocatedType(); 3994 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3995 auto &DL = DAG.getDataLayout(); 3996 uint64_t TySize = DL.getTypeAllocSize(Ty); 3997 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3998 3999 SDValue AllocSize = getValue(I.getArraySize()); 4000 4001 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4002 if (AllocSize.getValueType() != IntPtr) 4003 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4004 4005 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 4006 AllocSize, 4007 DAG.getConstant(TySize, dl, IntPtr)); 4008 4009 // Handle alignment. If the requested alignment is less than or equal to 4010 // the stack alignment, ignore it. If the size is greater than or equal to 4011 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4012 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4013 if (*Alignment <= StackAlign) 4014 Alignment = None; 4015 4016 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4017 // Round the size of the allocation up to the stack alignment size 4018 // by add SA-1 to the size. This doesn't overflow because we're computing 4019 // an address inside an alloca. 4020 SDNodeFlags Flags; 4021 Flags.setNoUnsignedWrap(true); 4022 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4023 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4024 4025 // Mask out the low bits for alignment purposes. 4026 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4027 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4028 4029 SDValue Ops[] = { 4030 getRoot(), AllocSize, 4031 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4032 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4033 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4034 setValue(&I, DSA); 4035 DAG.setRoot(DSA.getValue(1)); 4036 4037 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4038 } 4039 4040 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4041 if (I.isAtomic()) 4042 return visitAtomicLoad(I); 4043 4044 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4045 const Value *SV = I.getOperand(0); 4046 if (TLI.supportSwiftError()) { 4047 // Swifterror values can come from either a function parameter with 4048 // swifterror attribute or an alloca with swifterror attribute. 4049 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4050 if (Arg->hasSwiftErrorAttr()) 4051 return visitLoadFromSwiftError(I); 4052 } 4053 4054 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4055 if (Alloca->isSwiftError()) 4056 return visitLoadFromSwiftError(I); 4057 } 4058 } 4059 4060 SDValue Ptr = getValue(SV); 4061 4062 Type *Ty = I.getType(); 4063 Align Alignment = I.getAlign(); 4064 4065 AAMDNodes AAInfo; 4066 I.getAAMetadata(AAInfo); 4067 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4068 4069 SmallVector<EVT, 4> ValueVTs, MemVTs; 4070 SmallVector<uint64_t, 4> Offsets; 4071 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4072 unsigned NumValues = ValueVTs.size(); 4073 if (NumValues == 0) 4074 return; 4075 4076 bool isVolatile = I.isVolatile(); 4077 4078 SDValue Root; 4079 bool ConstantMemory = false; 4080 if (isVolatile) 4081 // Serialize volatile loads with other side effects. 4082 Root = getRoot(); 4083 else if (NumValues > MaxParallelChains) 4084 Root = getMemoryRoot(); 4085 else if (AA && 4086 AA->pointsToConstantMemory(MemoryLocation( 4087 SV, 4088 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4089 AAInfo))) { 4090 // Do not serialize (non-volatile) loads of constant memory with anything. 4091 Root = DAG.getEntryNode(); 4092 ConstantMemory = true; 4093 } else { 4094 // Do not serialize non-volatile loads against each other. 4095 Root = DAG.getRoot(); 4096 } 4097 4098 SDLoc dl = getCurSDLoc(); 4099 4100 if (isVolatile) 4101 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4102 4103 // An aggregate load cannot wrap around the address space, so offsets to its 4104 // parts don't wrap either. 4105 SDNodeFlags Flags; 4106 Flags.setNoUnsignedWrap(true); 4107 4108 SmallVector<SDValue, 4> Values(NumValues); 4109 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4110 EVT PtrVT = Ptr.getValueType(); 4111 4112 MachineMemOperand::Flags MMOFlags 4113 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4114 4115 unsigned ChainI = 0; 4116 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4117 // Serializing loads here may result in excessive register pressure, and 4118 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4119 // could recover a bit by hoisting nodes upward in the chain by recognizing 4120 // they are side-effect free or do not alias. The optimizer should really 4121 // avoid this case by converting large object/array copies to llvm.memcpy 4122 // (MaxParallelChains should always remain as failsafe). 4123 if (ChainI == MaxParallelChains) { 4124 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4125 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4126 makeArrayRef(Chains.data(), ChainI)); 4127 Root = Chain; 4128 ChainI = 0; 4129 } 4130 SDValue A = DAG.getNode(ISD::ADD, dl, 4131 PtrVT, Ptr, 4132 DAG.getConstant(Offsets[i], dl, PtrVT), 4133 Flags); 4134 4135 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4136 MachinePointerInfo(SV, Offsets[i]), Alignment, 4137 MMOFlags, AAInfo, Ranges); 4138 Chains[ChainI] = L.getValue(1); 4139 4140 if (MemVTs[i] != ValueVTs[i]) 4141 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4142 4143 Values[i] = L; 4144 } 4145 4146 if (!ConstantMemory) { 4147 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4148 makeArrayRef(Chains.data(), ChainI)); 4149 if (isVolatile) 4150 DAG.setRoot(Chain); 4151 else 4152 PendingLoads.push_back(Chain); 4153 } 4154 4155 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4156 DAG.getVTList(ValueVTs), Values)); 4157 } 4158 4159 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4160 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4161 "call visitStoreToSwiftError when backend supports swifterror"); 4162 4163 SmallVector<EVT, 4> ValueVTs; 4164 SmallVector<uint64_t, 4> Offsets; 4165 const Value *SrcV = I.getOperand(0); 4166 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4167 SrcV->getType(), ValueVTs, &Offsets); 4168 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4169 "expect a single EVT for swifterror"); 4170 4171 SDValue Src = getValue(SrcV); 4172 // Create a virtual register, then update the virtual register. 4173 Register VReg = 4174 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4175 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4176 // Chain can be getRoot or getControlRoot. 4177 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4178 SDValue(Src.getNode(), Src.getResNo())); 4179 DAG.setRoot(CopyNode); 4180 } 4181 4182 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4183 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4184 "call visitLoadFromSwiftError when backend supports swifterror"); 4185 4186 assert(!I.isVolatile() && 4187 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4188 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4189 "Support volatile, non temporal, invariant for load_from_swift_error"); 4190 4191 const Value *SV = I.getOperand(0); 4192 Type *Ty = I.getType(); 4193 AAMDNodes AAInfo; 4194 I.getAAMetadata(AAInfo); 4195 assert( 4196 (!AA || 4197 !AA->pointsToConstantMemory(MemoryLocation( 4198 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4199 AAInfo))) && 4200 "load_from_swift_error should not be constant memory"); 4201 4202 SmallVector<EVT, 4> ValueVTs; 4203 SmallVector<uint64_t, 4> Offsets; 4204 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4205 ValueVTs, &Offsets); 4206 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4207 "expect a single EVT for swifterror"); 4208 4209 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4210 SDValue L = DAG.getCopyFromReg( 4211 getRoot(), getCurSDLoc(), 4212 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4213 4214 setValue(&I, L); 4215 } 4216 4217 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4218 if (I.isAtomic()) 4219 return visitAtomicStore(I); 4220 4221 const Value *SrcV = I.getOperand(0); 4222 const Value *PtrV = I.getOperand(1); 4223 4224 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4225 if (TLI.supportSwiftError()) { 4226 // Swifterror values can come from either a function parameter with 4227 // swifterror attribute or an alloca with swifterror attribute. 4228 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4229 if (Arg->hasSwiftErrorAttr()) 4230 return visitStoreToSwiftError(I); 4231 } 4232 4233 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4234 if (Alloca->isSwiftError()) 4235 return visitStoreToSwiftError(I); 4236 } 4237 } 4238 4239 SmallVector<EVT, 4> ValueVTs, MemVTs; 4240 SmallVector<uint64_t, 4> Offsets; 4241 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4242 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4243 unsigned NumValues = ValueVTs.size(); 4244 if (NumValues == 0) 4245 return; 4246 4247 // Get the lowered operands. Note that we do this after 4248 // checking if NumResults is zero, because with zero results 4249 // the operands won't have values in the map. 4250 SDValue Src = getValue(SrcV); 4251 SDValue Ptr = getValue(PtrV); 4252 4253 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4254 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4255 SDLoc dl = getCurSDLoc(); 4256 Align Alignment = I.getAlign(); 4257 AAMDNodes AAInfo; 4258 I.getAAMetadata(AAInfo); 4259 4260 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4261 4262 // An aggregate load cannot wrap around the address space, so offsets to its 4263 // parts don't wrap either. 4264 SDNodeFlags Flags; 4265 Flags.setNoUnsignedWrap(true); 4266 4267 unsigned ChainI = 0; 4268 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4269 // See visitLoad comments. 4270 if (ChainI == MaxParallelChains) { 4271 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4272 makeArrayRef(Chains.data(), ChainI)); 4273 Root = Chain; 4274 ChainI = 0; 4275 } 4276 SDValue Add = 4277 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4278 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4279 if (MemVTs[i] != ValueVTs[i]) 4280 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4281 SDValue St = 4282 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4283 Alignment, MMOFlags, AAInfo); 4284 Chains[ChainI] = St; 4285 } 4286 4287 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4288 makeArrayRef(Chains.data(), ChainI)); 4289 DAG.setRoot(StoreNode); 4290 } 4291 4292 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4293 bool IsCompressing) { 4294 SDLoc sdl = getCurSDLoc(); 4295 4296 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4297 MaybeAlign &Alignment) { 4298 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4299 Src0 = I.getArgOperand(0); 4300 Ptr = I.getArgOperand(1); 4301 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4302 Mask = I.getArgOperand(3); 4303 }; 4304 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4305 MaybeAlign &Alignment) { 4306 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4307 Src0 = I.getArgOperand(0); 4308 Ptr = I.getArgOperand(1); 4309 Mask = I.getArgOperand(2); 4310 Alignment = None; 4311 }; 4312 4313 Value *PtrOperand, *MaskOperand, *Src0Operand; 4314 MaybeAlign Alignment; 4315 if (IsCompressing) 4316 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4317 else 4318 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4319 4320 SDValue Ptr = getValue(PtrOperand); 4321 SDValue Src0 = getValue(Src0Operand); 4322 SDValue Mask = getValue(MaskOperand); 4323 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4324 4325 EVT VT = Src0.getValueType(); 4326 if (!Alignment) 4327 Alignment = DAG.getEVTAlign(VT); 4328 4329 AAMDNodes AAInfo; 4330 I.getAAMetadata(AAInfo); 4331 4332 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4333 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4334 // TODO: Make MachineMemOperands aware of scalable 4335 // vectors. 4336 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4337 SDValue StoreNode = 4338 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4339 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4340 DAG.setRoot(StoreNode); 4341 setValue(&I, StoreNode); 4342 } 4343 4344 // Get a uniform base for the Gather/Scatter intrinsic. 4345 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4346 // We try to represent it as a base pointer + vector of indices. 4347 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4348 // The first operand of the GEP may be a single pointer or a vector of pointers 4349 // Example: 4350 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4351 // or 4352 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4353 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4354 // 4355 // When the first GEP operand is a single pointer - it is the uniform base we 4356 // are looking for. If first operand of the GEP is a splat vector - we 4357 // extract the splat value and use it as a uniform base. 4358 // In all other cases the function returns 'false'. 4359 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4360 ISD::MemIndexType &IndexType, SDValue &Scale, 4361 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4362 SelectionDAG& DAG = SDB->DAG; 4363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4364 const DataLayout &DL = DAG.getDataLayout(); 4365 4366 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4367 4368 // Handle splat constant pointer. 4369 if (auto *C = dyn_cast<Constant>(Ptr)) { 4370 C = C->getSplatValue(); 4371 if (!C) 4372 return false; 4373 4374 Base = SDB->getValue(C); 4375 4376 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4377 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4378 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4379 IndexType = ISD::SIGNED_SCALED; 4380 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4381 return true; 4382 } 4383 4384 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4385 if (!GEP || GEP->getParent() != CurBB) 4386 return false; 4387 4388 if (GEP->getNumOperands() != 2) 4389 return false; 4390 4391 const Value *BasePtr = GEP->getPointerOperand(); 4392 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4393 4394 // Make sure the base is scalar and the index is a vector. 4395 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4396 return false; 4397 4398 Base = SDB->getValue(BasePtr); 4399 Index = SDB->getValue(IndexVal); 4400 IndexType = ISD::SIGNED_SCALED; 4401 Scale = DAG.getTargetConstant( 4402 DL.getTypeAllocSize(GEP->getResultElementType()), 4403 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4404 return true; 4405 } 4406 4407 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4408 SDLoc sdl = getCurSDLoc(); 4409 4410 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4411 const Value *Ptr = I.getArgOperand(1); 4412 SDValue Src0 = getValue(I.getArgOperand(0)); 4413 SDValue Mask = getValue(I.getArgOperand(3)); 4414 EVT VT = Src0.getValueType(); 4415 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4416 ->getMaybeAlignValue() 4417 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4418 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4419 4420 AAMDNodes AAInfo; 4421 I.getAAMetadata(AAInfo); 4422 4423 SDValue Base; 4424 SDValue Index; 4425 ISD::MemIndexType IndexType; 4426 SDValue Scale; 4427 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4428 I.getParent()); 4429 4430 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4431 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4432 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4433 // TODO: Make MachineMemOperands aware of scalable 4434 // vectors. 4435 MemoryLocation::UnknownSize, Alignment, AAInfo); 4436 if (!UniformBase) { 4437 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4438 Index = getValue(Ptr); 4439 IndexType = ISD::SIGNED_UNSCALED; 4440 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4441 } 4442 4443 EVT IdxVT = Index.getValueType(); 4444 EVT EltTy = IdxVT.getVectorElementType(); 4445 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4446 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4447 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4448 } 4449 4450 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4451 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4452 Ops, MMO, IndexType, false); 4453 DAG.setRoot(Scatter); 4454 setValue(&I, Scatter); 4455 } 4456 4457 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4458 SDLoc sdl = getCurSDLoc(); 4459 4460 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4461 MaybeAlign &Alignment) { 4462 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4463 Ptr = I.getArgOperand(0); 4464 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4465 Mask = I.getArgOperand(2); 4466 Src0 = I.getArgOperand(3); 4467 }; 4468 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4469 MaybeAlign &Alignment) { 4470 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4471 Ptr = I.getArgOperand(0); 4472 Alignment = None; 4473 Mask = I.getArgOperand(1); 4474 Src0 = I.getArgOperand(2); 4475 }; 4476 4477 Value *PtrOperand, *MaskOperand, *Src0Operand; 4478 MaybeAlign Alignment; 4479 if (IsExpanding) 4480 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4481 else 4482 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4483 4484 SDValue Ptr = getValue(PtrOperand); 4485 SDValue Src0 = getValue(Src0Operand); 4486 SDValue Mask = getValue(MaskOperand); 4487 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4488 4489 EVT VT = Src0.getValueType(); 4490 if (!Alignment) 4491 Alignment = DAG.getEVTAlign(VT); 4492 4493 AAMDNodes AAInfo; 4494 I.getAAMetadata(AAInfo); 4495 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4496 4497 // Do not serialize masked loads of constant memory with anything. 4498 MemoryLocation ML; 4499 if (VT.isScalableVector()) 4500 ML = MemoryLocation::getAfter(PtrOperand); 4501 else 4502 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4503 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4504 AAInfo); 4505 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4506 4507 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4508 4509 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4510 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4511 // TODO: Make MachineMemOperands aware of scalable 4512 // vectors. 4513 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4514 4515 SDValue Load = 4516 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4517 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4518 if (AddToChain) 4519 PendingLoads.push_back(Load.getValue(1)); 4520 setValue(&I, Load); 4521 } 4522 4523 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4524 SDLoc sdl = getCurSDLoc(); 4525 4526 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4527 const Value *Ptr = I.getArgOperand(0); 4528 SDValue Src0 = getValue(I.getArgOperand(3)); 4529 SDValue Mask = getValue(I.getArgOperand(2)); 4530 4531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4532 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4533 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4534 ->getMaybeAlignValue() 4535 .getValueOr(DAG.getEVTAlign(VT.getScalarType())); 4536 4537 AAMDNodes AAInfo; 4538 I.getAAMetadata(AAInfo); 4539 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4540 4541 SDValue Root = DAG.getRoot(); 4542 SDValue Base; 4543 SDValue Index; 4544 ISD::MemIndexType IndexType; 4545 SDValue Scale; 4546 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4547 I.getParent()); 4548 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4549 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4550 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4551 // TODO: Make MachineMemOperands aware of scalable 4552 // vectors. 4553 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4554 4555 if (!UniformBase) { 4556 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4557 Index = getValue(Ptr); 4558 IndexType = ISD::SIGNED_UNSCALED; 4559 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4560 } 4561 4562 EVT IdxVT = Index.getValueType(); 4563 EVT EltTy = IdxVT.getVectorElementType(); 4564 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4565 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4566 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4567 } 4568 4569 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4570 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4571 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4572 4573 PendingLoads.push_back(Gather.getValue(1)); 4574 setValue(&I, Gather); 4575 } 4576 4577 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4578 SDLoc dl = getCurSDLoc(); 4579 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4580 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4581 SyncScope::ID SSID = I.getSyncScopeID(); 4582 4583 SDValue InChain = getRoot(); 4584 4585 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4586 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4587 4588 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4589 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4590 4591 MachineFunction &MF = DAG.getMachineFunction(); 4592 MachineMemOperand *MMO = MF.getMachineMemOperand( 4593 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4594 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4595 FailureOrdering); 4596 4597 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4598 dl, MemVT, VTs, InChain, 4599 getValue(I.getPointerOperand()), 4600 getValue(I.getCompareOperand()), 4601 getValue(I.getNewValOperand()), MMO); 4602 4603 SDValue OutChain = L.getValue(2); 4604 4605 setValue(&I, L); 4606 DAG.setRoot(OutChain); 4607 } 4608 4609 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4610 SDLoc dl = getCurSDLoc(); 4611 ISD::NodeType NT; 4612 switch (I.getOperation()) { 4613 default: llvm_unreachable("Unknown atomicrmw operation"); 4614 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4615 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4616 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4617 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4618 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4619 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4620 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4621 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4622 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4623 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4624 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4625 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4626 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4627 } 4628 AtomicOrdering Ordering = I.getOrdering(); 4629 SyncScope::ID SSID = I.getSyncScopeID(); 4630 4631 SDValue InChain = getRoot(); 4632 4633 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4635 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4636 4637 MachineFunction &MF = DAG.getMachineFunction(); 4638 MachineMemOperand *MMO = MF.getMachineMemOperand( 4639 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4640 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4641 4642 SDValue L = 4643 DAG.getAtomic(NT, dl, MemVT, InChain, 4644 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4645 MMO); 4646 4647 SDValue OutChain = L.getValue(1); 4648 4649 setValue(&I, L); 4650 DAG.setRoot(OutChain); 4651 } 4652 4653 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4654 SDLoc dl = getCurSDLoc(); 4655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4656 SDValue Ops[3]; 4657 Ops[0] = getRoot(); 4658 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4659 TLI.getFenceOperandTy(DAG.getDataLayout())); 4660 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4661 TLI.getFenceOperandTy(DAG.getDataLayout())); 4662 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4663 } 4664 4665 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4666 SDLoc dl = getCurSDLoc(); 4667 AtomicOrdering Order = I.getOrdering(); 4668 SyncScope::ID SSID = I.getSyncScopeID(); 4669 4670 SDValue InChain = getRoot(); 4671 4672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4673 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4674 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4675 4676 if (!TLI.supportsUnalignedAtomics() && 4677 I.getAlignment() < MemVT.getSizeInBits() / 8) 4678 report_fatal_error("Cannot generate unaligned atomic load"); 4679 4680 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4681 4682 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4683 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4684 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4685 4686 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4687 4688 SDValue Ptr = getValue(I.getPointerOperand()); 4689 4690 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4691 // TODO: Once this is better exercised by tests, it should be merged with 4692 // the normal path for loads to prevent future divergence. 4693 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4694 if (MemVT != VT) 4695 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4696 4697 setValue(&I, L); 4698 SDValue OutChain = L.getValue(1); 4699 if (!I.isUnordered()) 4700 DAG.setRoot(OutChain); 4701 else 4702 PendingLoads.push_back(OutChain); 4703 return; 4704 } 4705 4706 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4707 Ptr, MMO); 4708 4709 SDValue OutChain = L.getValue(1); 4710 if (MemVT != VT) 4711 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4712 4713 setValue(&I, L); 4714 DAG.setRoot(OutChain); 4715 } 4716 4717 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4718 SDLoc dl = getCurSDLoc(); 4719 4720 AtomicOrdering Ordering = I.getOrdering(); 4721 SyncScope::ID SSID = I.getSyncScopeID(); 4722 4723 SDValue InChain = getRoot(); 4724 4725 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4726 EVT MemVT = 4727 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4728 4729 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4730 report_fatal_error("Cannot generate unaligned atomic store"); 4731 4732 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4733 4734 MachineFunction &MF = DAG.getMachineFunction(); 4735 MachineMemOperand *MMO = MF.getMachineMemOperand( 4736 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4737 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4738 4739 SDValue Val = getValue(I.getValueOperand()); 4740 if (Val.getValueType() != MemVT) 4741 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4742 SDValue Ptr = getValue(I.getPointerOperand()); 4743 4744 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4745 // TODO: Once this is better exercised by tests, it should be merged with 4746 // the normal path for stores to prevent future divergence. 4747 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4748 DAG.setRoot(S); 4749 return; 4750 } 4751 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4752 Ptr, Val, MMO); 4753 4754 4755 DAG.setRoot(OutChain); 4756 } 4757 4758 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4759 /// node. 4760 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4761 unsigned Intrinsic) { 4762 // Ignore the callsite's attributes. A specific call site may be marked with 4763 // readnone, but the lowering code will expect the chain based on the 4764 // definition. 4765 const Function *F = I.getCalledFunction(); 4766 bool HasChain = !F->doesNotAccessMemory(); 4767 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4768 4769 // Build the operand list. 4770 SmallVector<SDValue, 8> Ops; 4771 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4772 if (OnlyLoad) { 4773 // We don't need to serialize loads against other loads. 4774 Ops.push_back(DAG.getRoot()); 4775 } else { 4776 Ops.push_back(getRoot()); 4777 } 4778 } 4779 4780 // Info is set by getTgtMemInstrinsic 4781 TargetLowering::IntrinsicInfo Info; 4782 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4783 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4784 DAG.getMachineFunction(), 4785 Intrinsic); 4786 4787 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4788 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4789 Info.opc == ISD::INTRINSIC_W_CHAIN) 4790 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4791 TLI.getPointerTy(DAG.getDataLayout()))); 4792 4793 // Add all operands of the call to the operand list. 4794 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4795 const Value *Arg = I.getArgOperand(i); 4796 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4797 Ops.push_back(getValue(Arg)); 4798 continue; 4799 } 4800 4801 // Use TargetConstant instead of a regular constant for immarg. 4802 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4803 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4804 assert(CI->getBitWidth() <= 64 && 4805 "large intrinsic immediates not handled"); 4806 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4807 } else { 4808 Ops.push_back( 4809 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4810 } 4811 } 4812 4813 SmallVector<EVT, 4> ValueVTs; 4814 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4815 4816 if (HasChain) 4817 ValueVTs.push_back(MVT::Other); 4818 4819 SDVTList VTs = DAG.getVTList(ValueVTs); 4820 4821 // Propagate fast-math-flags from IR to node(s). 4822 SDNodeFlags Flags; 4823 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4824 Flags.copyFMF(*FPMO); 4825 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4826 4827 // Create the node. 4828 SDValue Result; 4829 if (IsTgtIntrinsic) { 4830 // This is target intrinsic that touches memory 4831 AAMDNodes AAInfo; 4832 I.getAAMetadata(AAInfo); 4833 Result = 4834 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4835 MachinePointerInfo(Info.ptrVal, Info.offset), 4836 Info.align, Info.flags, Info.size, AAInfo); 4837 } else if (!HasChain) { 4838 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4839 } else if (!I.getType()->isVoidTy()) { 4840 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4841 } else { 4842 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4843 } 4844 4845 if (HasChain) { 4846 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4847 if (OnlyLoad) 4848 PendingLoads.push_back(Chain); 4849 else 4850 DAG.setRoot(Chain); 4851 } 4852 4853 if (!I.getType()->isVoidTy()) { 4854 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4855 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4856 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4857 } else 4858 Result = lowerRangeToAssertZExt(DAG, I, Result); 4859 4860 MaybeAlign Alignment = I.getRetAlign(); 4861 if (!Alignment) 4862 Alignment = F->getAttributes().getRetAlignment(); 4863 // Insert `assertalign` node if there's an alignment. 4864 if (InsertAssertAlign && Alignment) { 4865 Result = 4866 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4867 } 4868 4869 setValue(&I, Result); 4870 } 4871 } 4872 4873 /// GetSignificand - Get the significand and build it into a floating-point 4874 /// number with exponent of 1: 4875 /// 4876 /// Op = (Op & 0x007fffff) | 0x3f800000; 4877 /// 4878 /// where Op is the hexadecimal representation of floating point value. 4879 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4880 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4881 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4882 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4883 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4884 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4885 } 4886 4887 /// GetExponent - Get the exponent: 4888 /// 4889 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4890 /// 4891 /// where Op is the hexadecimal representation of floating point value. 4892 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4893 const TargetLowering &TLI, const SDLoc &dl) { 4894 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4895 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4896 SDValue t1 = DAG.getNode( 4897 ISD::SRL, dl, MVT::i32, t0, 4898 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4899 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4900 DAG.getConstant(127, dl, MVT::i32)); 4901 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4902 } 4903 4904 /// getF32Constant - Get 32-bit floating point constant. 4905 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4906 const SDLoc &dl) { 4907 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4908 MVT::f32); 4909 } 4910 4911 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4912 SelectionDAG &DAG) { 4913 // TODO: What fast-math-flags should be set on the floating-point nodes? 4914 4915 // IntegerPartOfX = ((int32_t)(t0); 4916 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4917 4918 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4919 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4920 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4921 4922 // IntegerPartOfX <<= 23; 4923 IntegerPartOfX = DAG.getNode( 4924 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4925 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4926 DAG.getDataLayout()))); 4927 4928 SDValue TwoToFractionalPartOfX; 4929 if (LimitFloatPrecision <= 6) { 4930 // For floating-point precision of 6: 4931 // 4932 // TwoToFractionalPartOfX = 4933 // 0.997535578f + 4934 // (0.735607626f + 0.252464424f * x) * x; 4935 // 4936 // error 0.0144103317, which is 6 bits 4937 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4938 getF32Constant(DAG, 0x3e814304, dl)); 4939 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4940 getF32Constant(DAG, 0x3f3c50c8, dl)); 4941 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4942 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4943 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4944 } else if (LimitFloatPrecision <= 12) { 4945 // For floating-point precision of 12: 4946 // 4947 // TwoToFractionalPartOfX = 4948 // 0.999892986f + 4949 // (0.696457318f + 4950 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4951 // 4952 // error 0.000107046256, which is 13 to 14 bits 4953 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4954 getF32Constant(DAG, 0x3da235e3, dl)); 4955 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4956 getF32Constant(DAG, 0x3e65b8f3, dl)); 4957 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4958 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4959 getF32Constant(DAG, 0x3f324b07, dl)); 4960 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4961 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4962 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4963 } else { // LimitFloatPrecision <= 18 4964 // For floating-point precision of 18: 4965 // 4966 // TwoToFractionalPartOfX = 4967 // 0.999999982f + 4968 // (0.693148872f + 4969 // (0.240227044f + 4970 // (0.554906021e-1f + 4971 // (0.961591928e-2f + 4972 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4973 // error 2.47208000*10^(-7), which is better than 18 bits 4974 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4975 getF32Constant(DAG, 0x3924b03e, dl)); 4976 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4977 getF32Constant(DAG, 0x3ab24b87, dl)); 4978 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4979 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4980 getF32Constant(DAG, 0x3c1d8c17, dl)); 4981 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4982 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4983 getF32Constant(DAG, 0x3d634a1d, dl)); 4984 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4985 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4986 getF32Constant(DAG, 0x3e75fe14, dl)); 4987 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4988 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4989 getF32Constant(DAG, 0x3f317234, dl)); 4990 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4991 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4992 getF32Constant(DAG, 0x3f800000, dl)); 4993 } 4994 4995 // Add the exponent into the result in integer domain. 4996 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4997 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4998 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4999 } 5000 5001 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5002 /// limited-precision mode. 5003 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5004 const TargetLowering &TLI, SDNodeFlags Flags) { 5005 if (Op.getValueType() == MVT::f32 && 5006 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5007 5008 // Put the exponent in the right bit position for later addition to the 5009 // final result: 5010 // 5011 // t0 = Op * log2(e) 5012 5013 // TODO: What fast-math-flags should be set here? 5014 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5015 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5016 return getLimitedPrecisionExp2(t0, dl, DAG); 5017 } 5018 5019 // No special expansion. 5020 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5021 } 5022 5023 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5024 /// limited-precision mode. 5025 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5026 const TargetLowering &TLI, SDNodeFlags Flags) { 5027 // TODO: What fast-math-flags should be set on the floating-point nodes? 5028 5029 if (Op.getValueType() == MVT::f32 && 5030 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5031 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5032 5033 // Scale the exponent by log(2). 5034 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5035 SDValue LogOfExponent = 5036 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5037 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5038 5039 // Get the significand and build it into a floating-point number with 5040 // exponent of 1. 5041 SDValue X = GetSignificand(DAG, Op1, dl); 5042 5043 SDValue LogOfMantissa; 5044 if (LimitFloatPrecision <= 6) { 5045 // For floating-point precision of 6: 5046 // 5047 // LogofMantissa = 5048 // -1.1609546f + 5049 // (1.4034025f - 0.23903021f * x) * x; 5050 // 5051 // error 0.0034276066, which is better than 8 bits 5052 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5053 getF32Constant(DAG, 0xbe74c456, dl)); 5054 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5055 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5056 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5057 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5058 getF32Constant(DAG, 0x3f949a29, dl)); 5059 } else if (LimitFloatPrecision <= 12) { 5060 // For floating-point precision of 12: 5061 // 5062 // LogOfMantissa = 5063 // -1.7417939f + 5064 // (2.8212026f + 5065 // (-1.4699568f + 5066 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5067 // 5068 // error 0.000061011436, which is 14 bits 5069 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5070 getF32Constant(DAG, 0xbd67b6d6, dl)); 5071 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5072 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5073 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5074 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5075 getF32Constant(DAG, 0x3fbc278b, dl)); 5076 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5077 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5078 getF32Constant(DAG, 0x40348e95, dl)); 5079 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5080 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5081 getF32Constant(DAG, 0x3fdef31a, dl)); 5082 } else { // LimitFloatPrecision <= 18 5083 // For floating-point precision of 18: 5084 // 5085 // LogOfMantissa = 5086 // -2.1072184f + 5087 // (4.2372794f + 5088 // (-3.7029485f + 5089 // (2.2781945f + 5090 // (-0.87823314f + 5091 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5092 // 5093 // error 0.0000023660568, which is better than 18 bits 5094 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5095 getF32Constant(DAG, 0xbc91e5ac, dl)); 5096 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5097 getF32Constant(DAG, 0x3e4350aa, dl)); 5098 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5099 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5100 getF32Constant(DAG, 0x3f60d3e3, dl)); 5101 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5102 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5103 getF32Constant(DAG, 0x4011cdf0, dl)); 5104 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5105 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5106 getF32Constant(DAG, 0x406cfd1c, dl)); 5107 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5108 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5109 getF32Constant(DAG, 0x408797cb, dl)); 5110 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5111 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5112 getF32Constant(DAG, 0x4006dcab, dl)); 5113 } 5114 5115 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5116 } 5117 5118 // No special expansion. 5119 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5120 } 5121 5122 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5123 /// limited-precision mode. 5124 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5125 const TargetLowering &TLI, SDNodeFlags Flags) { 5126 // TODO: What fast-math-flags should be set on the floating-point nodes? 5127 5128 if (Op.getValueType() == MVT::f32 && 5129 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5130 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5131 5132 // Get the exponent. 5133 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5134 5135 // Get the significand and build it into a floating-point number with 5136 // exponent of 1. 5137 SDValue X = GetSignificand(DAG, Op1, dl); 5138 5139 // Different possible minimax approximations of significand in 5140 // floating-point for various degrees of accuracy over [1,2]. 5141 SDValue Log2ofMantissa; 5142 if (LimitFloatPrecision <= 6) { 5143 // For floating-point precision of 6: 5144 // 5145 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5146 // 5147 // error 0.0049451742, which is more than 7 bits 5148 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5149 getF32Constant(DAG, 0xbeb08fe0, dl)); 5150 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5151 getF32Constant(DAG, 0x40019463, dl)); 5152 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5153 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5154 getF32Constant(DAG, 0x3fd6633d, dl)); 5155 } else if (LimitFloatPrecision <= 12) { 5156 // For floating-point precision of 12: 5157 // 5158 // Log2ofMantissa = 5159 // -2.51285454f + 5160 // (4.07009056f + 5161 // (-2.12067489f + 5162 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5163 // 5164 // error 0.0000876136000, which is better than 13 bits 5165 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5166 getF32Constant(DAG, 0xbda7262e, dl)); 5167 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5168 getF32Constant(DAG, 0x3f25280b, dl)); 5169 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5170 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5171 getF32Constant(DAG, 0x4007b923, dl)); 5172 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5173 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5174 getF32Constant(DAG, 0x40823e2f, dl)); 5175 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5176 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5177 getF32Constant(DAG, 0x4020d29c, dl)); 5178 } else { // LimitFloatPrecision <= 18 5179 // For floating-point precision of 18: 5180 // 5181 // Log2ofMantissa = 5182 // -3.0400495f + 5183 // (6.1129976f + 5184 // (-5.3420409f + 5185 // (3.2865683f + 5186 // (-1.2669343f + 5187 // (0.27515199f - 5188 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5189 // 5190 // error 0.0000018516, which is better than 18 bits 5191 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5192 getF32Constant(DAG, 0xbcd2769e, dl)); 5193 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5194 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5195 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5196 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5197 getF32Constant(DAG, 0x3fa22ae7, dl)); 5198 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5199 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5200 getF32Constant(DAG, 0x40525723, dl)); 5201 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5202 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5203 getF32Constant(DAG, 0x40aaf200, dl)); 5204 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5205 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5206 getF32Constant(DAG, 0x40c39dad, dl)); 5207 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5208 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5209 getF32Constant(DAG, 0x4042902c, dl)); 5210 } 5211 5212 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5213 } 5214 5215 // No special expansion. 5216 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5217 } 5218 5219 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5220 /// limited-precision mode. 5221 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5222 const TargetLowering &TLI, SDNodeFlags Flags) { 5223 // TODO: What fast-math-flags should be set on the floating-point nodes? 5224 5225 if (Op.getValueType() == MVT::f32 && 5226 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5227 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5228 5229 // Scale the exponent by log10(2) [0.30102999f]. 5230 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5231 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5232 getF32Constant(DAG, 0x3e9a209a, dl)); 5233 5234 // Get the significand and build it into a floating-point number with 5235 // exponent of 1. 5236 SDValue X = GetSignificand(DAG, Op1, dl); 5237 5238 SDValue Log10ofMantissa; 5239 if (LimitFloatPrecision <= 6) { 5240 // For floating-point precision of 6: 5241 // 5242 // Log10ofMantissa = 5243 // -0.50419619f + 5244 // (0.60948995f - 0.10380950f * x) * x; 5245 // 5246 // error 0.0014886165, which is 6 bits 5247 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5248 getF32Constant(DAG, 0xbdd49a13, dl)); 5249 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5250 getF32Constant(DAG, 0x3f1c0789, dl)); 5251 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5252 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5253 getF32Constant(DAG, 0x3f011300, dl)); 5254 } else if (LimitFloatPrecision <= 12) { 5255 // For floating-point precision of 12: 5256 // 5257 // Log10ofMantissa = 5258 // -0.64831180f + 5259 // (0.91751397f + 5260 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5261 // 5262 // error 0.00019228036, which is better than 12 bits 5263 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5264 getF32Constant(DAG, 0x3d431f31, dl)); 5265 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5266 getF32Constant(DAG, 0x3ea21fb2, dl)); 5267 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5268 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5269 getF32Constant(DAG, 0x3f6ae232, dl)); 5270 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5271 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5272 getF32Constant(DAG, 0x3f25f7c3, dl)); 5273 } else { // LimitFloatPrecision <= 18 5274 // For floating-point precision of 18: 5275 // 5276 // Log10ofMantissa = 5277 // -0.84299375f + 5278 // (1.5327582f + 5279 // (-1.0688956f + 5280 // (0.49102474f + 5281 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5282 // 5283 // error 0.0000037995730, which is better than 18 bits 5284 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5285 getF32Constant(DAG, 0x3c5d51ce, dl)); 5286 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5287 getF32Constant(DAG, 0x3e00685a, dl)); 5288 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5289 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5290 getF32Constant(DAG, 0x3efb6798, dl)); 5291 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5292 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5293 getF32Constant(DAG, 0x3f88d192, dl)); 5294 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5295 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5296 getF32Constant(DAG, 0x3fc4316c, dl)); 5297 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5298 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5299 getF32Constant(DAG, 0x3f57ce70, dl)); 5300 } 5301 5302 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5303 } 5304 5305 // No special expansion. 5306 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5307 } 5308 5309 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5310 /// limited-precision mode. 5311 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5312 const TargetLowering &TLI, SDNodeFlags Flags) { 5313 if (Op.getValueType() == MVT::f32 && 5314 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5315 return getLimitedPrecisionExp2(Op, dl, DAG); 5316 5317 // No special expansion. 5318 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5319 } 5320 5321 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5322 /// limited-precision mode with x == 10.0f. 5323 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5324 SelectionDAG &DAG, const TargetLowering &TLI, 5325 SDNodeFlags Flags) { 5326 bool IsExp10 = false; 5327 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5328 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5329 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5330 APFloat Ten(10.0f); 5331 IsExp10 = LHSC->isExactlyValue(Ten); 5332 } 5333 } 5334 5335 // TODO: What fast-math-flags should be set on the FMUL node? 5336 if (IsExp10) { 5337 // Put the exponent in the right bit position for later addition to the 5338 // final result: 5339 // 5340 // #define LOG2OF10 3.3219281f 5341 // t0 = Op * LOG2OF10; 5342 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5343 getF32Constant(DAG, 0x40549a78, dl)); 5344 return getLimitedPrecisionExp2(t0, dl, DAG); 5345 } 5346 5347 // No special expansion. 5348 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5349 } 5350 5351 /// ExpandPowI - Expand a llvm.powi intrinsic. 5352 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5353 SelectionDAG &DAG) { 5354 // If RHS is a constant, we can expand this out to a multiplication tree, 5355 // otherwise we end up lowering to a call to __powidf2 (for example). When 5356 // optimizing for size, we only want to do this if the expansion would produce 5357 // a small number of multiplies, otherwise we do the full expansion. 5358 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5359 // Get the exponent as a positive value. 5360 unsigned Val = RHSC->getSExtValue(); 5361 if ((int)Val < 0) Val = -Val; 5362 5363 // powi(x, 0) -> 1.0 5364 if (Val == 0) 5365 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5366 5367 bool OptForSize = DAG.shouldOptForSize(); 5368 if (!OptForSize || 5369 // If optimizing for size, don't insert too many multiplies. 5370 // This inserts up to 5 multiplies. 5371 countPopulation(Val) + Log2_32(Val) < 7) { 5372 // We use the simple binary decomposition method to generate the multiply 5373 // sequence. There are more optimal ways to do this (for example, 5374 // powi(x,15) generates one more multiply than it should), but this has 5375 // the benefit of being both really simple and much better than a libcall. 5376 SDValue Res; // Logically starts equal to 1.0 5377 SDValue CurSquare = LHS; 5378 // TODO: Intrinsics should have fast-math-flags that propagate to these 5379 // nodes. 5380 while (Val) { 5381 if (Val & 1) { 5382 if (Res.getNode()) 5383 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5384 else 5385 Res = CurSquare; // 1.0*CurSquare. 5386 } 5387 5388 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5389 CurSquare, CurSquare); 5390 Val >>= 1; 5391 } 5392 5393 // If the original was negative, invert the result, producing 1/(x*x*x). 5394 if (RHSC->getSExtValue() < 0) 5395 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5396 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5397 return Res; 5398 } 5399 } 5400 5401 // Otherwise, expand to a libcall. 5402 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5403 } 5404 5405 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5406 SDValue LHS, SDValue RHS, SDValue Scale, 5407 SelectionDAG &DAG, const TargetLowering &TLI) { 5408 EVT VT = LHS.getValueType(); 5409 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5410 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5411 LLVMContext &Ctx = *DAG.getContext(); 5412 5413 // If the type is legal but the operation isn't, this node might survive all 5414 // the way to operation legalization. If we end up there and we do not have 5415 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5416 // node. 5417 5418 // Coax the legalizer into expanding the node during type legalization instead 5419 // by bumping the size by one bit. This will force it to Promote, enabling the 5420 // early expansion and avoiding the need to expand later. 5421 5422 // We don't have to do this if Scale is 0; that can always be expanded, unless 5423 // it's a saturating signed operation. Those can experience true integer 5424 // division overflow, a case which we must avoid. 5425 5426 // FIXME: We wouldn't have to do this (or any of the early 5427 // expansion/promotion) if it was possible to expand a libcall of an 5428 // illegal type during operation legalization. But it's not, so things 5429 // get a bit hacky. 5430 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5431 if ((ScaleInt > 0 || (Saturating && Signed)) && 5432 (TLI.isTypeLegal(VT) || 5433 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5434 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5435 Opcode, VT, ScaleInt); 5436 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5437 EVT PromVT; 5438 if (VT.isScalarInteger()) 5439 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5440 else if (VT.isVector()) { 5441 PromVT = VT.getVectorElementType(); 5442 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5443 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5444 } else 5445 llvm_unreachable("Wrong VT for DIVFIX?"); 5446 if (Signed) { 5447 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5448 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5449 } else { 5450 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5451 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5452 } 5453 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5454 // For saturating operations, we need to shift up the LHS to get the 5455 // proper saturation width, and then shift down again afterwards. 5456 if (Saturating) 5457 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5458 DAG.getConstant(1, DL, ShiftTy)); 5459 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5460 if (Saturating) 5461 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5462 DAG.getConstant(1, DL, ShiftTy)); 5463 return DAG.getZExtOrTrunc(Res, DL, VT); 5464 } 5465 } 5466 5467 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5468 } 5469 5470 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5471 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5472 static void 5473 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5474 const SDValue &N) { 5475 switch (N.getOpcode()) { 5476 case ISD::CopyFromReg: { 5477 SDValue Op = N.getOperand(1); 5478 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5479 Op.getValueType().getSizeInBits()); 5480 return; 5481 } 5482 case ISD::BITCAST: 5483 case ISD::AssertZext: 5484 case ISD::AssertSext: 5485 case ISD::TRUNCATE: 5486 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5487 return; 5488 case ISD::BUILD_PAIR: 5489 case ISD::BUILD_VECTOR: 5490 case ISD::CONCAT_VECTORS: 5491 for (SDValue Op : N->op_values()) 5492 getUnderlyingArgRegs(Regs, Op); 5493 return; 5494 default: 5495 return; 5496 } 5497 } 5498 5499 /// If the DbgValueInst is a dbg_value of a function argument, create the 5500 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5501 /// instruction selection, they will be inserted to the entry BB. 5502 /// We don't currently support this for variadic dbg_values, as they shouldn't 5503 /// appear for function arguments or in the prologue. 5504 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5505 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5506 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5507 const Argument *Arg = dyn_cast<Argument>(V); 5508 if (!Arg) 5509 return false; 5510 5511 MachineFunction &MF = DAG.getMachineFunction(); 5512 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5513 5514 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5515 // we've been asked to pursue. 5516 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5517 bool Indirect) { 5518 if (Reg.isVirtual() && TM.Options.ValueTrackingVariableLocations) { 5519 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5520 // pointing at the VReg, which will be patched up later. 5521 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5522 auto MIB = BuildMI(MF, DL, Inst); 5523 MIB.addReg(Reg, RegState::Debug); 5524 MIB.addImm(0); 5525 MIB.addMetadata(Variable); 5526 auto *NewDIExpr = FragExpr; 5527 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5528 // the DIExpression. 5529 if (Indirect) 5530 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5531 MIB.addMetadata(NewDIExpr); 5532 return MIB; 5533 } else { 5534 // Create a completely standard DBG_VALUE. 5535 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5536 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5537 } 5538 }; 5539 5540 if (!IsDbgDeclare) { 5541 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5542 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5543 // the entry block. 5544 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5545 if (!IsInEntryBlock) 5546 return false; 5547 5548 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5549 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5550 // variable that also is a param. 5551 // 5552 // Although, if we are at the top of the entry block already, we can still 5553 // emit using ArgDbgValue. This might catch some situations when the 5554 // dbg.value refers to an argument that isn't used in the entry block, so 5555 // any CopyToReg node would be optimized out and the only way to express 5556 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5557 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5558 // we should only emit as ArgDbgValue if the Variable is an argument to the 5559 // current function, and the dbg.value intrinsic is found in the entry 5560 // block. 5561 bool VariableIsFunctionInputArg = Variable->isParameter() && 5562 !DL->getInlinedAt(); 5563 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5564 if (!IsInPrologue && !VariableIsFunctionInputArg) 5565 return false; 5566 5567 // Here we assume that a function argument on IR level only can be used to 5568 // describe one input parameter on source level. If we for example have 5569 // source code like this 5570 // 5571 // struct A { long x, y; }; 5572 // void foo(struct A a, long b) { 5573 // ... 5574 // b = a.x; 5575 // ... 5576 // } 5577 // 5578 // and IR like this 5579 // 5580 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5581 // entry: 5582 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5583 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5584 // call void @llvm.dbg.value(metadata i32 %b, "b", 5585 // ... 5586 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5587 // ... 5588 // 5589 // then the last dbg.value is describing a parameter "b" using a value that 5590 // is an argument. But since we already has used %a1 to describe a parameter 5591 // we should not handle that last dbg.value here (that would result in an 5592 // incorrect hoisting of the DBG_VALUE to the function entry). 5593 // Notice that we allow one dbg.value per IR level argument, to accommodate 5594 // for the situation with fragments above. 5595 if (VariableIsFunctionInputArg) { 5596 unsigned ArgNo = Arg->getArgNo(); 5597 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5598 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5599 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5600 return false; 5601 FuncInfo.DescribedArgs.set(ArgNo); 5602 } 5603 } 5604 5605 bool IsIndirect = false; 5606 Optional<MachineOperand> Op; 5607 // Some arguments' frame index is recorded during argument lowering. 5608 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5609 if (FI != std::numeric_limits<int>::max()) 5610 Op = MachineOperand::CreateFI(FI); 5611 5612 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5613 if (!Op && N.getNode()) { 5614 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5615 Register Reg; 5616 if (ArgRegsAndSizes.size() == 1) 5617 Reg = ArgRegsAndSizes.front().first; 5618 5619 if (Reg && Reg.isVirtual()) { 5620 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5621 Register PR = RegInfo.getLiveInPhysReg(Reg); 5622 if (PR) 5623 Reg = PR; 5624 } 5625 if (Reg) { 5626 Op = MachineOperand::CreateReg(Reg, false); 5627 IsIndirect = IsDbgDeclare; 5628 } 5629 } 5630 5631 if (!Op && N.getNode()) { 5632 // Check if frame index is available. 5633 SDValue LCandidate = peekThroughBitcasts(N); 5634 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5635 if (FrameIndexSDNode *FINode = 5636 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5637 Op = MachineOperand::CreateFI(FINode->getIndex()); 5638 } 5639 5640 if (!Op) { 5641 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5642 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5643 SplitRegs) { 5644 unsigned Offset = 0; 5645 for (auto RegAndSize : SplitRegs) { 5646 // If the expression is already a fragment, the current register 5647 // offset+size might extend beyond the fragment. In this case, only 5648 // the register bits that are inside the fragment are relevant. 5649 int RegFragmentSizeInBits = RegAndSize.second; 5650 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5651 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5652 // The register is entirely outside the expression fragment, 5653 // so is irrelevant for debug info. 5654 if (Offset >= ExprFragmentSizeInBits) 5655 break; 5656 // The register is partially outside the expression fragment, only 5657 // the low bits within the fragment are relevant for debug info. 5658 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5659 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5660 } 5661 } 5662 5663 auto FragmentExpr = DIExpression::createFragmentExpression( 5664 Expr, Offset, RegFragmentSizeInBits); 5665 Offset += RegAndSize.second; 5666 // If a valid fragment expression cannot be created, the variable's 5667 // correct value cannot be determined and so it is set as Undef. 5668 if (!FragmentExpr) { 5669 SDDbgValue *SDV = DAG.getConstantDbgValue( 5670 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5671 DAG.AddDbgValue(SDV, false); 5672 continue; 5673 } 5674 MachineInstr *NewMI = 5675 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare); 5676 FuncInfo.ArgDbgValues.push_back(NewMI); 5677 } 5678 }; 5679 5680 // Check if ValueMap has reg number. 5681 DenseMap<const Value *, Register>::const_iterator 5682 VMI = FuncInfo.ValueMap.find(V); 5683 if (VMI != FuncInfo.ValueMap.end()) { 5684 const auto &TLI = DAG.getTargetLoweringInfo(); 5685 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5686 V->getType(), None); 5687 if (RFV.occupiesMultipleRegs()) { 5688 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5689 return true; 5690 } 5691 5692 Op = MachineOperand::CreateReg(VMI->second, false); 5693 IsIndirect = IsDbgDeclare; 5694 } else if (ArgRegsAndSizes.size() > 1) { 5695 // This was split due to the calling convention, and no virtual register 5696 // mapping exists for the value. 5697 splitMultiRegDbgValue(ArgRegsAndSizes); 5698 return true; 5699 } 5700 } 5701 5702 if (!Op) 5703 return false; 5704 5705 assert(Variable->isValidLocationForIntrinsic(DL) && 5706 "Expected inlined-at fields to agree"); 5707 MachineInstr *NewMI = nullptr; 5708 5709 if (Op->isReg()) 5710 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5711 else 5712 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5713 Variable, Expr); 5714 5715 FuncInfo.ArgDbgValues.push_back(NewMI); 5716 return true; 5717 } 5718 5719 /// Return the appropriate SDDbgValue based on N. 5720 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5721 DILocalVariable *Variable, 5722 DIExpression *Expr, 5723 const DebugLoc &dl, 5724 unsigned DbgSDNodeOrder) { 5725 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5726 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5727 // stack slot locations. 5728 // 5729 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5730 // debug values here after optimization: 5731 // 5732 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5733 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5734 // 5735 // Both describe the direct values of their associated variables. 5736 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5737 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5738 } 5739 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5740 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5741 } 5742 5743 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5744 switch (Intrinsic) { 5745 case Intrinsic::smul_fix: 5746 return ISD::SMULFIX; 5747 case Intrinsic::umul_fix: 5748 return ISD::UMULFIX; 5749 case Intrinsic::smul_fix_sat: 5750 return ISD::SMULFIXSAT; 5751 case Intrinsic::umul_fix_sat: 5752 return ISD::UMULFIXSAT; 5753 case Intrinsic::sdiv_fix: 5754 return ISD::SDIVFIX; 5755 case Intrinsic::udiv_fix: 5756 return ISD::UDIVFIX; 5757 case Intrinsic::sdiv_fix_sat: 5758 return ISD::SDIVFIXSAT; 5759 case Intrinsic::udiv_fix_sat: 5760 return ISD::UDIVFIXSAT; 5761 default: 5762 llvm_unreachable("Unhandled fixed point intrinsic"); 5763 } 5764 } 5765 5766 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5767 const char *FunctionName) { 5768 assert(FunctionName && "FunctionName must not be nullptr"); 5769 SDValue Callee = DAG.getExternalSymbol( 5770 FunctionName, 5771 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5772 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5773 } 5774 5775 /// Given a @llvm.call.preallocated.setup, return the corresponding 5776 /// preallocated call. 5777 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5778 assert(cast<CallBase>(PreallocatedSetup) 5779 ->getCalledFunction() 5780 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5781 "expected call_preallocated_setup Value"); 5782 for (auto *U : PreallocatedSetup->users()) { 5783 auto *UseCall = cast<CallBase>(U); 5784 const Function *Fn = UseCall->getCalledFunction(); 5785 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5786 return UseCall; 5787 } 5788 } 5789 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5790 } 5791 5792 /// Lower the call to the specified intrinsic function. 5793 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5794 unsigned Intrinsic) { 5795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5796 SDLoc sdl = getCurSDLoc(); 5797 DebugLoc dl = getCurDebugLoc(); 5798 SDValue Res; 5799 5800 SDNodeFlags Flags; 5801 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5802 Flags.copyFMF(*FPOp); 5803 5804 switch (Intrinsic) { 5805 default: 5806 // By default, turn this into a target intrinsic node. 5807 visitTargetIntrinsic(I, Intrinsic); 5808 return; 5809 case Intrinsic::vscale: { 5810 match(&I, m_VScale(DAG.getDataLayout())); 5811 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5812 setValue(&I, 5813 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5814 return; 5815 } 5816 case Intrinsic::vastart: visitVAStart(I); return; 5817 case Intrinsic::vaend: visitVAEnd(I); return; 5818 case Intrinsic::vacopy: visitVACopy(I); return; 5819 case Intrinsic::returnaddress: 5820 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5821 TLI.getPointerTy(DAG.getDataLayout()), 5822 getValue(I.getArgOperand(0)))); 5823 return; 5824 case Intrinsic::addressofreturnaddress: 5825 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5826 TLI.getPointerTy(DAG.getDataLayout()))); 5827 return; 5828 case Intrinsic::sponentry: 5829 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5830 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5831 return; 5832 case Intrinsic::frameaddress: 5833 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5834 TLI.getFrameIndexTy(DAG.getDataLayout()), 5835 getValue(I.getArgOperand(0)))); 5836 return; 5837 case Intrinsic::read_volatile_register: 5838 case Intrinsic::read_register: { 5839 Value *Reg = I.getArgOperand(0); 5840 SDValue Chain = getRoot(); 5841 SDValue RegName = 5842 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5843 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5844 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5845 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5846 setValue(&I, Res); 5847 DAG.setRoot(Res.getValue(1)); 5848 return; 5849 } 5850 case Intrinsic::write_register: { 5851 Value *Reg = I.getArgOperand(0); 5852 Value *RegValue = I.getArgOperand(1); 5853 SDValue Chain = getRoot(); 5854 SDValue RegName = 5855 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5856 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5857 RegName, getValue(RegValue))); 5858 return; 5859 } 5860 case Intrinsic::memcpy: { 5861 const auto &MCI = cast<MemCpyInst>(I); 5862 SDValue Op1 = getValue(I.getArgOperand(0)); 5863 SDValue Op2 = getValue(I.getArgOperand(1)); 5864 SDValue Op3 = getValue(I.getArgOperand(2)); 5865 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5866 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5867 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5868 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5869 bool isVol = MCI.isVolatile(); 5870 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5871 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5872 // node. 5873 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5874 AAMDNodes AAInfo; 5875 I.getAAMetadata(AAInfo); 5876 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5877 /* AlwaysInline */ false, isTC, 5878 MachinePointerInfo(I.getArgOperand(0)), 5879 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5880 updateDAGForMaybeTailCall(MC); 5881 return; 5882 } 5883 case Intrinsic::memcpy_inline: { 5884 const auto &MCI = cast<MemCpyInlineInst>(I); 5885 SDValue Dst = getValue(I.getArgOperand(0)); 5886 SDValue Src = getValue(I.getArgOperand(1)); 5887 SDValue Size = getValue(I.getArgOperand(2)); 5888 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5889 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5890 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5891 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5892 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5893 bool isVol = MCI.isVolatile(); 5894 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5895 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5896 // node. 5897 AAMDNodes AAInfo; 5898 I.getAAMetadata(AAInfo); 5899 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5900 /* AlwaysInline */ true, isTC, 5901 MachinePointerInfo(I.getArgOperand(0)), 5902 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5903 updateDAGForMaybeTailCall(MC); 5904 return; 5905 } 5906 case Intrinsic::memset: { 5907 const auto &MSI = cast<MemSetInst>(I); 5908 SDValue Op1 = getValue(I.getArgOperand(0)); 5909 SDValue Op2 = getValue(I.getArgOperand(1)); 5910 SDValue Op3 = getValue(I.getArgOperand(2)); 5911 // @llvm.memset defines 0 and 1 to both mean no alignment. 5912 Align Alignment = MSI.getDestAlign().valueOrOne(); 5913 bool isVol = MSI.isVolatile(); 5914 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5915 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5916 AAMDNodes AAInfo; 5917 I.getAAMetadata(AAInfo); 5918 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5919 MachinePointerInfo(I.getArgOperand(0)), AAInfo); 5920 updateDAGForMaybeTailCall(MS); 5921 return; 5922 } 5923 case Intrinsic::memmove: { 5924 const auto &MMI = cast<MemMoveInst>(I); 5925 SDValue Op1 = getValue(I.getArgOperand(0)); 5926 SDValue Op2 = getValue(I.getArgOperand(1)); 5927 SDValue Op3 = getValue(I.getArgOperand(2)); 5928 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5929 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5930 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5931 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5932 bool isVol = MMI.isVolatile(); 5933 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5934 // FIXME: Support passing different dest/src alignments to the memmove DAG 5935 // node. 5936 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5937 AAMDNodes AAInfo; 5938 I.getAAMetadata(AAInfo); 5939 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5940 isTC, MachinePointerInfo(I.getArgOperand(0)), 5941 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5942 updateDAGForMaybeTailCall(MM); 5943 return; 5944 } 5945 case Intrinsic::memcpy_element_unordered_atomic: { 5946 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5947 SDValue Dst = getValue(MI.getRawDest()); 5948 SDValue Src = getValue(MI.getRawSource()); 5949 SDValue Length = getValue(MI.getLength()); 5950 5951 unsigned DstAlign = MI.getDestAlignment(); 5952 unsigned SrcAlign = MI.getSourceAlignment(); 5953 Type *LengthTy = MI.getLength()->getType(); 5954 unsigned ElemSz = MI.getElementSizeInBytes(); 5955 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5956 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5957 SrcAlign, Length, LengthTy, ElemSz, isTC, 5958 MachinePointerInfo(MI.getRawDest()), 5959 MachinePointerInfo(MI.getRawSource())); 5960 updateDAGForMaybeTailCall(MC); 5961 return; 5962 } 5963 case Intrinsic::memmove_element_unordered_atomic: { 5964 auto &MI = cast<AtomicMemMoveInst>(I); 5965 SDValue Dst = getValue(MI.getRawDest()); 5966 SDValue Src = getValue(MI.getRawSource()); 5967 SDValue Length = getValue(MI.getLength()); 5968 5969 unsigned DstAlign = MI.getDestAlignment(); 5970 unsigned SrcAlign = MI.getSourceAlignment(); 5971 Type *LengthTy = MI.getLength()->getType(); 5972 unsigned ElemSz = MI.getElementSizeInBytes(); 5973 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5974 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5975 SrcAlign, Length, LengthTy, ElemSz, isTC, 5976 MachinePointerInfo(MI.getRawDest()), 5977 MachinePointerInfo(MI.getRawSource())); 5978 updateDAGForMaybeTailCall(MC); 5979 return; 5980 } 5981 case Intrinsic::memset_element_unordered_atomic: { 5982 auto &MI = cast<AtomicMemSetInst>(I); 5983 SDValue Dst = getValue(MI.getRawDest()); 5984 SDValue Val = getValue(MI.getValue()); 5985 SDValue Length = getValue(MI.getLength()); 5986 5987 unsigned DstAlign = MI.getDestAlignment(); 5988 Type *LengthTy = MI.getLength()->getType(); 5989 unsigned ElemSz = MI.getElementSizeInBytes(); 5990 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5991 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5992 LengthTy, ElemSz, isTC, 5993 MachinePointerInfo(MI.getRawDest())); 5994 updateDAGForMaybeTailCall(MC); 5995 return; 5996 } 5997 case Intrinsic::call_preallocated_setup: { 5998 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5999 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6000 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6001 getRoot(), SrcValue); 6002 setValue(&I, Res); 6003 DAG.setRoot(Res); 6004 return; 6005 } 6006 case Intrinsic::call_preallocated_arg: { 6007 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6008 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6009 SDValue Ops[3]; 6010 Ops[0] = getRoot(); 6011 Ops[1] = SrcValue; 6012 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6013 MVT::i32); // arg index 6014 SDValue Res = DAG.getNode( 6015 ISD::PREALLOCATED_ARG, sdl, 6016 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6017 setValue(&I, Res); 6018 DAG.setRoot(Res.getValue(1)); 6019 return; 6020 } 6021 case Intrinsic::dbg_addr: 6022 case Intrinsic::dbg_declare: { 6023 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6024 // they are non-variadic. 6025 const auto &DI = cast<DbgVariableIntrinsic>(I); 6026 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6027 DILocalVariable *Variable = DI.getVariable(); 6028 DIExpression *Expression = DI.getExpression(); 6029 dropDanglingDebugInfo(Variable, Expression); 6030 assert(Variable && "Missing variable"); 6031 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6032 << "\n"); 6033 // Check if address has undef value. 6034 const Value *Address = DI.getVariableLocationOp(0); 6035 if (!Address || isa<UndefValue>(Address) || 6036 (Address->use_empty() && !isa<Argument>(Address))) { 6037 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6038 << " (bad/undef/unused-arg address)\n"); 6039 return; 6040 } 6041 6042 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6043 6044 // Check if this variable can be described by a frame index, typically 6045 // either as a static alloca or a byval parameter. 6046 int FI = std::numeric_limits<int>::max(); 6047 if (const auto *AI = 6048 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6049 if (AI->isStaticAlloca()) { 6050 auto I = FuncInfo.StaticAllocaMap.find(AI); 6051 if (I != FuncInfo.StaticAllocaMap.end()) 6052 FI = I->second; 6053 } 6054 } else if (const auto *Arg = dyn_cast<Argument>( 6055 Address->stripInBoundsConstantOffsets())) { 6056 FI = FuncInfo.getArgumentFrameIndex(Arg); 6057 } 6058 6059 // llvm.dbg.addr is control dependent and always generates indirect 6060 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6061 // the MachineFunction variable table. 6062 if (FI != std::numeric_limits<int>::max()) { 6063 if (Intrinsic == Intrinsic::dbg_addr) { 6064 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6065 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6066 dl, SDNodeOrder); 6067 DAG.AddDbgValue(SDV, isParameter); 6068 } else { 6069 LLVM_DEBUG(dbgs() << "Skipping " << DI 6070 << " (variable info stashed in MF side table)\n"); 6071 } 6072 return; 6073 } 6074 6075 SDValue &N = NodeMap[Address]; 6076 if (!N.getNode() && isa<Argument>(Address)) 6077 // Check unused arguments map. 6078 N = UnusedArgNodeMap[Address]; 6079 SDDbgValue *SDV; 6080 if (N.getNode()) { 6081 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6082 Address = BCI->getOperand(0); 6083 // Parameters are handled specially. 6084 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6085 if (isParameter && FINode) { 6086 // Byval parameter. We have a frame index at this point. 6087 SDV = 6088 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6089 /*IsIndirect*/ true, dl, SDNodeOrder); 6090 } else if (isa<Argument>(Address)) { 6091 // Address is an argument, so try to emit its dbg value using 6092 // virtual register info from the FuncInfo.ValueMap. 6093 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6094 return; 6095 } else { 6096 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6097 true, dl, SDNodeOrder); 6098 } 6099 DAG.AddDbgValue(SDV, isParameter); 6100 } else { 6101 // If Address is an argument then try to emit its dbg value using 6102 // virtual register info from the FuncInfo.ValueMap. 6103 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6104 N)) { 6105 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6106 << " (could not emit func-arg dbg_value)\n"); 6107 } 6108 } 6109 return; 6110 } 6111 case Intrinsic::dbg_label: { 6112 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6113 DILabel *Label = DI.getLabel(); 6114 assert(Label && "Missing label"); 6115 6116 SDDbgLabel *SDV; 6117 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6118 DAG.AddDbgLabel(SDV); 6119 return; 6120 } 6121 case Intrinsic::dbg_value: { 6122 const DbgValueInst &DI = cast<DbgValueInst>(I); 6123 assert(DI.getVariable() && "Missing variable"); 6124 6125 DILocalVariable *Variable = DI.getVariable(); 6126 DIExpression *Expression = DI.getExpression(); 6127 dropDanglingDebugInfo(Variable, Expression); 6128 SmallVector<Value *, 4> Values(DI.getValues()); 6129 if (Values.empty()) 6130 return; 6131 6132 if (std::count(Values.begin(), Values.end(), nullptr)) 6133 return; 6134 6135 bool IsVariadic = DI.hasArgList(); 6136 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6137 SDNodeOrder, IsVariadic)) 6138 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6139 return; 6140 } 6141 6142 case Intrinsic::eh_typeid_for: { 6143 // Find the type id for the given typeinfo. 6144 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6145 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6146 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6147 setValue(&I, Res); 6148 return; 6149 } 6150 6151 case Intrinsic::eh_return_i32: 6152 case Intrinsic::eh_return_i64: 6153 DAG.getMachineFunction().setCallsEHReturn(true); 6154 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6155 MVT::Other, 6156 getControlRoot(), 6157 getValue(I.getArgOperand(0)), 6158 getValue(I.getArgOperand(1)))); 6159 return; 6160 case Intrinsic::eh_unwind_init: 6161 DAG.getMachineFunction().setCallsUnwindInit(true); 6162 return; 6163 case Intrinsic::eh_dwarf_cfa: 6164 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6165 TLI.getPointerTy(DAG.getDataLayout()), 6166 getValue(I.getArgOperand(0)))); 6167 return; 6168 case Intrinsic::eh_sjlj_callsite: { 6169 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6170 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6171 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6172 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6173 6174 MMI.setCurrentCallSite(CI->getZExtValue()); 6175 return; 6176 } 6177 case Intrinsic::eh_sjlj_functioncontext: { 6178 // Get and store the index of the function context. 6179 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6180 AllocaInst *FnCtx = 6181 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6182 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6183 MFI.setFunctionContextIndex(FI); 6184 return; 6185 } 6186 case Intrinsic::eh_sjlj_setjmp: { 6187 SDValue Ops[2]; 6188 Ops[0] = getRoot(); 6189 Ops[1] = getValue(I.getArgOperand(0)); 6190 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6191 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6192 setValue(&I, Op.getValue(0)); 6193 DAG.setRoot(Op.getValue(1)); 6194 return; 6195 } 6196 case Intrinsic::eh_sjlj_longjmp: 6197 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6198 getRoot(), getValue(I.getArgOperand(0)))); 6199 return; 6200 case Intrinsic::eh_sjlj_setup_dispatch: 6201 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6202 getRoot())); 6203 return; 6204 case Intrinsic::masked_gather: 6205 visitMaskedGather(I); 6206 return; 6207 case Intrinsic::masked_load: 6208 visitMaskedLoad(I); 6209 return; 6210 case Intrinsic::masked_scatter: 6211 visitMaskedScatter(I); 6212 return; 6213 case Intrinsic::masked_store: 6214 visitMaskedStore(I); 6215 return; 6216 case Intrinsic::masked_expandload: 6217 visitMaskedLoad(I, true /* IsExpanding */); 6218 return; 6219 case Intrinsic::masked_compressstore: 6220 visitMaskedStore(I, true /* IsCompressing */); 6221 return; 6222 case Intrinsic::powi: 6223 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6224 getValue(I.getArgOperand(1)), DAG)); 6225 return; 6226 case Intrinsic::log: 6227 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6228 return; 6229 case Intrinsic::log2: 6230 setValue(&I, 6231 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6232 return; 6233 case Intrinsic::log10: 6234 setValue(&I, 6235 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6236 return; 6237 case Intrinsic::exp: 6238 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6239 return; 6240 case Intrinsic::exp2: 6241 setValue(&I, 6242 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6243 return; 6244 case Intrinsic::pow: 6245 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6246 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6247 return; 6248 case Intrinsic::sqrt: 6249 case Intrinsic::fabs: 6250 case Intrinsic::sin: 6251 case Intrinsic::cos: 6252 case Intrinsic::floor: 6253 case Intrinsic::ceil: 6254 case Intrinsic::trunc: 6255 case Intrinsic::rint: 6256 case Intrinsic::nearbyint: 6257 case Intrinsic::round: 6258 case Intrinsic::roundeven: 6259 case Intrinsic::canonicalize: { 6260 unsigned Opcode; 6261 switch (Intrinsic) { 6262 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6263 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6264 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6265 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6266 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6267 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6268 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6269 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6270 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6271 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6272 case Intrinsic::round: Opcode = ISD::FROUND; break; 6273 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6274 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6275 } 6276 6277 setValue(&I, DAG.getNode(Opcode, sdl, 6278 getValue(I.getArgOperand(0)).getValueType(), 6279 getValue(I.getArgOperand(0)), Flags)); 6280 return; 6281 } 6282 case Intrinsic::lround: 6283 case Intrinsic::llround: 6284 case Intrinsic::lrint: 6285 case Intrinsic::llrint: { 6286 unsigned Opcode; 6287 switch (Intrinsic) { 6288 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6289 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6290 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6291 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6292 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6293 } 6294 6295 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6296 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6297 getValue(I.getArgOperand(0)))); 6298 return; 6299 } 6300 case Intrinsic::minnum: 6301 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6302 getValue(I.getArgOperand(0)).getValueType(), 6303 getValue(I.getArgOperand(0)), 6304 getValue(I.getArgOperand(1)), Flags)); 6305 return; 6306 case Intrinsic::maxnum: 6307 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6308 getValue(I.getArgOperand(0)).getValueType(), 6309 getValue(I.getArgOperand(0)), 6310 getValue(I.getArgOperand(1)), Flags)); 6311 return; 6312 case Intrinsic::minimum: 6313 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6314 getValue(I.getArgOperand(0)).getValueType(), 6315 getValue(I.getArgOperand(0)), 6316 getValue(I.getArgOperand(1)), Flags)); 6317 return; 6318 case Intrinsic::maximum: 6319 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6320 getValue(I.getArgOperand(0)).getValueType(), 6321 getValue(I.getArgOperand(0)), 6322 getValue(I.getArgOperand(1)), Flags)); 6323 return; 6324 case Intrinsic::copysign: 6325 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6326 getValue(I.getArgOperand(0)).getValueType(), 6327 getValue(I.getArgOperand(0)), 6328 getValue(I.getArgOperand(1)), Flags)); 6329 return; 6330 case Intrinsic::arithmetic_fence: { 6331 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6332 getValue(I.getArgOperand(0)).getValueType(), 6333 getValue(I.getArgOperand(0)), Flags)); 6334 return; 6335 } 6336 case Intrinsic::fma: 6337 setValue(&I, DAG.getNode( 6338 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6339 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6340 getValue(I.getArgOperand(2)), Flags)); 6341 return; 6342 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6343 case Intrinsic::INTRINSIC: 6344 #include "llvm/IR/ConstrainedOps.def" 6345 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6346 return; 6347 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6348 #include "llvm/IR/VPIntrinsics.def" 6349 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6350 return; 6351 case Intrinsic::fmuladd: { 6352 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6353 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6354 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6355 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6356 getValue(I.getArgOperand(0)).getValueType(), 6357 getValue(I.getArgOperand(0)), 6358 getValue(I.getArgOperand(1)), 6359 getValue(I.getArgOperand(2)), Flags)); 6360 } else { 6361 // TODO: Intrinsic calls should have fast-math-flags. 6362 SDValue Mul = DAG.getNode( 6363 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6364 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6365 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6366 getValue(I.getArgOperand(0)).getValueType(), 6367 Mul, getValue(I.getArgOperand(2)), Flags); 6368 setValue(&I, Add); 6369 } 6370 return; 6371 } 6372 case Intrinsic::convert_to_fp16: 6373 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6374 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6375 getValue(I.getArgOperand(0)), 6376 DAG.getTargetConstant(0, sdl, 6377 MVT::i32)))); 6378 return; 6379 case Intrinsic::convert_from_fp16: 6380 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6381 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6382 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6383 getValue(I.getArgOperand(0))))); 6384 return; 6385 case Intrinsic::fptosi_sat: { 6386 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6387 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6388 getValue(I.getArgOperand(0)), 6389 DAG.getValueType(VT.getScalarType()))); 6390 return; 6391 } 6392 case Intrinsic::fptoui_sat: { 6393 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6394 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6395 getValue(I.getArgOperand(0)), 6396 DAG.getValueType(VT.getScalarType()))); 6397 return; 6398 } 6399 case Intrinsic::set_rounding: 6400 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6401 {getRoot(), getValue(I.getArgOperand(0))}); 6402 setValue(&I, Res); 6403 DAG.setRoot(Res.getValue(0)); 6404 return; 6405 case Intrinsic::pcmarker: { 6406 SDValue Tmp = getValue(I.getArgOperand(0)); 6407 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6408 return; 6409 } 6410 case Intrinsic::isnan: { 6411 const DataLayout DLayout = DAG.getDataLayout(); 6412 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6413 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6414 MachineFunction &MF = DAG.getMachineFunction(); 6415 const Function &F = MF.getFunction(); 6416 SDValue Op = getValue(I.getArgOperand(0)); 6417 SDNodeFlags Flags; 6418 Flags.setNoFPExcept( 6419 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6420 6421 // If ISD::ISNAN should be expanded, do it right now, because the expansion 6422 // can use illegal types. Making expansion early allows to legalize these 6423 // types prior to selection. 6424 if (!TLI.isOperationLegalOrCustom(ISD::ISNAN, ArgVT)) { 6425 SDValue Result = TLI.expandISNAN(DestVT, Op, Flags, sdl, DAG); 6426 setValue(&I, Result); 6427 return; 6428 } 6429 6430 SDValue V = DAG.getNode(ISD::ISNAN, sdl, DestVT, Op, Flags); 6431 setValue(&I, V); 6432 return; 6433 } 6434 case Intrinsic::readcyclecounter: { 6435 SDValue Op = getRoot(); 6436 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6437 DAG.getVTList(MVT::i64, MVT::Other), Op); 6438 setValue(&I, Res); 6439 DAG.setRoot(Res.getValue(1)); 6440 return; 6441 } 6442 case Intrinsic::bitreverse: 6443 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6444 getValue(I.getArgOperand(0)).getValueType(), 6445 getValue(I.getArgOperand(0)))); 6446 return; 6447 case Intrinsic::bswap: 6448 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6449 getValue(I.getArgOperand(0)).getValueType(), 6450 getValue(I.getArgOperand(0)))); 6451 return; 6452 case Intrinsic::cttz: { 6453 SDValue Arg = getValue(I.getArgOperand(0)); 6454 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6455 EVT Ty = Arg.getValueType(); 6456 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6457 sdl, Ty, Arg)); 6458 return; 6459 } 6460 case Intrinsic::ctlz: { 6461 SDValue Arg = getValue(I.getArgOperand(0)); 6462 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6463 EVT Ty = Arg.getValueType(); 6464 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6465 sdl, Ty, Arg)); 6466 return; 6467 } 6468 case Intrinsic::ctpop: { 6469 SDValue Arg = getValue(I.getArgOperand(0)); 6470 EVT Ty = Arg.getValueType(); 6471 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6472 return; 6473 } 6474 case Intrinsic::fshl: 6475 case Intrinsic::fshr: { 6476 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6477 SDValue X = getValue(I.getArgOperand(0)); 6478 SDValue Y = getValue(I.getArgOperand(1)); 6479 SDValue Z = getValue(I.getArgOperand(2)); 6480 EVT VT = X.getValueType(); 6481 6482 if (X == Y) { 6483 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6484 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6485 } else { 6486 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6487 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6488 } 6489 return; 6490 } 6491 case Intrinsic::sadd_sat: { 6492 SDValue Op1 = getValue(I.getArgOperand(0)); 6493 SDValue Op2 = getValue(I.getArgOperand(1)); 6494 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6495 return; 6496 } 6497 case Intrinsic::uadd_sat: { 6498 SDValue Op1 = getValue(I.getArgOperand(0)); 6499 SDValue Op2 = getValue(I.getArgOperand(1)); 6500 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6501 return; 6502 } 6503 case Intrinsic::ssub_sat: { 6504 SDValue Op1 = getValue(I.getArgOperand(0)); 6505 SDValue Op2 = getValue(I.getArgOperand(1)); 6506 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6507 return; 6508 } 6509 case Intrinsic::usub_sat: { 6510 SDValue Op1 = getValue(I.getArgOperand(0)); 6511 SDValue Op2 = getValue(I.getArgOperand(1)); 6512 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6513 return; 6514 } 6515 case Intrinsic::sshl_sat: { 6516 SDValue Op1 = getValue(I.getArgOperand(0)); 6517 SDValue Op2 = getValue(I.getArgOperand(1)); 6518 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6519 return; 6520 } 6521 case Intrinsic::ushl_sat: { 6522 SDValue Op1 = getValue(I.getArgOperand(0)); 6523 SDValue Op2 = getValue(I.getArgOperand(1)); 6524 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6525 return; 6526 } 6527 case Intrinsic::smul_fix: 6528 case Intrinsic::umul_fix: 6529 case Intrinsic::smul_fix_sat: 6530 case Intrinsic::umul_fix_sat: { 6531 SDValue Op1 = getValue(I.getArgOperand(0)); 6532 SDValue Op2 = getValue(I.getArgOperand(1)); 6533 SDValue Op3 = getValue(I.getArgOperand(2)); 6534 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6535 Op1.getValueType(), Op1, Op2, Op3)); 6536 return; 6537 } 6538 case Intrinsic::sdiv_fix: 6539 case Intrinsic::udiv_fix: 6540 case Intrinsic::sdiv_fix_sat: 6541 case Intrinsic::udiv_fix_sat: { 6542 SDValue Op1 = getValue(I.getArgOperand(0)); 6543 SDValue Op2 = getValue(I.getArgOperand(1)); 6544 SDValue Op3 = getValue(I.getArgOperand(2)); 6545 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6546 Op1, Op2, Op3, DAG, TLI)); 6547 return; 6548 } 6549 case Intrinsic::smax: { 6550 SDValue Op1 = getValue(I.getArgOperand(0)); 6551 SDValue Op2 = getValue(I.getArgOperand(1)); 6552 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6553 return; 6554 } 6555 case Intrinsic::smin: { 6556 SDValue Op1 = getValue(I.getArgOperand(0)); 6557 SDValue Op2 = getValue(I.getArgOperand(1)); 6558 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6559 return; 6560 } 6561 case Intrinsic::umax: { 6562 SDValue Op1 = getValue(I.getArgOperand(0)); 6563 SDValue Op2 = getValue(I.getArgOperand(1)); 6564 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6565 return; 6566 } 6567 case Intrinsic::umin: { 6568 SDValue Op1 = getValue(I.getArgOperand(0)); 6569 SDValue Op2 = getValue(I.getArgOperand(1)); 6570 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6571 return; 6572 } 6573 case Intrinsic::abs: { 6574 // TODO: Preserve "int min is poison" arg in SDAG? 6575 SDValue Op1 = getValue(I.getArgOperand(0)); 6576 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6577 return; 6578 } 6579 case Intrinsic::stacksave: { 6580 SDValue Op = getRoot(); 6581 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6582 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6583 setValue(&I, Res); 6584 DAG.setRoot(Res.getValue(1)); 6585 return; 6586 } 6587 case Intrinsic::stackrestore: 6588 Res = getValue(I.getArgOperand(0)); 6589 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6590 return; 6591 case Intrinsic::get_dynamic_area_offset: { 6592 SDValue Op = getRoot(); 6593 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6594 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6595 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6596 // target. 6597 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6598 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6599 " intrinsic!"); 6600 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6601 Op); 6602 DAG.setRoot(Op); 6603 setValue(&I, Res); 6604 return; 6605 } 6606 case Intrinsic::stackguard: { 6607 MachineFunction &MF = DAG.getMachineFunction(); 6608 const Module &M = *MF.getFunction().getParent(); 6609 SDValue Chain = getRoot(); 6610 if (TLI.useLoadStackGuardNode()) { 6611 Res = getLoadStackGuard(DAG, sdl, Chain); 6612 } else { 6613 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6614 const Value *Global = TLI.getSDagStackGuard(M); 6615 Align Align = DL->getPrefTypeAlign(Global->getType()); 6616 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6617 MachinePointerInfo(Global, 0), Align, 6618 MachineMemOperand::MOVolatile); 6619 } 6620 if (TLI.useStackGuardXorFP()) 6621 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6622 DAG.setRoot(Chain); 6623 setValue(&I, Res); 6624 return; 6625 } 6626 case Intrinsic::stackprotector: { 6627 // Emit code into the DAG to store the stack guard onto the stack. 6628 MachineFunction &MF = DAG.getMachineFunction(); 6629 MachineFrameInfo &MFI = MF.getFrameInfo(); 6630 SDValue Src, Chain = getRoot(); 6631 6632 if (TLI.useLoadStackGuardNode()) 6633 Src = getLoadStackGuard(DAG, sdl, Chain); 6634 else 6635 Src = getValue(I.getArgOperand(0)); // The guard's value. 6636 6637 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6638 6639 int FI = FuncInfo.StaticAllocaMap[Slot]; 6640 MFI.setStackProtectorIndex(FI); 6641 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6642 6643 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6644 6645 // Store the stack protector onto the stack. 6646 Res = DAG.getStore( 6647 Chain, sdl, Src, FIN, 6648 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6649 MaybeAlign(), MachineMemOperand::MOVolatile); 6650 setValue(&I, Res); 6651 DAG.setRoot(Res); 6652 return; 6653 } 6654 case Intrinsic::objectsize: 6655 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6656 6657 case Intrinsic::is_constant: 6658 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6659 6660 case Intrinsic::annotation: 6661 case Intrinsic::ptr_annotation: 6662 case Intrinsic::launder_invariant_group: 6663 case Intrinsic::strip_invariant_group: 6664 // Drop the intrinsic, but forward the value 6665 setValue(&I, getValue(I.getOperand(0))); 6666 return; 6667 6668 case Intrinsic::assume: 6669 case Intrinsic::experimental_noalias_scope_decl: 6670 case Intrinsic::var_annotation: 6671 case Intrinsic::sideeffect: 6672 // Discard annotate attributes, noalias scope declarations, assumptions, and 6673 // artificial side-effects. 6674 return; 6675 6676 case Intrinsic::codeview_annotation: { 6677 // Emit a label associated with this metadata. 6678 MachineFunction &MF = DAG.getMachineFunction(); 6679 MCSymbol *Label = 6680 MF.getMMI().getContext().createTempSymbol("annotation", true); 6681 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6682 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6683 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6684 DAG.setRoot(Res); 6685 return; 6686 } 6687 6688 case Intrinsic::init_trampoline: { 6689 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6690 6691 SDValue Ops[6]; 6692 Ops[0] = getRoot(); 6693 Ops[1] = getValue(I.getArgOperand(0)); 6694 Ops[2] = getValue(I.getArgOperand(1)); 6695 Ops[3] = getValue(I.getArgOperand(2)); 6696 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6697 Ops[5] = DAG.getSrcValue(F); 6698 6699 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6700 6701 DAG.setRoot(Res); 6702 return; 6703 } 6704 case Intrinsic::adjust_trampoline: 6705 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6706 TLI.getPointerTy(DAG.getDataLayout()), 6707 getValue(I.getArgOperand(0)))); 6708 return; 6709 case Intrinsic::gcroot: { 6710 assert(DAG.getMachineFunction().getFunction().hasGC() && 6711 "only valid in functions with gc specified, enforced by Verifier"); 6712 assert(GFI && "implied by previous"); 6713 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6714 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6715 6716 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6717 GFI->addStackRoot(FI->getIndex(), TypeMap); 6718 return; 6719 } 6720 case Intrinsic::gcread: 6721 case Intrinsic::gcwrite: 6722 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6723 case Intrinsic::flt_rounds: 6724 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6725 setValue(&I, Res); 6726 DAG.setRoot(Res.getValue(1)); 6727 return; 6728 6729 case Intrinsic::expect: 6730 // Just replace __builtin_expect(exp, c) with EXP. 6731 setValue(&I, getValue(I.getArgOperand(0))); 6732 return; 6733 6734 case Intrinsic::ubsantrap: 6735 case Intrinsic::debugtrap: 6736 case Intrinsic::trap: { 6737 StringRef TrapFuncName = 6738 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6739 if (TrapFuncName.empty()) { 6740 switch (Intrinsic) { 6741 case Intrinsic::trap: 6742 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6743 break; 6744 case Intrinsic::debugtrap: 6745 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6746 break; 6747 case Intrinsic::ubsantrap: 6748 DAG.setRoot(DAG.getNode( 6749 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6750 DAG.getTargetConstant( 6751 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6752 MVT::i32))); 6753 break; 6754 default: llvm_unreachable("unknown trap intrinsic"); 6755 } 6756 return; 6757 } 6758 TargetLowering::ArgListTy Args; 6759 if (Intrinsic == Intrinsic::ubsantrap) { 6760 Args.push_back(TargetLoweringBase::ArgListEntry()); 6761 Args[0].Val = I.getArgOperand(0); 6762 Args[0].Node = getValue(Args[0].Val); 6763 Args[0].Ty = Args[0].Val->getType(); 6764 } 6765 6766 TargetLowering::CallLoweringInfo CLI(DAG); 6767 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6768 CallingConv::C, I.getType(), 6769 DAG.getExternalSymbol(TrapFuncName.data(), 6770 TLI.getPointerTy(DAG.getDataLayout())), 6771 std::move(Args)); 6772 6773 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6774 DAG.setRoot(Result.second); 6775 return; 6776 } 6777 6778 case Intrinsic::uadd_with_overflow: 6779 case Intrinsic::sadd_with_overflow: 6780 case Intrinsic::usub_with_overflow: 6781 case Intrinsic::ssub_with_overflow: 6782 case Intrinsic::umul_with_overflow: 6783 case Intrinsic::smul_with_overflow: { 6784 ISD::NodeType Op; 6785 switch (Intrinsic) { 6786 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6787 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6788 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6789 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6790 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6791 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6792 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6793 } 6794 SDValue Op1 = getValue(I.getArgOperand(0)); 6795 SDValue Op2 = getValue(I.getArgOperand(1)); 6796 6797 EVT ResultVT = Op1.getValueType(); 6798 EVT OverflowVT = MVT::i1; 6799 if (ResultVT.isVector()) 6800 OverflowVT = EVT::getVectorVT( 6801 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6802 6803 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6804 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6805 return; 6806 } 6807 case Intrinsic::prefetch: { 6808 SDValue Ops[5]; 6809 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6810 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6811 Ops[0] = DAG.getRoot(); 6812 Ops[1] = getValue(I.getArgOperand(0)); 6813 Ops[2] = getValue(I.getArgOperand(1)); 6814 Ops[3] = getValue(I.getArgOperand(2)); 6815 Ops[4] = getValue(I.getArgOperand(3)); 6816 SDValue Result = DAG.getMemIntrinsicNode( 6817 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6818 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6819 /* align */ None, Flags); 6820 6821 // Chain the prefetch in parallell with any pending loads, to stay out of 6822 // the way of later optimizations. 6823 PendingLoads.push_back(Result); 6824 Result = getRoot(); 6825 DAG.setRoot(Result); 6826 return; 6827 } 6828 case Intrinsic::lifetime_start: 6829 case Intrinsic::lifetime_end: { 6830 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6831 // Stack coloring is not enabled in O0, discard region information. 6832 if (TM.getOptLevel() == CodeGenOpt::None) 6833 return; 6834 6835 const int64_t ObjectSize = 6836 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6837 Value *const ObjectPtr = I.getArgOperand(1); 6838 SmallVector<const Value *, 4> Allocas; 6839 getUnderlyingObjects(ObjectPtr, Allocas); 6840 6841 for (const Value *Alloca : Allocas) { 6842 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6843 6844 // Could not find an Alloca. 6845 if (!LifetimeObject) 6846 continue; 6847 6848 // First check that the Alloca is static, otherwise it won't have a 6849 // valid frame index. 6850 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6851 if (SI == FuncInfo.StaticAllocaMap.end()) 6852 return; 6853 6854 const int FrameIndex = SI->second; 6855 int64_t Offset; 6856 if (GetPointerBaseWithConstantOffset( 6857 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6858 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6859 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6860 Offset); 6861 DAG.setRoot(Res); 6862 } 6863 return; 6864 } 6865 case Intrinsic::pseudoprobe: { 6866 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6867 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6868 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6869 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6870 DAG.setRoot(Res); 6871 return; 6872 } 6873 case Intrinsic::invariant_start: 6874 // Discard region information. 6875 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6876 return; 6877 case Intrinsic::invariant_end: 6878 // Discard region information. 6879 return; 6880 case Intrinsic::clear_cache: 6881 /// FunctionName may be null. 6882 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6883 lowerCallToExternalSymbol(I, FunctionName); 6884 return; 6885 case Intrinsic::donothing: 6886 case Intrinsic::seh_try_begin: 6887 case Intrinsic::seh_scope_begin: 6888 case Intrinsic::seh_try_end: 6889 case Intrinsic::seh_scope_end: 6890 // ignore 6891 return; 6892 case Intrinsic::experimental_stackmap: 6893 visitStackmap(I); 6894 return; 6895 case Intrinsic::experimental_patchpoint_void: 6896 case Intrinsic::experimental_patchpoint_i64: 6897 visitPatchpoint(I); 6898 return; 6899 case Intrinsic::experimental_gc_statepoint: 6900 LowerStatepoint(cast<GCStatepointInst>(I)); 6901 return; 6902 case Intrinsic::experimental_gc_result: 6903 visitGCResult(cast<GCResultInst>(I)); 6904 return; 6905 case Intrinsic::experimental_gc_relocate: 6906 visitGCRelocate(cast<GCRelocateInst>(I)); 6907 return; 6908 case Intrinsic::instrprof_increment: 6909 llvm_unreachable("instrprof failed to lower an increment"); 6910 case Intrinsic::instrprof_value_profile: 6911 llvm_unreachable("instrprof failed to lower a value profiling call"); 6912 case Intrinsic::localescape: { 6913 MachineFunction &MF = DAG.getMachineFunction(); 6914 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6915 6916 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6917 // is the same on all targets. 6918 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6919 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6920 if (isa<ConstantPointerNull>(Arg)) 6921 continue; // Skip null pointers. They represent a hole in index space. 6922 AllocaInst *Slot = cast<AllocaInst>(Arg); 6923 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6924 "can only escape static allocas"); 6925 int FI = FuncInfo.StaticAllocaMap[Slot]; 6926 MCSymbol *FrameAllocSym = 6927 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6928 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6929 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6930 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6931 .addSym(FrameAllocSym) 6932 .addFrameIndex(FI); 6933 } 6934 6935 return; 6936 } 6937 6938 case Intrinsic::localrecover: { 6939 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6940 MachineFunction &MF = DAG.getMachineFunction(); 6941 6942 // Get the symbol that defines the frame offset. 6943 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6944 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6945 unsigned IdxVal = 6946 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6947 MCSymbol *FrameAllocSym = 6948 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6949 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6950 6951 Value *FP = I.getArgOperand(1); 6952 SDValue FPVal = getValue(FP); 6953 EVT PtrVT = FPVal.getValueType(); 6954 6955 // Create a MCSymbol for the label to avoid any target lowering 6956 // that would make this PC relative. 6957 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6958 SDValue OffsetVal = 6959 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6960 6961 // Add the offset to the FP. 6962 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6963 setValue(&I, Add); 6964 6965 return; 6966 } 6967 6968 case Intrinsic::eh_exceptionpointer: 6969 case Intrinsic::eh_exceptioncode: { 6970 // Get the exception pointer vreg, copy from it, and resize it to fit. 6971 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6972 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6973 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6974 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6975 SDValue N = 6976 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6977 if (Intrinsic == Intrinsic::eh_exceptioncode) 6978 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6979 setValue(&I, N); 6980 return; 6981 } 6982 case Intrinsic::xray_customevent: { 6983 // Here we want to make sure that the intrinsic behaves as if it has a 6984 // specific calling convention, and only for x86_64. 6985 // FIXME: Support other platforms later. 6986 const auto &Triple = DAG.getTarget().getTargetTriple(); 6987 if (Triple.getArch() != Triple::x86_64) 6988 return; 6989 6990 SDLoc DL = getCurSDLoc(); 6991 SmallVector<SDValue, 8> Ops; 6992 6993 // We want to say that we always want the arguments in registers. 6994 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6995 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6996 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6997 SDValue Chain = getRoot(); 6998 Ops.push_back(LogEntryVal); 6999 Ops.push_back(StrSizeVal); 7000 Ops.push_back(Chain); 7001 7002 // We need to enforce the calling convention for the callsite, so that 7003 // argument ordering is enforced correctly, and that register allocation can 7004 // see that some registers may be assumed clobbered and have to preserve 7005 // them across calls to the intrinsic. 7006 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7007 DL, NodeTys, Ops); 7008 SDValue patchableNode = SDValue(MN, 0); 7009 DAG.setRoot(patchableNode); 7010 setValue(&I, patchableNode); 7011 return; 7012 } 7013 case Intrinsic::xray_typedevent: { 7014 // Here we want to make sure that the intrinsic behaves as if it has a 7015 // specific calling convention, and only for x86_64. 7016 // FIXME: Support other platforms later. 7017 const auto &Triple = DAG.getTarget().getTargetTriple(); 7018 if (Triple.getArch() != Triple::x86_64) 7019 return; 7020 7021 SDLoc DL = getCurSDLoc(); 7022 SmallVector<SDValue, 8> Ops; 7023 7024 // We want to say that we always want the arguments in registers. 7025 // It's unclear to me how manipulating the selection DAG here forces callers 7026 // to provide arguments in registers instead of on the stack. 7027 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7028 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7029 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7030 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7031 SDValue Chain = getRoot(); 7032 Ops.push_back(LogTypeId); 7033 Ops.push_back(LogEntryVal); 7034 Ops.push_back(StrSizeVal); 7035 Ops.push_back(Chain); 7036 7037 // We need to enforce the calling convention for the callsite, so that 7038 // argument ordering is enforced correctly, and that register allocation can 7039 // see that some registers may be assumed clobbered and have to preserve 7040 // them across calls to the intrinsic. 7041 MachineSDNode *MN = DAG.getMachineNode( 7042 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 7043 SDValue patchableNode = SDValue(MN, 0); 7044 DAG.setRoot(patchableNode); 7045 setValue(&I, patchableNode); 7046 return; 7047 } 7048 case Intrinsic::experimental_deoptimize: 7049 LowerDeoptimizeCall(&I); 7050 return; 7051 case Intrinsic::experimental_stepvector: 7052 visitStepVector(I); 7053 return; 7054 case Intrinsic::vector_reduce_fadd: 7055 case Intrinsic::vector_reduce_fmul: 7056 case Intrinsic::vector_reduce_add: 7057 case Intrinsic::vector_reduce_mul: 7058 case Intrinsic::vector_reduce_and: 7059 case Intrinsic::vector_reduce_or: 7060 case Intrinsic::vector_reduce_xor: 7061 case Intrinsic::vector_reduce_smax: 7062 case Intrinsic::vector_reduce_smin: 7063 case Intrinsic::vector_reduce_umax: 7064 case Intrinsic::vector_reduce_umin: 7065 case Intrinsic::vector_reduce_fmax: 7066 case Intrinsic::vector_reduce_fmin: 7067 visitVectorReduce(I, Intrinsic); 7068 return; 7069 7070 case Intrinsic::icall_branch_funnel: { 7071 SmallVector<SDValue, 16> Ops; 7072 Ops.push_back(getValue(I.getArgOperand(0))); 7073 7074 int64_t Offset; 7075 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7076 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7077 if (!Base) 7078 report_fatal_error( 7079 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7080 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 7081 7082 struct BranchFunnelTarget { 7083 int64_t Offset; 7084 SDValue Target; 7085 }; 7086 SmallVector<BranchFunnelTarget, 8> Targets; 7087 7088 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 7089 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7090 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7091 if (ElemBase != Base) 7092 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7093 "to the same GlobalValue"); 7094 7095 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7096 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7097 if (!GA) 7098 report_fatal_error( 7099 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7100 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7101 GA->getGlobal(), getCurSDLoc(), 7102 Val.getValueType(), GA->getOffset())}); 7103 } 7104 llvm::sort(Targets, 7105 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7106 return T1.Offset < T2.Offset; 7107 }); 7108 7109 for (auto &T : Targets) { 7110 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7111 Ops.push_back(T.Target); 7112 } 7113 7114 Ops.push_back(DAG.getRoot()); // Chain 7115 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7116 getCurSDLoc(), MVT::Other, Ops), 7117 0); 7118 DAG.setRoot(N); 7119 setValue(&I, N); 7120 HasTailCall = true; 7121 return; 7122 } 7123 7124 case Intrinsic::wasm_landingpad_index: 7125 // Information this intrinsic contained has been transferred to 7126 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7127 // delete it now. 7128 return; 7129 7130 case Intrinsic::aarch64_settag: 7131 case Intrinsic::aarch64_settag_zero: { 7132 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7133 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7134 SDValue Val = TSI.EmitTargetCodeForSetTag( 7135 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7136 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7137 ZeroMemory); 7138 DAG.setRoot(Val); 7139 setValue(&I, Val); 7140 return; 7141 } 7142 case Intrinsic::ptrmask: { 7143 SDValue Ptr = getValue(I.getOperand(0)); 7144 SDValue Const = getValue(I.getOperand(1)); 7145 7146 EVT PtrVT = Ptr.getValueType(); 7147 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7148 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7149 return; 7150 } 7151 case Intrinsic::get_active_lane_mask: { 7152 auto DL = getCurSDLoc(); 7153 SDValue Index = getValue(I.getOperand(0)); 7154 SDValue TripCount = getValue(I.getOperand(1)); 7155 Type *ElementTy = I.getOperand(0)->getType(); 7156 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7157 unsigned VecWidth = VT.getVectorNumElements(); 7158 7159 SmallVector<SDValue, 16> OpsTripCount; 7160 SmallVector<SDValue, 16> OpsIndex; 7161 SmallVector<SDValue, 16> OpsStepConstants; 7162 for (unsigned i = 0; i < VecWidth; i++) { 7163 OpsTripCount.push_back(TripCount); 7164 OpsIndex.push_back(Index); 7165 OpsStepConstants.push_back( 7166 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7167 } 7168 7169 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7170 7171 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7172 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7173 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7174 SDValue VectorInduction = DAG.getNode( 7175 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7176 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7177 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7178 VectorTripCount, ISD::CondCode::SETULT); 7179 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7180 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7181 SetCC)); 7182 return; 7183 } 7184 case Intrinsic::experimental_vector_insert: { 7185 auto DL = getCurSDLoc(); 7186 7187 SDValue Vec = getValue(I.getOperand(0)); 7188 SDValue SubVec = getValue(I.getOperand(1)); 7189 SDValue Index = getValue(I.getOperand(2)); 7190 7191 // The intrinsic's index type is i64, but the SDNode requires an index type 7192 // suitable for the target. Convert the index as required. 7193 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7194 if (Index.getValueType() != VectorIdxTy) 7195 Index = DAG.getVectorIdxConstant( 7196 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7197 7198 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7199 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7200 Index)); 7201 return; 7202 } 7203 case Intrinsic::experimental_vector_extract: { 7204 auto DL = getCurSDLoc(); 7205 7206 SDValue Vec = getValue(I.getOperand(0)); 7207 SDValue Index = getValue(I.getOperand(1)); 7208 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7209 7210 // The intrinsic's index type is i64, but the SDNode requires an index type 7211 // suitable for the target. Convert the index as required. 7212 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7213 if (Index.getValueType() != VectorIdxTy) 7214 Index = DAG.getVectorIdxConstant( 7215 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7216 7217 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7218 return; 7219 } 7220 case Intrinsic::experimental_vector_reverse: 7221 visitVectorReverse(I); 7222 return; 7223 case Intrinsic::experimental_vector_splice: 7224 visitVectorSplice(I); 7225 return; 7226 } 7227 } 7228 7229 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7230 const ConstrainedFPIntrinsic &FPI) { 7231 SDLoc sdl = getCurSDLoc(); 7232 7233 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7234 SmallVector<EVT, 4> ValueVTs; 7235 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7236 ValueVTs.push_back(MVT::Other); // Out chain 7237 7238 // We do not need to serialize constrained FP intrinsics against 7239 // each other or against (nonvolatile) loads, so they can be 7240 // chained like loads. 7241 SDValue Chain = DAG.getRoot(); 7242 SmallVector<SDValue, 4> Opers; 7243 Opers.push_back(Chain); 7244 if (FPI.isUnaryOp()) { 7245 Opers.push_back(getValue(FPI.getArgOperand(0))); 7246 } else if (FPI.isTernaryOp()) { 7247 Opers.push_back(getValue(FPI.getArgOperand(0))); 7248 Opers.push_back(getValue(FPI.getArgOperand(1))); 7249 Opers.push_back(getValue(FPI.getArgOperand(2))); 7250 } else { 7251 Opers.push_back(getValue(FPI.getArgOperand(0))); 7252 Opers.push_back(getValue(FPI.getArgOperand(1))); 7253 } 7254 7255 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7256 assert(Result.getNode()->getNumValues() == 2); 7257 7258 // Push node to the appropriate list so that future instructions can be 7259 // chained up correctly. 7260 SDValue OutChain = Result.getValue(1); 7261 switch (EB) { 7262 case fp::ExceptionBehavior::ebIgnore: 7263 // The only reason why ebIgnore nodes still need to be chained is that 7264 // they might depend on the current rounding mode, and therefore must 7265 // not be moved across instruction that may change that mode. 7266 LLVM_FALLTHROUGH; 7267 case fp::ExceptionBehavior::ebMayTrap: 7268 // These must not be moved across calls or instructions that may change 7269 // floating-point exception masks. 7270 PendingConstrainedFP.push_back(OutChain); 7271 break; 7272 case fp::ExceptionBehavior::ebStrict: 7273 // These must not be moved across calls or instructions that may change 7274 // floating-point exception masks or read floating-point exception flags. 7275 // In addition, they cannot be optimized out even if unused. 7276 PendingConstrainedFPStrict.push_back(OutChain); 7277 break; 7278 } 7279 }; 7280 7281 SDVTList VTs = DAG.getVTList(ValueVTs); 7282 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7283 7284 SDNodeFlags Flags; 7285 if (EB == fp::ExceptionBehavior::ebIgnore) 7286 Flags.setNoFPExcept(true); 7287 7288 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7289 Flags.copyFMF(*FPOp); 7290 7291 unsigned Opcode; 7292 switch (FPI.getIntrinsicID()) { 7293 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7294 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7295 case Intrinsic::INTRINSIC: \ 7296 Opcode = ISD::STRICT_##DAGN; \ 7297 break; 7298 #include "llvm/IR/ConstrainedOps.def" 7299 case Intrinsic::experimental_constrained_fmuladd: { 7300 Opcode = ISD::STRICT_FMA; 7301 // Break fmuladd into fmul and fadd. 7302 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7303 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7304 ValueVTs[0])) { 7305 Opers.pop_back(); 7306 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7307 pushOutChain(Mul, EB); 7308 Opcode = ISD::STRICT_FADD; 7309 Opers.clear(); 7310 Opers.push_back(Mul.getValue(1)); 7311 Opers.push_back(Mul.getValue(0)); 7312 Opers.push_back(getValue(FPI.getArgOperand(2))); 7313 } 7314 break; 7315 } 7316 } 7317 7318 // A few strict DAG nodes carry additional operands that are not 7319 // set up by the default code above. 7320 switch (Opcode) { 7321 default: break; 7322 case ISD::STRICT_FP_ROUND: 7323 Opers.push_back( 7324 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7325 break; 7326 case ISD::STRICT_FSETCC: 7327 case ISD::STRICT_FSETCCS: { 7328 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7329 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7330 if (TM.Options.NoNaNsFPMath) 7331 Condition = getFCmpCodeWithoutNaN(Condition); 7332 Opers.push_back(DAG.getCondCode(Condition)); 7333 break; 7334 } 7335 } 7336 7337 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7338 pushOutChain(Result, EB); 7339 7340 SDValue FPResult = Result.getValue(0); 7341 setValue(&FPI, FPResult); 7342 } 7343 7344 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7345 Optional<unsigned> ResOPC; 7346 switch (VPIntrin.getIntrinsicID()) { 7347 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7348 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7349 #define END_REGISTER_VP_INTRINSIC(...) break; 7350 #include "llvm/IR/VPIntrinsics.def" 7351 } 7352 7353 if (!ResOPC.hasValue()) 7354 llvm_unreachable( 7355 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7356 7357 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7358 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7359 if (VPIntrin.getFastMathFlags().allowReassoc()) 7360 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7361 : ISD::VP_REDUCE_FMUL; 7362 } 7363 7364 return ResOPC.getValue(); 7365 } 7366 7367 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7368 const VPIntrinsic &VPIntrin) { 7369 SDLoc DL = getCurSDLoc(); 7370 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7371 7372 SmallVector<EVT, 4> ValueVTs; 7373 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7374 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7375 SDVTList VTs = DAG.getVTList(ValueVTs); 7376 7377 auto EVLParamPos = 7378 VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID()); 7379 7380 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7381 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7382 "Unexpected target EVL type"); 7383 7384 // Request operands. 7385 SmallVector<SDValue, 7> OpValues; 7386 for (unsigned I = 0; I < VPIntrin.getNumArgOperands(); ++I) { 7387 auto Op = getValue(VPIntrin.getArgOperand(I)); 7388 if (I == EVLParamPos) 7389 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7390 OpValues.push_back(Op); 7391 } 7392 7393 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7394 setValue(&VPIntrin, Result); 7395 } 7396 7397 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7398 const BasicBlock *EHPadBB, 7399 MCSymbol *&BeginLabel) { 7400 MachineFunction &MF = DAG.getMachineFunction(); 7401 MachineModuleInfo &MMI = MF.getMMI(); 7402 7403 // Insert a label before the invoke call to mark the try range. This can be 7404 // used to detect deletion of the invoke via the MachineModuleInfo. 7405 BeginLabel = MMI.getContext().createTempSymbol(); 7406 7407 // For SjLj, keep track of which landing pads go with which invokes 7408 // so as to maintain the ordering of pads in the LSDA. 7409 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7410 if (CallSiteIndex) { 7411 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7412 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7413 7414 // Now that the call site is handled, stop tracking it. 7415 MMI.setCurrentCallSite(0); 7416 } 7417 7418 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7419 } 7420 7421 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7422 const BasicBlock *EHPadBB, 7423 MCSymbol *BeginLabel) { 7424 assert(BeginLabel && "BeginLabel should've been set"); 7425 7426 MachineFunction &MF = DAG.getMachineFunction(); 7427 MachineModuleInfo &MMI = MF.getMMI(); 7428 7429 // Insert a label at the end of the invoke call to mark the try range. This 7430 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7431 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7432 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7433 7434 // Inform MachineModuleInfo of range. 7435 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7436 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7437 // actually use outlined funclets and their LSDA info style. 7438 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7439 assert(II && "II should've been set"); 7440 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7441 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7442 } else if (!isScopedEHPersonality(Pers)) { 7443 assert(EHPadBB); 7444 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7445 } 7446 7447 return Chain; 7448 } 7449 7450 std::pair<SDValue, SDValue> 7451 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7452 const BasicBlock *EHPadBB) { 7453 MCSymbol *BeginLabel = nullptr; 7454 7455 if (EHPadBB) { 7456 // Both PendingLoads and PendingExports must be flushed here; 7457 // this call might not return. 7458 (void)getRoot(); 7459 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7460 CLI.setChain(getRoot()); 7461 } 7462 7463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7464 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7465 7466 assert((CLI.IsTailCall || Result.second.getNode()) && 7467 "Non-null chain expected with non-tail call!"); 7468 assert((Result.second.getNode() || !Result.first.getNode()) && 7469 "Null value expected with tail call!"); 7470 7471 if (!Result.second.getNode()) { 7472 // As a special case, a null chain means that a tail call has been emitted 7473 // and the DAG root is already updated. 7474 HasTailCall = true; 7475 7476 // Since there's no actual continuation from this block, nothing can be 7477 // relying on us setting vregs for them. 7478 PendingExports.clear(); 7479 } else { 7480 DAG.setRoot(Result.second); 7481 } 7482 7483 if (EHPadBB) { 7484 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7485 BeginLabel)); 7486 } 7487 7488 return Result; 7489 } 7490 7491 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7492 bool isTailCall, 7493 bool isMustTailCall, 7494 const BasicBlock *EHPadBB) { 7495 auto &DL = DAG.getDataLayout(); 7496 FunctionType *FTy = CB.getFunctionType(); 7497 Type *RetTy = CB.getType(); 7498 7499 TargetLowering::ArgListTy Args; 7500 Args.reserve(CB.arg_size()); 7501 7502 const Value *SwiftErrorVal = nullptr; 7503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7504 7505 if (isTailCall) { 7506 // Avoid emitting tail calls in functions with the disable-tail-calls 7507 // attribute. 7508 auto *Caller = CB.getParent()->getParent(); 7509 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7510 "true" && !isMustTailCall) 7511 isTailCall = false; 7512 7513 // We can't tail call inside a function with a swifterror argument. Lowering 7514 // does not support this yet. It would have to move into the swifterror 7515 // register before the call. 7516 if (TLI.supportSwiftError() && 7517 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7518 isTailCall = false; 7519 } 7520 7521 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7522 TargetLowering::ArgListEntry Entry; 7523 const Value *V = *I; 7524 7525 // Skip empty types 7526 if (V->getType()->isEmptyTy()) 7527 continue; 7528 7529 SDValue ArgNode = getValue(V); 7530 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7531 7532 Entry.setAttributes(&CB, I - CB.arg_begin()); 7533 7534 // Use swifterror virtual register as input to the call. 7535 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7536 SwiftErrorVal = V; 7537 // We find the virtual register for the actual swifterror argument. 7538 // Instead of using the Value, we use the virtual register instead. 7539 Entry.Node = 7540 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7541 EVT(TLI.getPointerTy(DL))); 7542 } 7543 7544 Args.push_back(Entry); 7545 7546 // If we have an explicit sret argument that is an Instruction, (i.e., it 7547 // might point to function-local memory), we can't meaningfully tail-call. 7548 if (Entry.IsSRet && isa<Instruction>(V)) 7549 isTailCall = false; 7550 } 7551 7552 // If call site has a cfguardtarget operand bundle, create and add an 7553 // additional ArgListEntry. 7554 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7555 TargetLowering::ArgListEntry Entry; 7556 Value *V = Bundle->Inputs[0]; 7557 SDValue ArgNode = getValue(V); 7558 Entry.Node = ArgNode; 7559 Entry.Ty = V->getType(); 7560 Entry.IsCFGuardTarget = true; 7561 Args.push_back(Entry); 7562 } 7563 7564 // Check if target-independent constraints permit a tail call here. 7565 // Target-dependent constraints are checked within TLI->LowerCallTo. 7566 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7567 isTailCall = false; 7568 7569 // Disable tail calls if there is an swifterror argument. Targets have not 7570 // been updated to support tail calls. 7571 if (TLI.supportSwiftError() && SwiftErrorVal) 7572 isTailCall = false; 7573 7574 TargetLowering::CallLoweringInfo CLI(DAG); 7575 CLI.setDebugLoc(getCurSDLoc()) 7576 .setChain(getRoot()) 7577 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7578 .setTailCall(isTailCall) 7579 .setConvergent(CB.isConvergent()) 7580 .setIsPreallocated( 7581 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7582 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7583 7584 if (Result.first.getNode()) { 7585 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7586 setValue(&CB, Result.first); 7587 } 7588 7589 // The last element of CLI.InVals has the SDValue for swifterror return. 7590 // Here we copy it to a virtual register and update SwiftErrorMap for 7591 // book-keeping. 7592 if (SwiftErrorVal && TLI.supportSwiftError()) { 7593 // Get the last element of InVals. 7594 SDValue Src = CLI.InVals.back(); 7595 Register VReg = 7596 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7597 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7598 DAG.setRoot(CopyNode); 7599 } 7600 } 7601 7602 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7603 SelectionDAGBuilder &Builder) { 7604 // Check to see if this load can be trivially constant folded, e.g. if the 7605 // input is from a string literal. 7606 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7607 // Cast pointer to the type we really want to load. 7608 Type *LoadTy = 7609 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7610 if (LoadVT.isVector()) 7611 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7612 7613 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7614 PointerType::getUnqual(LoadTy)); 7615 7616 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7617 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7618 return Builder.getValue(LoadCst); 7619 } 7620 7621 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7622 // still constant memory, the input chain can be the entry node. 7623 SDValue Root; 7624 bool ConstantMemory = false; 7625 7626 // Do not serialize (non-volatile) loads of constant memory with anything. 7627 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7628 Root = Builder.DAG.getEntryNode(); 7629 ConstantMemory = true; 7630 } else { 7631 // Do not serialize non-volatile loads against each other. 7632 Root = Builder.DAG.getRoot(); 7633 } 7634 7635 SDValue Ptr = Builder.getValue(PtrVal); 7636 SDValue LoadVal = 7637 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7638 MachinePointerInfo(PtrVal), Align(1)); 7639 7640 if (!ConstantMemory) 7641 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7642 return LoadVal; 7643 } 7644 7645 /// Record the value for an instruction that produces an integer result, 7646 /// converting the type where necessary. 7647 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7648 SDValue Value, 7649 bool IsSigned) { 7650 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7651 I.getType(), true); 7652 if (IsSigned) 7653 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7654 else 7655 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7656 setValue(&I, Value); 7657 } 7658 7659 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7660 /// true and lower it. Otherwise return false, and it will be lowered like a 7661 /// normal call. 7662 /// The caller already checked that \p I calls the appropriate LibFunc with a 7663 /// correct prototype. 7664 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7665 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7666 const Value *Size = I.getArgOperand(2); 7667 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7668 if (CSize && CSize->getZExtValue() == 0) { 7669 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7670 I.getType(), true); 7671 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7672 return true; 7673 } 7674 7675 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7676 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7677 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7678 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7679 if (Res.first.getNode()) { 7680 processIntegerCallValue(I, Res.first, true); 7681 PendingLoads.push_back(Res.second); 7682 return true; 7683 } 7684 7685 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7686 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7687 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7688 return false; 7689 7690 // If the target has a fast compare for the given size, it will return a 7691 // preferred load type for that size. Require that the load VT is legal and 7692 // that the target supports unaligned loads of that type. Otherwise, return 7693 // INVALID. 7694 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7695 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7696 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7697 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7698 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7699 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7700 // TODO: Check alignment of src and dest ptrs. 7701 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7702 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7703 if (!TLI.isTypeLegal(LVT) || 7704 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7705 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7706 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7707 } 7708 7709 return LVT; 7710 }; 7711 7712 // This turns into unaligned loads. We only do this if the target natively 7713 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7714 // we'll only produce a small number of byte loads. 7715 MVT LoadVT; 7716 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7717 switch (NumBitsToCompare) { 7718 default: 7719 return false; 7720 case 16: 7721 LoadVT = MVT::i16; 7722 break; 7723 case 32: 7724 LoadVT = MVT::i32; 7725 break; 7726 case 64: 7727 case 128: 7728 case 256: 7729 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7730 break; 7731 } 7732 7733 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7734 return false; 7735 7736 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7737 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7738 7739 // Bitcast to a wide integer type if the loads are vectors. 7740 if (LoadVT.isVector()) { 7741 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7742 LoadL = DAG.getBitcast(CmpVT, LoadL); 7743 LoadR = DAG.getBitcast(CmpVT, LoadR); 7744 } 7745 7746 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7747 processIntegerCallValue(I, Cmp, false); 7748 return true; 7749 } 7750 7751 /// See if we can lower a memchr call into an optimized form. If so, return 7752 /// true and lower it. Otherwise return false, and it will be lowered like a 7753 /// normal call. 7754 /// The caller already checked that \p I calls the appropriate LibFunc with a 7755 /// correct prototype. 7756 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7757 const Value *Src = I.getArgOperand(0); 7758 const Value *Char = I.getArgOperand(1); 7759 const Value *Length = I.getArgOperand(2); 7760 7761 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7762 std::pair<SDValue, SDValue> Res = 7763 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7764 getValue(Src), getValue(Char), getValue(Length), 7765 MachinePointerInfo(Src)); 7766 if (Res.first.getNode()) { 7767 setValue(&I, Res.first); 7768 PendingLoads.push_back(Res.second); 7769 return true; 7770 } 7771 7772 return false; 7773 } 7774 7775 /// See if we can lower a mempcpy call into an optimized form. If so, return 7776 /// true and lower it. Otherwise return false, and it will be lowered like a 7777 /// normal call. 7778 /// The caller already checked that \p I calls the appropriate LibFunc with a 7779 /// correct prototype. 7780 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7781 SDValue Dst = getValue(I.getArgOperand(0)); 7782 SDValue Src = getValue(I.getArgOperand(1)); 7783 SDValue Size = getValue(I.getArgOperand(2)); 7784 7785 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7786 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7787 // DAG::getMemcpy needs Alignment to be defined. 7788 Align Alignment = std::min(DstAlign, SrcAlign); 7789 7790 bool isVol = false; 7791 SDLoc sdl = getCurSDLoc(); 7792 7793 // In the mempcpy context we need to pass in a false value for isTailCall 7794 // because the return pointer needs to be adjusted by the size of 7795 // the copied memory. 7796 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7797 AAMDNodes AAInfo; 7798 I.getAAMetadata(AAInfo); 7799 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7800 /*isTailCall=*/false, 7801 MachinePointerInfo(I.getArgOperand(0)), 7802 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 7803 assert(MC.getNode() != nullptr && 7804 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7805 DAG.setRoot(MC); 7806 7807 // Check if Size needs to be truncated or extended. 7808 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7809 7810 // Adjust return pointer to point just past the last dst byte. 7811 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7812 Dst, Size); 7813 setValue(&I, DstPlusSize); 7814 return true; 7815 } 7816 7817 /// See if we can lower a strcpy call into an optimized form. If so, return 7818 /// true and lower it, otherwise return false and it will be lowered like a 7819 /// normal call. 7820 /// The caller already checked that \p I calls the appropriate LibFunc with a 7821 /// correct prototype. 7822 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7823 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7824 7825 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7826 std::pair<SDValue, SDValue> Res = 7827 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7828 getValue(Arg0), getValue(Arg1), 7829 MachinePointerInfo(Arg0), 7830 MachinePointerInfo(Arg1), isStpcpy); 7831 if (Res.first.getNode()) { 7832 setValue(&I, Res.first); 7833 DAG.setRoot(Res.second); 7834 return true; 7835 } 7836 7837 return false; 7838 } 7839 7840 /// See if we can lower a strcmp call into an optimized form. If so, return 7841 /// true and lower it, otherwise return false and it will be lowered like a 7842 /// normal call. 7843 /// The caller already checked that \p I calls the appropriate LibFunc with a 7844 /// correct prototype. 7845 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7846 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7847 7848 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7849 std::pair<SDValue, SDValue> Res = 7850 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7851 getValue(Arg0), getValue(Arg1), 7852 MachinePointerInfo(Arg0), 7853 MachinePointerInfo(Arg1)); 7854 if (Res.first.getNode()) { 7855 processIntegerCallValue(I, Res.first, true); 7856 PendingLoads.push_back(Res.second); 7857 return true; 7858 } 7859 7860 return false; 7861 } 7862 7863 /// See if we can lower a strlen call into an optimized form. If so, return 7864 /// true and lower it, otherwise return false and it will be lowered like a 7865 /// normal call. 7866 /// The caller already checked that \p I calls the appropriate LibFunc with a 7867 /// correct prototype. 7868 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7869 const Value *Arg0 = I.getArgOperand(0); 7870 7871 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7872 std::pair<SDValue, SDValue> Res = 7873 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7874 getValue(Arg0), MachinePointerInfo(Arg0)); 7875 if (Res.first.getNode()) { 7876 processIntegerCallValue(I, Res.first, false); 7877 PendingLoads.push_back(Res.second); 7878 return true; 7879 } 7880 7881 return false; 7882 } 7883 7884 /// See if we can lower a strnlen call into an optimized form. If so, return 7885 /// true and lower it, otherwise return false and it will be lowered like a 7886 /// normal call. 7887 /// The caller already checked that \p I calls the appropriate LibFunc with a 7888 /// correct prototype. 7889 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7890 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7891 7892 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7893 std::pair<SDValue, SDValue> Res = 7894 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7895 getValue(Arg0), getValue(Arg1), 7896 MachinePointerInfo(Arg0)); 7897 if (Res.first.getNode()) { 7898 processIntegerCallValue(I, Res.first, false); 7899 PendingLoads.push_back(Res.second); 7900 return true; 7901 } 7902 7903 return false; 7904 } 7905 7906 /// See if we can lower a unary floating-point operation into an SDNode with 7907 /// the specified Opcode. If so, return true and lower it, otherwise return 7908 /// false and it will be lowered like a normal call. 7909 /// The caller already checked that \p I calls the appropriate LibFunc with a 7910 /// correct prototype. 7911 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7912 unsigned Opcode) { 7913 // We already checked this call's prototype; verify it doesn't modify errno. 7914 if (!I.onlyReadsMemory()) 7915 return false; 7916 7917 SDNodeFlags Flags; 7918 Flags.copyFMF(cast<FPMathOperator>(I)); 7919 7920 SDValue Tmp = getValue(I.getArgOperand(0)); 7921 setValue(&I, 7922 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7923 return true; 7924 } 7925 7926 /// See if we can lower a binary floating-point operation into an SDNode with 7927 /// the specified Opcode. If so, return true and lower it. Otherwise return 7928 /// false, and it will be lowered like a normal call. 7929 /// The caller already checked that \p I calls the appropriate LibFunc with a 7930 /// correct prototype. 7931 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7932 unsigned Opcode) { 7933 // We already checked this call's prototype; verify it doesn't modify errno. 7934 if (!I.onlyReadsMemory()) 7935 return false; 7936 7937 SDNodeFlags Flags; 7938 Flags.copyFMF(cast<FPMathOperator>(I)); 7939 7940 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7941 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7942 EVT VT = Tmp0.getValueType(); 7943 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7944 return true; 7945 } 7946 7947 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7948 // Handle inline assembly differently. 7949 if (I.isInlineAsm()) { 7950 visitInlineAsm(I); 7951 return; 7952 } 7953 7954 if (Function *F = I.getCalledFunction()) { 7955 if (F->isDeclaration()) { 7956 // Is this an LLVM intrinsic or a target-specific intrinsic? 7957 unsigned IID = F->getIntrinsicID(); 7958 if (!IID) 7959 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7960 IID = II->getIntrinsicID(F); 7961 7962 if (IID) { 7963 visitIntrinsicCall(I, IID); 7964 return; 7965 } 7966 } 7967 7968 // Check for well-known libc/libm calls. If the function is internal, it 7969 // can't be a library call. Don't do the check if marked as nobuiltin for 7970 // some reason or the call site requires strict floating point semantics. 7971 LibFunc Func; 7972 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7973 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7974 LibInfo->hasOptimizedCodeGen(Func)) { 7975 switch (Func) { 7976 default: break; 7977 case LibFunc_bcmp: 7978 if (visitMemCmpBCmpCall(I)) 7979 return; 7980 break; 7981 case LibFunc_copysign: 7982 case LibFunc_copysignf: 7983 case LibFunc_copysignl: 7984 // We already checked this call's prototype; verify it doesn't modify 7985 // errno. 7986 if (I.onlyReadsMemory()) { 7987 SDValue LHS = getValue(I.getArgOperand(0)); 7988 SDValue RHS = getValue(I.getArgOperand(1)); 7989 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7990 LHS.getValueType(), LHS, RHS)); 7991 return; 7992 } 7993 break; 7994 case LibFunc_fabs: 7995 case LibFunc_fabsf: 7996 case LibFunc_fabsl: 7997 if (visitUnaryFloatCall(I, ISD::FABS)) 7998 return; 7999 break; 8000 case LibFunc_fmin: 8001 case LibFunc_fminf: 8002 case LibFunc_fminl: 8003 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8004 return; 8005 break; 8006 case LibFunc_fmax: 8007 case LibFunc_fmaxf: 8008 case LibFunc_fmaxl: 8009 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8010 return; 8011 break; 8012 case LibFunc_sin: 8013 case LibFunc_sinf: 8014 case LibFunc_sinl: 8015 if (visitUnaryFloatCall(I, ISD::FSIN)) 8016 return; 8017 break; 8018 case LibFunc_cos: 8019 case LibFunc_cosf: 8020 case LibFunc_cosl: 8021 if (visitUnaryFloatCall(I, ISD::FCOS)) 8022 return; 8023 break; 8024 case LibFunc_sqrt: 8025 case LibFunc_sqrtf: 8026 case LibFunc_sqrtl: 8027 case LibFunc_sqrt_finite: 8028 case LibFunc_sqrtf_finite: 8029 case LibFunc_sqrtl_finite: 8030 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8031 return; 8032 break; 8033 case LibFunc_floor: 8034 case LibFunc_floorf: 8035 case LibFunc_floorl: 8036 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8037 return; 8038 break; 8039 case LibFunc_nearbyint: 8040 case LibFunc_nearbyintf: 8041 case LibFunc_nearbyintl: 8042 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8043 return; 8044 break; 8045 case LibFunc_ceil: 8046 case LibFunc_ceilf: 8047 case LibFunc_ceill: 8048 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8049 return; 8050 break; 8051 case LibFunc_rint: 8052 case LibFunc_rintf: 8053 case LibFunc_rintl: 8054 if (visitUnaryFloatCall(I, ISD::FRINT)) 8055 return; 8056 break; 8057 case LibFunc_round: 8058 case LibFunc_roundf: 8059 case LibFunc_roundl: 8060 if (visitUnaryFloatCall(I, ISD::FROUND)) 8061 return; 8062 break; 8063 case LibFunc_trunc: 8064 case LibFunc_truncf: 8065 case LibFunc_truncl: 8066 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8067 return; 8068 break; 8069 case LibFunc_log2: 8070 case LibFunc_log2f: 8071 case LibFunc_log2l: 8072 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8073 return; 8074 break; 8075 case LibFunc_exp2: 8076 case LibFunc_exp2f: 8077 case LibFunc_exp2l: 8078 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8079 return; 8080 break; 8081 case LibFunc_memcmp: 8082 if (visitMemCmpBCmpCall(I)) 8083 return; 8084 break; 8085 case LibFunc_mempcpy: 8086 if (visitMemPCpyCall(I)) 8087 return; 8088 break; 8089 case LibFunc_memchr: 8090 if (visitMemChrCall(I)) 8091 return; 8092 break; 8093 case LibFunc_strcpy: 8094 if (visitStrCpyCall(I, false)) 8095 return; 8096 break; 8097 case LibFunc_stpcpy: 8098 if (visitStrCpyCall(I, true)) 8099 return; 8100 break; 8101 case LibFunc_strcmp: 8102 if (visitStrCmpCall(I)) 8103 return; 8104 break; 8105 case LibFunc_strlen: 8106 if (visitStrLenCall(I)) 8107 return; 8108 break; 8109 case LibFunc_strnlen: 8110 if (visitStrNLenCall(I)) 8111 return; 8112 break; 8113 } 8114 } 8115 } 8116 8117 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8118 // have to do anything here to lower funclet bundles. 8119 // CFGuardTarget bundles are lowered in LowerCallTo. 8120 assert(!I.hasOperandBundlesOtherThan( 8121 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8122 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8123 LLVMContext::OB_clang_arc_attachedcall}) && 8124 "Cannot lower calls with arbitrary operand bundles!"); 8125 8126 SDValue Callee = getValue(I.getCalledOperand()); 8127 8128 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8129 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8130 else 8131 // Check if we can potentially perform a tail call. More detailed checking 8132 // is be done within LowerCallTo, after more information about the call is 8133 // known. 8134 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8135 } 8136 8137 namespace { 8138 8139 /// AsmOperandInfo - This contains information for each constraint that we are 8140 /// lowering. 8141 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8142 public: 8143 /// CallOperand - If this is the result output operand or a clobber 8144 /// this is null, otherwise it is the incoming operand to the CallInst. 8145 /// This gets modified as the asm is processed. 8146 SDValue CallOperand; 8147 8148 /// AssignedRegs - If this is a register or register class operand, this 8149 /// contains the set of register corresponding to the operand. 8150 RegsForValue AssignedRegs; 8151 8152 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8153 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8154 } 8155 8156 /// Whether or not this operand accesses memory 8157 bool hasMemory(const TargetLowering &TLI) const { 8158 // Indirect operand accesses access memory. 8159 if (isIndirect) 8160 return true; 8161 8162 for (const auto &Code : Codes) 8163 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8164 return true; 8165 8166 return false; 8167 } 8168 8169 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8170 /// corresponds to. If there is no Value* for this operand, it returns 8171 /// MVT::Other. 8172 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8173 const DataLayout &DL) const { 8174 if (!CallOperandVal) return MVT::Other; 8175 8176 if (isa<BasicBlock>(CallOperandVal)) 8177 return TLI.getProgramPointerTy(DL); 8178 8179 llvm::Type *OpTy = CallOperandVal->getType(); 8180 8181 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8182 // If this is an indirect operand, the operand is a pointer to the 8183 // accessed type. 8184 if (isIndirect) { 8185 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8186 if (!PtrTy) 8187 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8188 OpTy = PtrTy->getElementType(); 8189 } 8190 8191 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8192 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8193 if (STy->getNumElements() == 1) 8194 OpTy = STy->getElementType(0); 8195 8196 // If OpTy is not a single value, it may be a struct/union that we 8197 // can tile with integers. 8198 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8199 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8200 switch (BitSize) { 8201 default: break; 8202 case 1: 8203 case 8: 8204 case 16: 8205 case 32: 8206 case 64: 8207 case 128: 8208 OpTy = IntegerType::get(Context, BitSize); 8209 break; 8210 } 8211 } 8212 8213 return TLI.getAsmOperandValueType(DL, OpTy, true); 8214 } 8215 }; 8216 8217 8218 } // end anonymous namespace 8219 8220 /// Make sure that the output operand \p OpInfo and its corresponding input 8221 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8222 /// out). 8223 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8224 SDISelAsmOperandInfo &MatchingOpInfo, 8225 SelectionDAG &DAG) { 8226 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8227 return; 8228 8229 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8230 const auto &TLI = DAG.getTargetLoweringInfo(); 8231 8232 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8233 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8234 OpInfo.ConstraintVT); 8235 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8236 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8237 MatchingOpInfo.ConstraintVT); 8238 if ((OpInfo.ConstraintVT.isInteger() != 8239 MatchingOpInfo.ConstraintVT.isInteger()) || 8240 (MatchRC.second != InputRC.second)) { 8241 // FIXME: error out in a more elegant fashion 8242 report_fatal_error("Unsupported asm: input constraint" 8243 " with a matching output constraint of" 8244 " incompatible type!"); 8245 } 8246 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8247 } 8248 8249 /// Get a direct memory input to behave well as an indirect operand. 8250 /// This may introduce stores, hence the need for a \p Chain. 8251 /// \return The (possibly updated) chain. 8252 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8253 SDISelAsmOperandInfo &OpInfo, 8254 SelectionDAG &DAG) { 8255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8256 8257 // If we don't have an indirect input, put it in the constpool if we can, 8258 // otherwise spill it to a stack slot. 8259 // TODO: This isn't quite right. We need to handle these according to 8260 // the addressing mode that the constraint wants. Also, this may take 8261 // an additional register for the computation and we don't want that 8262 // either. 8263 8264 // If the operand is a float, integer, or vector constant, spill to a 8265 // constant pool entry to get its address. 8266 const Value *OpVal = OpInfo.CallOperandVal; 8267 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8268 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8269 OpInfo.CallOperand = DAG.getConstantPool( 8270 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8271 return Chain; 8272 } 8273 8274 // Otherwise, create a stack slot and emit a store to it before the asm. 8275 Type *Ty = OpVal->getType(); 8276 auto &DL = DAG.getDataLayout(); 8277 uint64_t TySize = DL.getTypeAllocSize(Ty); 8278 MachineFunction &MF = DAG.getMachineFunction(); 8279 int SSFI = MF.getFrameInfo().CreateStackObject( 8280 TySize, DL.getPrefTypeAlign(Ty), false); 8281 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8282 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8283 MachinePointerInfo::getFixedStack(MF, SSFI), 8284 TLI.getMemValueType(DL, Ty)); 8285 OpInfo.CallOperand = StackSlot; 8286 8287 return Chain; 8288 } 8289 8290 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8291 /// specified operand. We prefer to assign virtual registers, to allow the 8292 /// register allocator to handle the assignment process. However, if the asm 8293 /// uses features that we can't model on machineinstrs, we have SDISel do the 8294 /// allocation. This produces generally horrible, but correct, code. 8295 /// 8296 /// OpInfo describes the operand 8297 /// RefOpInfo describes the matching operand if any, the operand otherwise 8298 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8299 SDISelAsmOperandInfo &OpInfo, 8300 SDISelAsmOperandInfo &RefOpInfo) { 8301 LLVMContext &Context = *DAG.getContext(); 8302 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8303 8304 MachineFunction &MF = DAG.getMachineFunction(); 8305 SmallVector<unsigned, 4> Regs; 8306 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8307 8308 // No work to do for memory operations. 8309 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8310 return; 8311 8312 // If this is a constraint for a single physreg, or a constraint for a 8313 // register class, find it. 8314 unsigned AssignedReg; 8315 const TargetRegisterClass *RC; 8316 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8317 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8318 // RC is unset only on failure. Return immediately. 8319 if (!RC) 8320 return; 8321 8322 // Get the actual register value type. This is important, because the user 8323 // may have asked for (e.g.) the AX register in i32 type. We need to 8324 // remember that AX is actually i16 to get the right extension. 8325 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8326 8327 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8328 // If this is an FP operand in an integer register (or visa versa), or more 8329 // generally if the operand value disagrees with the register class we plan 8330 // to stick it in, fix the operand type. 8331 // 8332 // If this is an input value, the bitcast to the new type is done now. 8333 // Bitcast for output value is done at the end of visitInlineAsm(). 8334 if ((OpInfo.Type == InlineAsm::isOutput || 8335 OpInfo.Type == InlineAsm::isInput) && 8336 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8337 // Try to convert to the first EVT that the reg class contains. If the 8338 // types are identical size, use a bitcast to convert (e.g. two differing 8339 // vector types). Note: output bitcast is done at the end of 8340 // visitInlineAsm(). 8341 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8342 // Exclude indirect inputs while they are unsupported because the code 8343 // to perform the load is missing and thus OpInfo.CallOperand still 8344 // refers to the input address rather than the pointed-to value. 8345 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8346 OpInfo.CallOperand = 8347 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8348 OpInfo.ConstraintVT = RegVT; 8349 // If the operand is an FP value and we want it in integer registers, 8350 // use the corresponding integer type. This turns an f64 value into 8351 // i64, which can be passed with two i32 values on a 32-bit machine. 8352 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8353 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8354 if (OpInfo.Type == InlineAsm::isInput) 8355 OpInfo.CallOperand = 8356 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8357 OpInfo.ConstraintVT = VT; 8358 } 8359 } 8360 } 8361 8362 // No need to allocate a matching input constraint since the constraint it's 8363 // matching to has already been allocated. 8364 if (OpInfo.isMatchingInputConstraint()) 8365 return; 8366 8367 EVT ValueVT = OpInfo.ConstraintVT; 8368 if (OpInfo.ConstraintVT == MVT::Other) 8369 ValueVT = RegVT; 8370 8371 // Initialize NumRegs. 8372 unsigned NumRegs = 1; 8373 if (OpInfo.ConstraintVT != MVT::Other) 8374 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8375 8376 // If this is a constraint for a specific physical register, like {r17}, 8377 // assign it now. 8378 8379 // If this associated to a specific register, initialize iterator to correct 8380 // place. If virtual, make sure we have enough registers 8381 8382 // Initialize iterator if necessary 8383 TargetRegisterClass::iterator I = RC->begin(); 8384 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8385 8386 // Do not check for single registers. 8387 if (AssignedReg) { 8388 for (; *I != AssignedReg; ++I) 8389 assert(I != RC->end() && "AssignedReg should be member of RC"); 8390 } 8391 8392 for (; NumRegs; --NumRegs, ++I) { 8393 assert(I != RC->end() && "Ran out of registers to allocate!"); 8394 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8395 Regs.push_back(R); 8396 } 8397 8398 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8399 } 8400 8401 static unsigned 8402 findMatchingInlineAsmOperand(unsigned OperandNo, 8403 const std::vector<SDValue> &AsmNodeOperands) { 8404 // Scan until we find the definition we already emitted of this operand. 8405 unsigned CurOp = InlineAsm::Op_FirstOperand; 8406 for (; OperandNo; --OperandNo) { 8407 // Advance to the next operand. 8408 unsigned OpFlag = 8409 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8410 assert((InlineAsm::isRegDefKind(OpFlag) || 8411 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8412 InlineAsm::isMemKind(OpFlag)) && 8413 "Skipped past definitions?"); 8414 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8415 } 8416 return CurOp; 8417 } 8418 8419 namespace { 8420 8421 class ExtraFlags { 8422 unsigned Flags = 0; 8423 8424 public: 8425 explicit ExtraFlags(const CallBase &Call) { 8426 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8427 if (IA->hasSideEffects()) 8428 Flags |= InlineAsm::Extra_HasSideEffects; 8429 if (IA->isAlignStack()) 8430 Flags |= InlineAsm::Extra_IsAlignStack; 8431 if (Call.isConvergent()) 8432 Flags |= InlineAsm::Extra_IsConvergent; 8433 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8434 } 8435 8436 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8437 // Ideally, we would only check against memory constraints. However, the 8438 // meaning of an Other constraint can be target-specific and we can't easily 8439 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8440 // for Other constraints as well. 8441 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8442 OpInfo.ConstraintType == TargetLowering::C_Other) { 8443 if (OpInfo.Type == InlineAsm::isInput) 8444 Flags |= InlineAsm::Extra_MayLoad; 8445 else if (OpInfo.Type == InlineAsm::isOutput) 8446 Flags |= InlineAsm::Extra_MayStore; 8447 else if (OpInfo.Type == InlineAsm::isClobber) 8448 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8449 } 8450 } 8451 8452 unsigned get() const { return Flags; } 8453 }; 8454 8455 } // end anonymous namespace 8456 8457 /// visitInlineAsm - Handle a call to an InlineAsm object. 8458 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8459 const BasicBlock *EHPadBB) { 8460 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8461 8462 /// ConstraintOperands - Information about all of the constraints. 8463 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8464 8465 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8466 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8467 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8468 8469 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8470 // AsmDialect, MayLoad, MayStore). 8471 bool HasSideEffect = IA->hasSideEffects(); 8472 ExtraFlags ExtraInfo(Call); 8473 8474 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8475 unsigned ResNo = 0; // ResNo - The result number of the next output. 8476 unsigned NumMatchingOps = 0; 8477 for (auto &T : TargetConstraints) { 8478 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8479 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8480 8481 // Compute the value type for each operand. 8482 if (OpInfo.Type == InlineAsm::isInput || 8483 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8484 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8485 8486 // Process the call argument. BasicBlocks are labels, currently appearing 8487 // only in asm's. 8488 if (isa<CallBrInst>(Call) && 8489 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8490 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8491 NumMatchingOps) && 8492 (NumMatchingOps == 0 || 8493 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8494 NumMatchingOps))) { 8495 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8496 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8497 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8498 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8499 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8500 } else { 8501 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8502 } 8503 8504 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8505 DAG.getDataLayout()); 8506 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8507 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8508 // The return value of the call is this value. As such, there is no 8509 // corresponding argument. 8510 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8511 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8512 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8513 DAG.getDataLayout(), STy->getElementType(ResNo)); 8514 } else { 8515 assert(ResNo == 0 && "Asm only has one result!"); 8516 OpInfo.ConstraintVT = TLI.getAsmOperandValueType( 8517 DAG.getDataLayout(), Call.getType()).getSimpleVT(); 8518 } 8519 ++ResNo; 8520 } else { 8521 OpInfo.ConstraintVT = MVT::Other; 8522 } 8523 8524 if (OpInfo.hasMatchingInput()) 8525 ++NumMatchingOps; 8526 8527 if (!HasSideEffect) 8528 HasSideEffect = OpInfo.hasMemory(TLI); 8529 8530 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8531 // FIXME: Could we compute this on OpInfo rather than T? 8532 8533 // Compute the constraint code and ConstraintType to use. 8534 TLI.ComputeConstraintToUse(T, SDValue()); 8535 8536 if (T.ConstraintType == TargetLowering::C_Immediate && 8537 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8538 // We've delayed emitting a diagnostic like the "n" constraint because 8539 // inlining could cause an integer showing up. 8540 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8541 "' expects an integer constant " 8542 "expression"); 8543 8544 ExtraInfo.update(T); 8545 } 8546 8547 // We won't need to flush pending loads if this asm doesn't touch 8548 // memory and is nonvolatile. 8549 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8550 8551 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8552 if (EmitEHLabels) { 8553 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8554 } 8555 bool IsCallBr = isa<CallBrInst>(Call); 8556 8557 if (IsCallBr || EmitEHLabels) { 8558 // If this is a callbr or invoke we need to flush pending exports since 8559 // inlineasm_br and invoke are terminators. 8560 // We need to do this before nodes are glued to the inlineasm_br node. 8561 Chain = getControlRoot(); 8562 } 8563 8564 MCSymbol *BeginLabel = nullptr; 8565 if (EmitEHLabels) { 8566 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8567 } 8568 8569 // Second pass over the constraints: compute which constraint option to use. 8570 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8571 // If this is an output operand with a matching input operand, look up the 8572 // matching input. If their types mismatch, e.g. one is an integer, the 8573 // other is floating point, or their sizes are different, flag it as an 8574 // error. 8575 if (OpInfo.hasMatchingInput()) { 8576 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8577 patchMatchingInput(OpInfo, Input, DAG); 8578 } 8579 8580 // Compute the constraint code and ConstraintType to use. 8581 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8582 8583 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8584 OpInfo.Type == InlineAsm::isClobber) 8585 continue; 8586 8587 // If this is a memory input, and if the operand is not indirect, do what we 8588 // need to provide an address for the memory input. 8589 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8590 !OpInfo.isIndirect) { 8591 assert((OpInfo.isMultipleAlternative || 8592 (OpInfo.Type == InlineAsm::isInput)) && 8593 "Can only indirectify direct input operands!"); 8594 8595 // Memory operands really want the address of the value. 8596 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8597 8598 // There is no longer a Value* corresponding to this operand. 8599 OpInfo.CallOperandVal = nullptr; 8600 8601 // It is now an indirect operand. 8602 OpInfo.isIndirect = true; 8603 } 8604 8605 } 8606 8607 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8608 std::vector<SDValue> AsmNodeOperands; 8609 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8610 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8611 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8612 8613 // If we have a !srcloc metadata node associated with it, we want to attach 8614 // this to the ultimately generated inline asm machineinstr. To do this, we 8615 // pass in the third operand as this (potentially null) inline asm MDNode. 8616 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8617 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8618 8619 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8620 // bits as operand 3. 8621 AsmNodeOperands.push_back(DAG.getTargetConstant( 8622 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8623 8624 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8625 // this, assign virtual and physical registers for inputs and otput. 8626 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8627 // Assign Registers. 8628 SDISelAsmOperandInfo &RefOpInfo = 8629 OpInfo.isMatchingInputConstraint() 8630 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8631 : OpInfo; 8632 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8633 8634 auto DetectWriteToReservedRegister = [&]() { 8635 const MachineFunction &MF = DAG.getMachineFunction(); 8636 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8637 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8638 if (Register::isPhysicalRegister(Reg) && 8639 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8640 const char *RegName = TRI.getName(Reg); 8641 emitInlineAsmError(Call, "write to reserved register '" + 8642 Twine(RegName) + "'"); 8643 return true; 8644 } 8645 } 8646 return false; 8647 }; 8648 8649 switch (OpInfo.Type) { 8650 case InlineAsm::isOutput: 8651 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8652 unsigned ConstraintID = 8653 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8654 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8655 "Failed to convert memory constraint code to constraint id."); 8656 8657 // Add information to the INLINEASM node to know about this output. 8658 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8659 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8660 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8661 MVT::i32)); 8662 AsmNodeOperands.push_back(OpInfo.CallOperand); 8663 } else { 8664 // Otherwise, this outputs to a register (directly for C_Register / 8665 // C_RegisterClass, and a target-defined fashion for 8666 // C_Immediate/C_Other). Find a register that we can use. 8667 if (OpInfo.AssignedRegs.Regs.empty()) { 8668 emitInlineAsmError( 8669 Call, "couldn't allocate output register for constraint '" + 8670 Twine(OpInfo.ConstraintCode) + "'"); 8671 return; 8672 } 8673 8674 if (DetectWriteToReservedRegister()) 8675 return; 8676 8677 // Add information to the INLINEASM node to know that this register is 8678 // set. 8679 OpInfo.AssignedRegs.AddInlineAsmOperands( 8680 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8681 : InlineAsm::Kind_RegDef, 8682 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8683 } 8684 break; 8685 8686 case InlineAsm::isInput: { 8687 SDValue InOperandVal = OpInfo.CallOperand; 8688 8689 if (OpInfo.isMatchingInputConstraint()) { 8690 // If this is required to match an output register we have already set, 8691 // just use its register. 8692 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8693 AsmNodeOperands); 8694 unsigned OpFlag = 8695 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8696 if (InlineAsm::isRegDefKind(OpFlag) || 8697 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8698 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8699 if (OpInfo.isIndirect) { 8700 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8701 emitInlineAsmError(Call, "inline asm not supported yet: " 8702 "don't know how to handle tied " 8703 "indirect register inputs"); 8704 return; 8705 } 8706 8707 SmallVector<unsigned, 4> Regs; 8708 MachineFunction &MF = DAG.getMachineFunction(); 8709 MachineRegisterInfo &MRI = MF.getRegInfo(); 8710 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8711 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8712 Register TiedReg = R->getReg(); 8713 MVT RegVT = R->getSimpleValueType(0); 8714 const TargetRegisterClass *RC = TiedReg.isVirtual() ? 8715 MRI.getRegClass(TiedReg) : TRI.getMinimalPhysRegClass(TiedReg); 8716 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8717 for (unsigned i = 0; i != NumRegs; ++i) 8718 Regs.push_back(MRI.createVirtualRegister(RC)); 8719 8720 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8721 8722 SDLoc dl = getCurSDLoc(); 8723 // Use the produced MatchedRegs object to 8724 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8725 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8726 true, OpInfo.getMatchedOperand(), dl, 8727 DAG, AsmNodeOperands); 8728 break; 8729 } 8730 8731 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8732 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8733 "Unexpected number of operands"); 8734 // Add information to the INLINEASM node to know about this input. 8735 // See InlineAsm.h isUseOperandTiedToDef. 8736 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8737 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8738 OpInfo.getMatchedOperand()); 8739 AsmNodeOperands.push_back(DAG.getTargetConstant( 8740 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8741 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8742 break; 8743 } 8744 8745 // Treat indirect 'X' constraint as memory. 8746 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8747 OpInfo.isIndirect) 8748 OpInfo.ConstraintType = TargetLowering::C_Memory; 8749 8750 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8751 OpInfo.ConstraintType == TargetLowering::C_Other) { 8752 std::vector<SDValue> Ops; 8753 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8754 Ops, DAG); 8755 if (Ops.empty()) { 8756 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8757 if (isa<ConstantSDNode>(InOperandVal)) { 8758 emitInlineAsmError(Call, "value out of range for constraint '" + 8759 Twine(OpInfo.ConstraintCode) + "'"); 8760 return; 8761 } 8762 8763 emitInlineAsmError(Call, 8764 "invalid operand for inline asm constraint '" + 8765 Twine(OpInfo.ConstraintCode) + "'"); 8766 return; 8767 } 8768 8769 // Add information to the INLINEASM node to know about this input. 8770 unsigned ResOpType = 8771 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8772 AsmNodeOperands.push_back(DAG.getTargetConstant( 8773 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8774 llvm::append_range(AsmNodeOperands, Ops); 8775 break; 8776 } 8777 8778 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8779 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8780 assert(InOperandVal.getValueType() == 8781 TLI.getPointerTy(DAG.getDataLayout()) && 8782 "Memory operands expect pointer values"); 8783 8784 unsigned ConstraintID = 8785 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8786 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8787 "Failed to convert memory constraint code to constraint id."); 8788 8789 // Add information to the INLINEASM node to know about this input. 8790 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8791 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8792 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8793 getCurSDLoc(), 8794 MVT::i32)); 8795 AsmNodeOperands.push_back(InOperandVal); 8796 break; 8797 } 8798 8799 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8800 OpInfo.ConstraintType == TargetLowering::C_Register) && 8801 "Unknown constraint type!"); 8802 8803 // TODO: Support this. 8804 if (OpInfo.isIndirect) { 8805 emitInlineAsmError( 8806 Call, "Don't know how to handle indirect register inputs yet " 8807 "for constraint '" + 8808 Twine(OpInfo.ConstraintCode) + "'"); 8809 return; 8810 } 8811 8812 // Copy the input into the appropriate registers. 8813 if (OpInfo.AssignedRegs.Regs.empty()) { 8814 emitInlineAsmError(Call, 8815 "couldn't allocate input reg for constraint '" + 8816 Twine(OpInfo.ConstraintCode) + "'"); 8817 return; 8818 } 8819 8820 if (DetectWriteToReservedRegister()) 8821 return; 8822 8823 SDLoc dl = getCurSDLoc(); 8824 8825 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8826 &Call); 8827 8828 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8829 dl, DAG, AsmNodeOperands); 8830 break; 8831 } 8832 case InlineAsm::isClobber: 8833 // Add the clobbered value to the operand list, so that the register 8834 // allocator is aware that the physreg got clobbered. 8835 if (!OpInfo.AssignedRegs.Regs.empty()) 8836 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8837 false, 0, getCurSDLoc(), DAG, 8838 AsmNodeOperands); 8839 break; 8840 } 8841 } 8842 8843 // Finish up input operands. Set the input chain and add the flag last. 8844 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8845 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8846 8847 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8848 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8849 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8850 Flag = Chain.getValue(1); 8851 8852 // Do additional work to generate outputs. 8853 8854 SmallVector<EVT, 1> ResultVTs; 8855 SmallVector<SDValue, 1> ResultValues; 8856 SmallVector<SDValue, 8> OutChains; 8857 8858 llvm::Type *CallResultType = Call.getType(); 8859 ArrayRef<Type *> ResultTypes; 8860 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8861 ResultTypes = StructResult->elements(); 8862 else if (!CallResultType->isVoidTy()) 8863 ResultTypes = makeArrayRef(CallResultType); 8864 8865 auto CurResultType = ResultTypes.begin(); 8866 auto handleRegAssign = [&](SDValue V) { 8867 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8868 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8869 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8870 ++CurResultType; 8871 // If the type of the inline asm call site return value is different but has 8872 // same size as the type of the asm output bitcast it. One example of this 8873 // is for vectors with different width / number of elements. This can 8874 // happen for register classes that can contain multiple different value 8875 // types. The preg or vreg allocated may not have the same VT as was 8876 // expected. 8877 // 8878 // This can also happen for a return value that disagrees with the register 8879 // class it is put in, eg. a double in a general-purpose register on a 8880 // 32-bit machine. 8881 if (ResultVT != V.getValueType() && 8882 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8883 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8884 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8885 V.getValueType().isInteger()) { 8886 // If a result value was tied to an input value, the computed result 8887 // may have a wider width than the expected result. Extract the 8888 // relevant portion. 8889 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8890 } 8891 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8892 ResultVTs.push_back(ResultVT); 8893 ResultValues.push_back(V); 8894 }; 8895 8896 // Deal with output operands. 8897 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8898 if (OpInfo.Type == InlineAsm::isOutput) { 8899 SDValue Val; 8900 // Skip trivial output operands. 8901 if (OpInfo.AssignedRegs.Regs.empty()) 8902 continue; 8903 8904 switch (OpInfo.ConstraintType) { 8905 case TargetLowering::C_Register: 8906 case TargetLowering::C_RegisterClass: 8907 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8908 Chain, &Flag, &Call); 8909 break; 8910 case TargetLowering::C_Immediate: 8911 case TargetLowering::C_Other: 8912 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8913 OpInfo, DAG); 8914 break; 8915 case TargetLowering::C_Memory: 8916 break; // Already handled. 8917 case TargetLowering::C_Unknown: 8918 assert(false && "Unexpected unknown constraint"); 8919 } 8920 8921 // Indirect output manifest as stores. Record output chains. 8922 if (OpInfo.isIndirect) { 8923 const Value *Ptr = OpInfo.CallOperandVal; 8924 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8925 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8926 MachinePointerInfo(Ptr)); 8927 OutChains.push_back(Store); 8928 } else { 8929 // generate CopyFromRegs to associated registers. 8930 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8931 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8932 for (const SDValue &V : Val->op_values()) 8933 handleRegAssign(V); 8934 } else 8935 handleRegAssign(Val); 8936 } 8937 } 8938 } 8939 8940 // Set results. 8941 if (!ResultValues.empty()) { 8942 assert(CurResultType == ResultTypes.end() && 8943 "Mismatch in number of ResultTypes"); 8944 assert(ResultValues.size() == ResultTypes.size() && 8945 "Mismatch in number of output operands in asm result"); 8946 8947 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8948 DAG.getVTList(ResultVTs), ResultValues); 8949 setValue(&Call, V); 8950 } 8951 8952 // Collect store chains. 8953 if (!OutChains.empty()) 8954 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8955 8956 if (EmitEHLabels) { 8957 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 8958 } 8959 8960 // Only Update Root if inline assembly has a memory effect. 8961 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 8962 EmitEHLabels) 8963 DAG.setRoot(Chain); 8964 } 8965 8966 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8967 const Twine &Message) { 8968 LLVMContext &Ctx = *DAG.getContext(); 8969 Ctx.emitError(&Call, Message); 8970 8971 // Make sure we leave the DAG in a valid state 8972 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8973 SmallVector<EVT, 1> ValueVTs; 8974 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8975 8976 if (ValueVTs.empty()) 8977 return; 8978 8979 SmallVector<SDValue, 1> Ops; 8980 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8981 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8982 8983 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8984 } 8985 8986 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8987 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8988 MVT::Other, getRoot(), 8989 getValue(I.getArgOperand(0)), 8990 DAG.getSrcValue(I.getArgOperand(0)))); 8991 } 8992 8993 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8994 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8995 const DataLayout &DL = DAG.getDataLayout(); 8996 SDValue V = DAG.getVAArg( 8997 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8998 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8999 DL.getABITypeAlign(I.getType()).value()); 9000 DAG.setRoot(V.getValue(1)); 9001 9002 if (I.getType()->isPointerTy()) 9003 V = DAG.getPtrExtOrTrunc( 9004 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9005 setValue(&I, V); 9006 } 9007 9008 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9009 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9010 MVT::Other, getRoot(), 9011 getValue(I.getArgOperand(0)), 9012 DAG.getSrcValue(I.getArgOperand(0)))); 9013 } 9014 9015 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9016 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9017 MVT::Other, getRoot(), 9018 getValue(I.getArgOperand(0)), 9019 getValue(I.getArgOperand(1)), 9020 DAG.getSrcValue(I.getArgOperand(0)), 9021 DAG.getSrcValue(I.getArgOperand(1)))); 9022 } 9023 9024 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9025 const Instruction &I, 9026 SDValue Op) { 9027 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9028 if (!Range) 9029 return Op; 9030 9031 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9032 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9033 return Op; 9034 9035 APInt Lo = CR.getUnsignedMin(); 9036 if (!Lo.isMinValue()) 9037 return Op; 9038 9039 APInt Hi = CR.getUnsignedMax(); 9040 unsigned Bits = std::max(Hi.getActiveBits(), 9041 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9042 9043 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9044 9045 SDLoc SL = getCurSDLoc(); 9046 9047 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9048 DAG.getValueType(SmallVT)); 9049 unsigned NumVals = Op.getNode()->getNumValues(); 9050 if (NumVals == 1) 9051 return ZExt; 9052 9053 SmallVector<SDValue, 4> Ops; 9054 9055 Ops.push_back(ZExt); 9056 for (unsigned I = 1; I != NumVals; ++I) 9057 Ops.push_back(Op.getValue(I)); 9058 9059 return DAG.getMergeValues(Ops, SL); 9060 } 9061 9062 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9063 /// the call being lowered. 9064 /// 9065 /// This is a helper for lowering intrinsics that follow a target calling 9066 /// convention or require stack pointer adjustment. Only a subset of the 9067 /// intrinsic's operands need to participate in the calling convention. 9068 void SelectionDAGBuilder::populateCallLoweringInfo( 9069 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9070 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9071 bool IsPatchPoint) { 9072 TargetLowering::ArgListTy Args; 9073 Args.reserve(NumArgs); 9074 9075 // Populate the argument list. 9076 // Attributes for args start at offset 1, after the return attribute. 9077 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9078 ArgI != ArgE; ++ArgI) { 9079 const Value *V = Call->getOperand(ArgI); 9080 9081 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9082 9083 TargetLowering::ArgListEntry Entry; 9084 Entry.Node = getValue(V); 9085 Entry.Ty = V->getType(); 9086 Entry.setAttributes(Call, ArgI); 9087 Args.push_back(Entry); 9088 } 9089 9090 CLI.setDebugLoc(getCurSDLoc()) 9091 .setChain(getRoot()) 9092 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9093 .setDiscardResult(Call->use_empty()) 9094 .setIsPatchPoint(IsPatchPoint) 9095 .setIsPreallocated( 9096 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9097 } 9098 9099 /// Add a stack map intrinsic call's live variable operands to a stackmap 9100 /// or patchpoint target node's operand list. 9101 /// 9102 /// Constants are converted to TargetConstants purely as an optimization to 9103 /// avoid constant materialization and register allocation. 9104 /// 9105 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9106 /// generate addess computation nodes, and so FinalizeISel can convert the 9107 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9108 /// address materialization and register allocation, but may also be required 9109 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9110 /// alloca in the entry block, then the runtime may assume that the alloca's 9111 /// StackMap location can be read immediately after compilation and that the 9112 /// location is valid at any point during execution (this is similar to the 9113 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9114 /// only available in a register, then the runtime would need to trap when 9115 /// execution reaches the StackMap in order to read the alloca's location. 9116 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9117 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9118 SelectionDAGBuilder &Builder) { 9119 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9120 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9122 Ops.push_back( 9123 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9124 Ops.push_back( 9125 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9126 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9127 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9128 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9129 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9130 } else 9131 Ops.push_back(OpVal); 9132 } 9133 } 9134 9135 /// Lower llvm.experimental.stackmap directly to its target opcode. 9136 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9137 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9138 // [live variables...]) 9139 9140 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9141 9142 SDValue Chain, InFlag, Callee, NullPtr; 9143 SmallVector<SDValue, 32> Ops; 9144 9145 SDLoc DL = getCurSDLoc(); 9146 Callee = getValue(CI.getCalledOperand()); 9147 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9148 9149 // The stackmap intrinsic only records the live variables (the arguments 9150 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9151 // intrinsic, this won't be lowered to a function call. This means we don't 9152 // have to worry about calling conventions and target specific lowering code. 9153 // Instead we perform the call lowering right here. 9154 // 9155 // chain, flag = CALLSEQ_START(chain, 0, 0) 9156 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9157 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9158 // 9159 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9160 InFlag = Chain.getValue(1); 9161 9162 // Add the <id> and <numBytes> constants. 9163 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9164 Ops.push_back(DAG.getTargetConstant( 9165 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9166 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9167 Ops.push_back(DAG.getTargetConstant( 9168 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9169 MVT::i32)); 9170 9171 // Push live variables for the stack map. 9172 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9173 9174 // We are not pushing any register mask info here on the operands list, 9175 // because the stackmap doesn't clobber anything. 9176 9177 // Push the chain and the glue flag. 9178 Ops.push_back(Chain); 9179 Ops.push_back(InFlag); 9180 9181 // Create the STACKMAP node. 9182 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9183 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9184 Chain = SDValue(SM, 0); 9185 InFlag = Chain.getValue(1); 9186 9187 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9188 9189 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9190 9191 // Set the root to the target-lowered call chain. 9192 DAG.setRoot(Chain); 9193 9194 // Inform the Frame Information that we have a stackmap in this function. 9195 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9196 } 9197 9198 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9199 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9200 const BasicBlock *EHPadBB) { 9201 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9202 // i32 <numBytes>, 9203 // i8* <target>, 9204 // i32 <numArgs>, 9205 // [Args...], 9206 // [live variables...]) 9207 9208 CallingConv::ID CC = CB.getCallingConv(); 9209 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9210 bool HasDef = !CB.getType()->isVoidTy(); 9211 SDLoc dl = getCurSDLoc(); 9212 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9213 9214 // Handle immediate and symbolic callees. 9215 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9216 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9217 /*isTarget=*/true); 9218 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9219 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9220 SDLoc(SymbolicCallee), 9221 SymbolicCallee->getValueType(0)); 9222 9223 // Get the real number of arguments participating in the call <numArgs> 9224 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9225 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9226 9227 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9228 // Intrinsics include all meta-operands up to but not including CC. 9229 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9230 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9231 "Not enough arguments provided to the patchpoint intrinsic"); 9232 9233 // For AnyRegCC the arguments are lowered later on manually. 9234 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9235 Type *ReturnTy = 9236 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9237 9238 TargetLowering::CallLoweringInfo CLI(DAG); 9239 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9240 ReturnTy, true); 9241 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9242 9243 SDNode *CallEnd = Result.second.getNode(); 9244 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9245 CallEnd = CallEnd->getOperand(0).getNode(); 9246 9247 /// Get a call instruction from the call sequence chain. 9248 /// Tail calls are not allowed. 9249 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9250 "Expected a callseq node."); 9251 SDNode *Call = CallEnd->getOperand(0).getNode(); 9252 bool HasGlue = Call->getGluedNode(); 9253 9254 // Replace the target specific call node with the patchable intrinsic. 9255 SmallVector<SDValue, 8> Ops; 9256 9257 // Add the <id> and <numBytes> constants. 9258 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9259 Ops.push_back(DAG.getTargetConstant( 9260 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9261 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9262 Ops.push_back(DAG.getTargetConstant( 9263 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9264 MVT::i32)); 9265 9266 // Add the callee. 9267 Ops.push_back(Callee); 9268 9269 // Adjust <numArgs> to account for any arguments that have been passed on the 9270 // stack instead. 9271 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9272 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9273 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9274 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9275 9276 // Add the calling convention 9277 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9278 9279 // Add the arguments we omitted previously. The register allocator should 9280 // place these in any free register. 9281 if (IsAnyRegCC) 9282 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9283 Ops.push_back(getValue(CB.getArgOperand(i))); 9284 9285 // Push the arguments from the call instruction up to the register mask. 9286 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9287 Ops.append(Call->op_begin() + 2, e); 9288 9289 // Push live variables for the stack map. 9290 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9291 9292 // Push the register mask info. 9293 if (HasGlue) 9294 Ops.push_back(*(Call->op_end()-2)); 9295 else 9296 Ops.push_back(*(Call->op_end()-1)); 9297 9298 // Push the chain (this is originally the first operand of the call, but 9299 // becomes now the last or second to last operand). 9300 Ops.push_back(*(Call->op_begin())); 9301 9302 // Push the glue flag (last operand). 9303 if (HasGlue) 9304 Ops.push_back(*(Call->op_end()-1)); 9305 9306 SDVTList NodeTys; 9307 if (IsAnyRegCC && HasDef) { 9308 // Create the return types based on the intrinsic definition 9309 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9310 SmallVector<EVT, 3> ValueVTs; 9311 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9312 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9313 9314 // There is always a chain and a glue type at the end 9315 ValueVTs.push_back(MVT::Other); 9316 ValueVTs.push_back(MVT::Glue); 9317 NodeTys = DAG.getVTList(ValueVTs); 9318 } else 9319 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9320 9321 // Replace the target specific call node with a PATCHPOINT node. 9322 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9323 dl, NodeTys, Ops); 9324 9325 // Update the NodeMap. 9326 if (HasDef) { 9327 if (IsAnyRegCC) 9328 setValue(&CB, SDValue(MN, 0)); 9329 else 9330 setValue(&CB, Result.first); 9331 } 9332 9333 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9334 // call sequence. Furthermore the location of the chain and glue can change 9335 // when the AnyReg calling convention is used and the intrinsic returns a 9336 // value. 9337 if (IsAnyRegCC && HasDef) { 9338 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9339 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9340 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9341 } else 9342 DAG.ReplaceAllUsesWith(Call, MN); 9343 DAG.DeleteNode(Call); 9344 9345 // Inform the Frame Information that we have a patchpoint in this function. 9346 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9347 } 9348 9349 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9350 unsigned Intrinsic) { 9351 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9352 SDValue Op1 = getValue(I.getArgOperand(0)); 9353 SDValue Op2; 9354 if (I.getNumArgOperands() > 1) 9355 Op2 = getValue(I.getArgOperand(1)); 9356 SDLoc dl = getCurSDLoc(); 9357 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9358 SDValue Res; 9359 SDNodeFlags SDFlags; 9360 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9361 SDFlags.copyFMF(*FPMO); 9362 9363 switch (Intrinsic) { 9364 case Intrinsic::vector_reduce_fadd: 9365 if (SDFlags.hasAllowReassociation()) 9366 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9367 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9368 SDFlags); 9369 else 9370 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9371 break; 9372 case Intrinsic::vector_reduce_fmul: 9373 if (SDFlags.hasAllowReassociation()) 9374 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9375 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9376 SDFlags); 9377 else 9378 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9379 break; 9380 case Intrinsic::vector_reduce_add: 9381 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9382 break; 9383 case Intrinsic::vector_reduce_mul: 9384 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9385 break; 9386 case Intrinsic::vector_reduce_and: 9387 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9388 break; 9389 case Intrinsic::vector_reduce_or: 9390 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9391 break; 9392 case Intrinsic::vector_reduce_xor: 9393 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9394 break; 9395 case Intrinsic::vector_reduce_smax: 9396 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9397 break; 9398 case Intrinsic::vector_reduce_smin: 9399 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9400 break; 9401 case Intrinsic::vector_reduce_umax: 9402 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9403 break; 9404 case Intrinsic::vector_reduce_umin: 9405 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9406 break; 9407 case Intrinsic::vector_reduce_fmax: 9408 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9409 break; 9410 case Intrinsic::vector_reduce_fmin: 9411 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9412 break; 9413 default: 9414 llvm_unreachable("Unhandled vector reduce intrinsic"); 9415 } 9416 setValue(&I, Res); 9417 } 9418 9419 /// Returns an AttributeList representing the attributes applied to the return 9420 /// value of the given call. 9421 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9422 SmallVector<Attribute::AttrKind, 2> Attrs; 9423 if (CLI.RetSExt) 9424 Attrs.push_back(Attribute::SExt); 9425 if (CLI.RetZExt) 9426 Attrs.push_back(Attribute::ZExt); 9427 if (CLI.IsInReg) 9428 Attrs.push_back(Attribute::InReg); 9429 9430 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9431 Attrs); 9432 } 9433 9434 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9435 /// implementation, which just calls LowerCall. 9436 /// FIXME: When all targets are 9437 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9438 std::pair<SDValue, SDValue> 9439 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9440 // Handle the incoming return values from the call. 9441 CLI.Ins.clear(); 9442 Type *OrigRetTy = CLI.RetTy; 9443 SmallVector<EVT, 4> RetTys; 9444 SmallVector<uint64_t, 4> Offsets; 9445 auto &DL = CLI.DAG.getDataLayout(); 9446 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9447 9448 if (CLI.IsPostTypeLegalization) { 9449 // If we are lowering a libcall after legalization, split the return type. 9450 SmallVector<EVT, 4> OldRetTys; 9451 SmallVector<uint64_t, 4> OldOffsets; 9452 RetTys.swap(OldRetTys); 9453 Offsets.swap(OldOffsets); 9454 9455 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9456 EVT RetVT = OldRetTys[i]; 9457 uint64_t Offset = OldOffsets[i]; 9458 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9459 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9460 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9461 RetTys.append(NumRegs, RegisterVT); 9462 for (unsigned j = 0; j != NumRegs; ++j) 9463 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9464 } 9465 } 9466 9467 SmallVector<ISD::OutputArg, 4> Outs; 9468 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9469 9470 bool CanLowerReturn = 9471 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9472 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9473 9474 SDValue DemoteStackSlot; 9475 int DemoteStackIdx = -100; 9476 if (!CanLowerReturn) { 9477 // FIXME: equivalent assert? 9478 // assert(!CS.hasInAllocaArgument() && 9479 // "sret demotion is incompatible with inalloca"); 9480 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9481 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9482 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9483 DemoteStackIdx = 9484 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9485 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9486 DL.getAllocaAddrSpace()); 9487 9488 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9489 ArgListEntry Entry; 9490 Entry.Node = DemoteStackSlot; 9491 Entry.Ty = StackSlotPtrType; 9492 Entry.IsSExt = false; 9493 Entry.IsZExt = false; 9494 Entry.IsInReg = false; 9495 Entry.IsSRet = true; 9496 Entry.IsNest = false; 9497 Entry.IsByVal = false; 9498 Entry.IsByRef = false; 9499 Entry.IsReturned = false; 9500 Entry.IsSwiftSelf = false; 9501 Entry.IsSwiftAsync = false; 9502 Entry.IsSwiftError = false; 9503 Entry.IsCFGuardTarget = false; 9504 Entry.Alignment = Alignment; 9505 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9506 CLI.NumFixedArgs += 1; 9507 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9508 9509 // sret demotion isn't compatible with tail-calls, since the sret argument 9510 // points into the callers stack frame. 9511 CLI.IsTailCall = false; 9512 } else { 9513 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9514 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9515 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9516 ISD::ArgFlagsTy Flags; 9517 if (NeedsRegBlock) { 9518 Flags.setInConsecutiveRegs(); 9519 if (I == RetTys.size() - 1) 9520 Flags.setInConsecutiveRegsLast(); 9521 } 9522 EVT VT = RetTys[I]; 9523 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9524 CLI.CallConv, VT); 9525 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9526 CLI.CallConv, VT); 9527 for (unsigned i = 0; i != NumRegs; ++i) { 9528 ISD::InputArg MyFlags; 9529 MyFlags.Flags = Flags; 9530 MyFlags.VT = RegisterVT; 9531 MyFlags.ArgVT = VT; 9532 MyFlags.Used = CLI.IsReturnValueUsed; 9533 if (CLI.RetTy->isPointerTy()) { 9534 MyFlags.Flags.setPointer(); 9535 MyFlags.Flags.setPointerAddrSpace( 9536 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9537 } 9538 if (CLI.RetSExt) 9539 MyFlags.Flags.setSExt(); 9540 if (CLI.RetZExt) 9541 MyFlags.Flags.setZExt(); 9542 if (CLI.IsInReg) 9543 MyFlags.Flags.setInReg(); 9544 CLI.Ins.push_back(MyFlags); 9545 } 9546 } 9547 } 9548 9549 // We push in swifterror return as the last element of CLI.Ins. 9550 ArgListTy &Args = CLI.getArgs(); 9551 if (supportSwiftError()) { 9552 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9553 if (Args[i].IsSwiftError) { 9554 ISD::InputArg MyFlags; 9555 MyFlags.VT = getPointerTy(DL); 9556 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9557 MyFlags.Flags.setSwiftError(); 9558 CLI.Ins.push_back(MyFlags); 9559 } 9560 } 9561 } 9562 9563 // Handle all of the outgoing arguments. 9564 CLI.Outs.clear(); 9565 CLI.OutVals.clear(); 9566 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9567 SmallVector<EVT, 4> ValueVTs; 9568 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9569 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9570 Type *FinalType = Args[i].Ty; 9571 if (Args[i].IsByVal) 9572 FinalType = Args[i].IndirectType; 9573 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9574 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9575 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9576 ++Value) { 9577 EVT VT = ValueVTs[Value]; 9578 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9579 SDValue Op = SDValue(Args[i].Node.getNode(), 9580 Args[i].Node.getResNo() + Value); 9581 ISD::ArgFlagsTy Flags; 9582 9583 // Certain targets (such as MIPS), may have a different ABI alignment 9584 // for a type depending on the context. Give the target a chance to 9585 // specify the alignment it wants. 9586 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9587 Flags.setOrigAlign(OriginalAlignment); 9588 9589 if (Args[i].Ty->isPointerTy()) { 9590 Flags.setPointer(); 9591 Flags.setPointerAddrSpace( 9592 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9593 } 9594 if (Args[i].IsZExt) 9595 Flags.setZExt(); 9596 if (Args[i].IsSExt) 9597 Flags.setSExt(); 9598 if (Args[i].IsInReg) { 9599 // If we are using vectorcall calling convention, a structure that is 9600 // passed InReg - is surely an HVA 9601 if (CLI.CallConv == CallingConv::X86_VectorCall && 9602 isa<StructType>(FinalType)) { 9603 // The first value of a structure is marked 9604 if (0 == Value) 9605 Flags.setHvaStart(); 9606 Flags.setHva(); 9607 } 9608 // Set InReg Flag 9609 Flags.setInReg(); 9610 } 9611 if (Args[i].IsSRet) 9612 Flags.setSRet(); 9613 if (Args[i].IsSwiftSelf) 9614 Flags.setSwiftSelf(); 9615 if (Args[i].IsSwiftAsync) 9616 Flags.setSwiftAsync(); 9617 if (Args[i].IsSwiftError) 9618 Flags.setSwiftError(); 9619 if (Args[i].IsCFGuardTarget) 9620 Flags.setCFGuardTarget(); 9621 if (Args[i].IsByVal) 9622 Flags.setByVal(); 9623 if (Args[i].IsByRef) 9624 Flags.setByRef(); 9625 if (Args[i].IsPreallocated) { 9626 Flags.setPreallocated(); 9627 // Set the byval flag for CCAssignFn callbacks that don't know about 9628 // preallocated. This way we can know how many bytes we should've 9629 // allocated and how many bytes a callee cleanup function will pop. If 9630 // we port preallocated to more targets, we'll have to add custom 9631 // preallocated handling in the various CC lowering callbacks. 9632 Flags.setByVal(); 9633 } 9634 if (Args[i].IsInAlloca) { 9635 Flags.setInAlloca(); 9636 // Set the byval flag for CCAssignFn callbacks that don't know about 9637 // inalloca. This way we can know how many bytes we should've allocated 9638 // and how many bytes a callee cleanup function will pop. If we port 9639 // inalloca to more targets, we'll have to add custom inalloca handling 9640 // in the various CC lowering callbacks. 9641 Flags.setByVal(); 9642 } 9643 Align MemAlign; 9644 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9645 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 9646 Flags.setByValSize(FrameSize); 9647 9648 // info is not there but there are cases it cannot get right. 9649 if (auto MA = Args[i].Alignment) 9650 MemAlign = *MA; 9651 else 9652 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 9653 } else if (auto MA = Args[i].Alignment) { 9654 MemAlign = *MA; 9655 } else { 9656 MemAlign = OriginalAlignment; 9657 } 9658 Flags.setMemAlign(MemAlign); 9659 if (Args[i].IsNest) 9660 Flags.setNest(); 9661 if (NeedsRegBlock) 9662 Flags.setInConsecutiveRegs(); 9663 9664 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9665 CLI.CallConv, VT); 9666 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9667 CLI.CallConv, VT); 9668 SmallVector<SDValue, 4> Parts(NumParts); 9669 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9670 9671 if (Args[i].IsSExt) 9672 ExtendKind = ISD::SIGN_EXTEND; 9673 else if (Args[i].IsZExt) 9674 ExtendKind = ISD::ZERO_EXTEND; 9675 9676 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9677 // for now. 9678 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9679 CanLowerReturn) { 9680 assert((CLI.RetTy == Args[i].Ty || 9681 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9682 CLI.RetTy->getPointerAddressSpace() == 9683 Args[i].Ty->getPointerAddressSpace())) && 9684 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9685 // Before passing 'returned' to the target lowering code, ensure that 9686 // either the register MVT and the actual EVT are the same size or that 9687 // the return value and argument are extended in the same way; in these 9688 // cases it's safe to pass the argument register value unchanged as the 9689 // return register value (although it's at the target's option whether 9690 // to do so) 9691 // TODO: allow code generation to take advantage of partially preserved 9692 // registers rather than clobbering the entire register when the 9693 // parameter extension method is not compatible with the return 9694 // extension method 9695 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9696 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9697 CLI.RetZExt == Args[i].IsZExt)) 9698 Flags.setReturned(); 9699 } 9700 9701 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9702 CLI.CallConv, ExtendKind); 9703 9704 for (unsigned j = 0; j != NumParts; ++j) { 9705 // if it isn't first piece, alignment must be 1 9706 // For scalable vectors the scalable part is currently handled 9707 // by individual targets, so we just use the known minimum size here. 9708 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9709 i < CLI.NumFixedArgs, i, 9710 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9711 if (NumParts > 1 && j == 0) 9712 MyFlags.Flags.setSplit(); 9713 else if (j != 0) { 9714 MyFlags.Flags.setOrigAlign(Align(1)); 9715 if (j == NumParts - 1) 9716 MyFlags.Flags.setSplitEnd(); 9717 } 9718 9719 CLI.Outs.push_back(MyFlags); 9720 CLI.OutVals.push_back(Parts[j]); 9721 } 9722 9723 if (NeedsRegBlock && Value == NumValues - 1) 9724 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9725 } 9726 } 9727 9728 SmallVector<SDValue, 4> InVals; 9729 CLI.Chain = LowerCall(CLI, InVals); 9730 9731 // Update CLI.InVals to use outside of this function. 9732 CLI.InVals = InVals; 9733 9734 // Verify that the target's LowerCall behaved as expected. 9735 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9736 "LowerCall didn't return a valid chain!"); 9737 assert((!CLI.IsTailCall || InVals.empty()) && 9738 "LowerCall emitted a return value for a tail call!"); 9739 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9740 "LowerCall didn't emit the correct number of values!"); 9741 9742 // For a tail call, the return value is merely live-out and there aren't 9743 // any nodes in the DAG representing it. Return a special value to 9744 // indicate that a tail call has been emitted and no more Instructions 9745 // should be processed in the current block. 9746 if (CLI.IsTailCall) { 9747 CLI.DAG.setRoot(CLI.Chain); 9748 return std::make_pair(SDValue(), SDValue()); 9749 } 9750 9751 #ifndef NDEBUG 9752 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9753 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9754 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9755 "LowerCall emitted a value with the wrong type!"); 9756 } 9757 #endif 9758 9759 SmallVector<SDValue, 4> ReturnValues; 9760 if (!CanLowerReturn) { 9761 // The instruction result is the result of loading from the 9762 // hidden sret parameter. 9763 SmallVector<EVT, 1> PVTs; 9764 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9765 9766 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9767 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9768 EVT PtrVT = PVTs[0]; 9769 9770 unsigned NumValues = RetTys.size(); 9771 ReturnValues.resize(NumValues); 9772 SmallVector<SDValue, 4> Chains(NumValues); 9773 9774 // An aggregate return value cannot wrap around the address space, so 9775 // offsets to its parts don't wrap either. 9776 SDNodeFlags Flags; 9777 Flags.setNoUnsignedWrap(true); 9778 9779 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9780 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9781 for (unsigned i = 0; i < NumValues; ++i) { 9782 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9783 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9784 PtrVT), Flags); 9785 SDValue L = CLI.DAG.getLoad( 9786 RetTys[i], CLI.DL, CLI.Chain, Add, 9787 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9788 DemoteStackIdx, Offsets[i]), 9789 HiddenSRetAlign); 9790 ReturnValues[i] = L; 9791 Chains[i] = L.getValue(1); 9792 } 9793 9794 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9795 } else { 9796 // Collect the legal value parts into potentially illegal values 9797 // that correspond to the original function's return values. 9798 Optional<ISD::NodeType> AssertOp; 9799 if (CLI.RetSExt) 9800 AssertOp = ISD::AssertSext; 9801 else if (CLI.RetZExt) 9802 AssertOp = ISD::AssertZext; 9803 unsigned CurReg = 0; 9804 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9805 EVT VT = RetTys[I]; 9806 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9807 CLI.CallConv, VT); 9808 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9809 CLI.CallConv, VT); 9810 9811 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9812 NumRegs, RegisterVT, VT, nullptr, 9813 CLI.CallConv, AssertOp)); 9814 CurReg += NumRegs; 9815 } 9816 9817 // For a function returning void, there is no return value. We can't create 9818 // such a node, so we just return a null return value in that case. In 9819 // that case, nothing will actually look at the value. 9820 if (ReturnValues.empty()) 9821 return std::make_pair(SDValue(), CLI.Chain); 9822 } 9823 9824 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9825 CLI.DAG.getVTList(RetTys), ReturnValues); 9826 return std::make_pair(Res, CLI.Chain); 9827 } 9828 9829 /// Places new result values for the node in Results (their number 9830 /// and types must exactly match those of the original return values of 9831 /// the node), or leaves Results empty, which indicates that the node is not 9832 /// to be custom lowered after all. 9833 void TargetLowering::LowerOperationWrapper(SDNode *N, 9834 SmallVectorImpl<SDValue> &Results, 9835 SelectionDAG &DAG) const { 9836 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9837 9838 if (!Res.getNode()) 9839 return; 9840 9841 // If the original node has one result, take the return value from 9842 // LowerOperation as is. It might not be result number 0. 9843 if (N->getNumValues() == 1) { 9844 Results.push_back(Res); 9845 return; 9846 } 9847 9848 // If the original node has multiple results, then the return node should 9849 // have the same number of results. 9850 assert((N->getNumValues() == Res->getNumValues()) && 9851 "Lowering returned the wrong number of results!"); 9852 9853 // Places new result values base on N result number. 9854 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9855 Results.push_back(Res.getValue(I)); 9856 } 9857 9858 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9859 llvm_unreachable("LowerOperation not implemented for this target!"); 9860 } 9861 9862 static ISD::NodeType getPreferredExtendForValue(const Value *V) { 9863 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9864 9865 // TODO: Skip Arguments to match behavior when this was calculated only for 9866 // instructions. 9867 if (isa<Argument>(V)) 9868 return ExtendKind; 9869 9870 // For the users of the source value being used for compare instruction, if 9871 // the number of signed predicate is greater than unsigned predicate, we 9872 // prefer to use SIGN_EXTEND. 9873 // 9874 // With this optimization, we would be able to reduce some redundant sign or 9875 // zero extension instruction, and eventually more machine CSE opportunities 9876 // can be exposed. 9877 unsigned NumOfSigned = 0, NumOfUnsigned = 0; 9878 for (const User *U : V->users()) { 9879 if (const auto *CI = dyn_cast<CmpInst>(U)) { 9880 NumOfSigned += CI->isSigned(); 9881 NumOfUnsigned += CI->isUnsigned(); 9882 } 9883 } 9884 if (NumOfSigned > NumOfUnsigned) 9885 ExtendKind = ISD::SIGN_EXTEND; 9886 9887 return ExtendKind; 9888 } 9889 9890 void 9891 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9892 SDValue Op = getNonRegisterValue(V); 9893 assert((Op.getOpcode() != ISD::CopyFromReg || 9894 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9895 "Copy from a reg to the same reg!"); 9896 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9897 9898 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9899 // If this is an InlineAsm we have to match the registers required, not the 9900 // notional registers required by the type. 9901 9902 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9903 None); // This is not an ABI copy. 9904 SDValue Chain = DAG.getEntryNode(); 9905 9906 // Look up the preferred extend kind if we've already computed it. Otherwise, 9907 // compute it and cache it. 9908 ISD::NodeType &ExtendType = FuncInfo.PreferredExtendType[V]; 9909 if (!ExtendType) 9910 ExtendType = getPreferredExtendForValue(V); 9911 9912 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9913 PendingExports.push_back(Chain); 9914 } 9915 9916 #include "llvm/CodeGen/SelectionDAGISel.h" 9917 9918 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9919 /// entry block, return true. This includes arguments used by switches, since 9920 /// the switch may expand into multiple basic blocks. 9921 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9922 // With FastISel active, we may be splitting blocks, so force creation 9923 // of virtual registers for all non-dead arguments. 9924 if (FastISel) 9925 return A->use_empty(); 9926 9927 const BasicBlock &Entry = A->getParent()->front(); 9928 for (const User *U : A->users()) 9929 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9930 return false; // Use not in entry block. 9931 9932 return true; 9933 } 9934 9935 using ArgCopyElisionMapTy = 9936 DenseMap<const Argument *, 9937 std::pair<const AllocaInst *, const StoreInst *>>; 9938 9939 /// Scan the entry block of the function in FuncInfo for arguments that look 9940 /// like copies into a local alloca. Record any copied arguments in 9941 /// ArgCopyElisionCandidates. 9942 static void 9943 findArgumentCopyElisionCandidates(const DataLayout &DL, 9944 FunctionLoweringInfo *FuncInfo, 9945 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9946 // Record the state of every static alloca used in the entry block. Argument 9947 // allocas are all used in the entry block, so we need approximately as many 9948 // entries as we have arguments. 9949 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9950 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9951 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9952 StaticAllocas.reserve(NumArgs * 2); 9953 9954 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9955 if (!V) 9956 return nullptr; 9957 V = V->stripPointerCasts(); 9958 const auto *AI = dyn_cast<AllocaInst>(V); 9959 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9960 return nullptr; 9961 auto Iter = StaticAllocas.insert({AI, Unknown}); 9962 return &Iter.first->second; 9963 }; 9964 9965 // Look for stores of arguments to static allocas. Look through bitcasts and 9966 // GEPs to handle type coercions, as long as the alloca is fully initialized 9967 // by the store. Any non-store use of an alloca escapes it and any subsequent 9968 // unanalyzed store might write it. 9969 // FIXME: Handle structs initialized with multiple stores. 9970 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9971 // Look for stores, and handle non-store uses conservatively. 9972 const auto *SI = dyn_cast<StoreInst>(&I); 9973 if (!SI) { 9974 // We will look through cast uses, so ignore them completely. 9975 if (I.isCast()) 9976 continue; 9977 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9978 // to allocas. 9979 if (I.isDebugOrPseudoInst()) 9980 continue; 9981 // This is an unknown instruction. Assume it escapes or writes to all 9982 // static alloca operands. 9983 for (const Use &U : I.operands()) { 9984 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9985 *Info = StaticAllocaInfo::Clobbered; 9986 } 9987 continue; 9988 } 9989 9990 // If the stored value is a static alloca, mark it as escaped. 9991 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9992 *Info = StaticAllocaInfo::Clobbered; 9993 9994 // Check if the destination is a static alloca. 9995 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9996 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9997 if (!Info) 9998 continue; 9999 const AllocaInst *AI = cast<AllocaInst>(Dst); 10000 10001 // Skip allocas that have been initialized or clobbered. 10002 if (*Info != StaticAllocaInfo::Unknown) 10003 continue; 10004 10005 // Check if the stored value is an argument, and that this store fully 10006 // initializes the alloca. 10007 // If the argument type has padding bits we can't directly forward a pointer 10008 // as the upper bits may contain garbage. 10009 // Don't elide copies from the same argument twice. 10010 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10011 const auto *Arg = dyn_cast<Argument>(Val); 10012 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10013 Arg->getType()->isEmptyTy() || 10014 DL.getTypeStoreSize(Arg->getType()) != 10015 DL.getTypeAllocSize(AI->getAllocatedType()) || 10016 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10017 ArgCopyElisionCandidates.count(Arg)) { 10018 *Info = StaticAllocaInfo::Clobbered; 10019 continue; 10020 } 10021 10022 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10023 << '\n'); 10024 10025 // Mark this alloca and store for argument copy elision. 10026 *Info = StaticAllocaInfo::Elidable; 10027 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10028 10029 // Stop scanning if we've seen all arguments. This will happen early in -O0 10030 // builds, which is useful, because -O0 builds have large entry blocks and 10031 // many allocas. 10032 if (ArgCopyElisionCandidates.size() == NumArgs) 10033 break; 10034 } 10035 } 10036 10037 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10038 /// ArgVal is a load from a suitable fixed stack object. 10039 static void tryToElideArgumentCopy( 10040 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10041 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10042 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10043 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10044 SDValue ArgVal, bool &ArgHasUses) { 10045 // Check if this is a load from a fixed stack object. 10046 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10047 if (!LNode) 10048 return; 10049 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10050 if (!FINode) 10051 return; 10052 10053 // Check that the fixed stack object is the right size and alignment. 10054 // Look at the alignment that the user wrote on the alloca instead of looking 10055 // at the stack object. 10056 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10057 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10058 const AllocaInst *AI = ArgCopyIter->second.first; 10059 int FixedIndex = FINode->getIndex(); 10060 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10061 int OldIndex = AllocaIndex; 10062 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10063 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10064 LLVM_DEBUG( 10065 dbgs() << " argument copy elision failed due to bad fixed stack " 10066 "object size\n"); 10067 return; 10068 } 10069 Align RequiredAlignment = AI->getAlign(); 10070 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10071 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10072 "greater than stack argument alignment (" 10073 << DebugStr(RequiredAlignment) << " vs " 10074 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10075 return; 10076 } 10077 10078 // Perform the elision. Delete the old stack object and replace its only use 10079 // in the variable info map. Mark the stack object as mutable. 10080 LLVM_DEBUG({ 10081 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10082 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10083 << '\n'; 10084 }); 10085 MFI.RemoveStackObject(OldIndex); 10086 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10087 AllocaIndex = FixedIndex; 10088 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10089 Chains.push_back(ArgVal.getValue(1)); 10090 10091 // Avoid emitting code for the store implementing the copy. 10092 const StoreInst *SI = ArgCopyIter->second.second; 10093 ElidedArgCopyInstrs.insert(SI); 10094 10095 // Check for uses of the argument again so that we can avoid exporting ArgVal 10096 // if it is't used by anything other than the store. 10097 for (const Value *U : Arg.users()) { 10098 if (U != SI) { 10099 ArgHasUses = true; 10100 break; 10101 } 10102 } 10103 } 10104 10105 void SelectionDAGISel::LowerArguments(const Function &F) { 10106 SelectionDAG &DAG = SDB->DAG; 10107 SDLoc dl = SDB->getCurSDLoc(); 10108 const DataLayout &DL = DAG.getDataLayout(); 10109 SmallVector<ISD::InputArg, 16> Ins; 10110 10111 // In Naked functions we aren't going to save any registers. 10112 if (F.hasFnAttribute(Attribute::Naked)) 10113 return; 10114 10115 if (!FuncInfo->CanLowerReturn) { 10116 // Put in an sret pointer parameter before all the other parameters. 10117 SmallVector<EVT, 1> ValueVTs; 10118 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10119 F.getReturnType()->getPointerTo( 10120 DAG.getDataLayout().getAllocaAddrSpace()), 10121 ValueVTs); 10122 10123 // NOTE: Assuming that a pointer will never break down to more than one VT 10124 // or one register. 10125 ISD::ArgFlagsTy Flags; 10126 Flags.setSRet(); 10127 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10128 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10129 ISD::InputArg::NoArgIndex, 0); 10130 Ins.push_back(RetArg); 10131 } 10132 10133 // Look for stores of arguments to static allocas. Mark such arguments with a 10134 // flag to ask the target to give us the memory location of that argument if 10135 // available. 10136 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10137 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10138 ArgCopyElisionCandidates); 10139 10140 // Set up the incoming argument description vector. 10141 for (const Argument &Arg : F.args()) { 10142 unsigned ArgNo = Arg.getArgNo(); 10143 SmallVector<EVT, 4> ValueVTs; 10144 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10145 bool isArgValueUsed = !Arg.use_empty(); 10146 unsigned PartBase = 0; 10147 Type *FinalType = Arg.getType(); 10148 if (Arg.hasAttribute(Attribute::ByVal)) 10149 FinalType = Arg.getParamByValType(); 10150 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10151 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10152 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10153 Value != NumValues; ++Value) { 10154 EVT VT = ValueVTs[Value]; 10155 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10156 ISD::ArgFlagsTy Flags; 10157 10158 10159 if (Arg.getType()->isPointerTy()) { 10160 Flags.setPointer(); 10161 Flags.setPointerAddrSpace( 10162 cast<PointerType>(Arg.getType())->getAddressSpace()); 10163 } 10164 if (Arg.hasAttribute(Attribute::ZExt)) 10165 Flags.setZExt(); 10166 if (Arg.hasAttribute(Attribute::SExt)) 10167 Flags.setSExt(); 10168 if (Arg.hasAttribute(Attribute::InReg)) { 10169 // If we are using vectorcall calling convention, a structure that is 10170 // passed InReg - is surely an HVA 10171 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10172 isa<StructType>(Arg.getType())) { 10173 // The first value of a structure is marked 10174 if (0 == Value) 10175 Flags.setHvaStart(); 10176 Flags.setHva(); 10177 } 10178 // Set InReg Flag 10179 Flags.setInReg(); 10180 } 10181 if (Arg.hasAttribute(Attribute::StructRet)) 10182 Flags.setSRet(); 10183 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10184 Flags.setSwiftSelf(); 10185 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10186 Flags.setSwiftAsync(); 10187 if (Arg.hasAttribute(Attribute::SwiftError)) 10188 Flags.setSwiftError(); 10189 if (Arg.hasAttribute(Attribute::ByVal)) 10190 Flags.setByVal(); 10191 if (Arg.hasAttribute(Attribute::ByRef)) 10192 Flags.setByRef(); 10193 if (Arg.hasAttribute(Attribute::InAlloca)) { 10194 Flags.setInAlloca(); 10195 // Set the byval flag for CCAssignFn callbacks that don't know about 10196 // inalloca. This way we can know how many bytes we should've allocated 10197 // and how many bytes a callee cleanup function will pop. If we port 10198 // inalloca to more targets, we'll have to add custom inalloca handling 10199 // in the various CC lowering callbacks. 10200 Flags.setByVal(); 10201 } 10202 if (Arg.hasAttribute(Attribute::Preallocated)) { 10203 Flags.setPreallocated(); 10204 // Set the byval flag for CCAssignFn callbacks that don't know about 10205 // preallocated. This way we can know how many bytes we should've 10206 // allocated and how many bytes a callee cleanup function will pop. If 10207 // we port preallocated to more targets, we'll have to add custom 10208 // preallocated handling in the various CC lowering callbacks. 10209 Flags.setByVal(); 10210 } 10211 10212 // Certain targets (such as MIPS), may have a different ABI alignment 10213 // for a type depending on the context. Give the target a chance to 10214 // specify the alignment it wants. 10215 const Align OriginalAlignment( 10216 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10217 Flags.setOrigAlign(OriginalAlignment); 10218 10219 Align MemAlign; 10220 Type *ArgMemTy = nullptr; 10221 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10222 Flags.isByRef()) { 10223 if (!ArgMemTy) 10224 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10225 10226 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10227 10228 // For in-memory arguments, size and alignment should be passed from FE. 10229 // BE will guess if this info is not there but there are cases it cannot 10230 // get right. 10231 if (auto ParamAlign = Arg.getParamStackAlign()) 10232 MemAlign = *ParamAlign; 10233 else if ((ParamAlign = Arg.getParamAlign())) 10234 MemAlign = *ParamAlign; 10235 else 10236 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10237 if (Flags.isByRef()) 10238 Flags.setByRefSize(MemSize); 10239 else 10240 Flags.setByValSize(MemSize); 10241 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10242 MemAlign = *ParamAlign; 10243 } else { 10244 MemAlign = OriginalAlignment; 10245 } 10246 Flags.setMemAlign(MemAlign); 10247 10248 if (Arg.hasAttribute(Attribute::Nest)) 10249 Flags.setNest(); 10250 if (NeedsRegBlock) 10251 Flags.setInConsecutiveRegs(); 10252 if (ArgCopyElisionCandidates.count(&Arg)) 10253 Flags.setCopyElisionCandidate(); 10254 if (Arg.hasAttribute(Attribute::Returned)) 10255 Flags.setReturned(); 10256 10257 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10258 *CurDAG->getContext(), F.getCallingConv(), VT); 10259 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10260 *CurDAG->getContext(), F.getCallingConv(), VT); 10261 for (unsigned i = 0; i != NumRegs; ++i) { 10262 // For scalable vectors, use the minimum size; individual targets 10263 // are responsible for handling scalable vector arguments and 10264 // return values. 10265 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10266 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10267 if (NumRegs > 1 && i == 0) 10268 MyFlags.Flags.setSplit(); 10269 // if it isn't first piece, alignment must be 1 10270 else if (i > 0) { 10271 MyFlags.Flags.setOrigAlign(Align(1)); 10272 if (i == NumRegs - 1) 10273 MyFlags.Flags.setSplitEnd(); 10274 } 10275 Ins.push_back(MyFlags); 10276 } 10277 if (NeedsRegBlock && Value == NumValues - 1) 10278 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10279 PartBase += VT.getStoreSize().getKnownMinSize(); 10280 } 10281 } 10282 10283 // Call the target to set up the argument values. 10284 SmallVector<SDValue, 8> InVals; 10285 SDValue NewRoot = TLI->LowerFormalArguments( 10286 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10287 10288 // Verify that the target's LowerFormalArguments behaved as expected. 10289 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10290 "LowerFormalArguments didn't return a valid chain!"); 10291 assert(InVals.size() == Ins.size() && 10292 "LowerFormalArguments didn't emit the correct number of values!"); 10293 LLVM_DEBUG({ 10294 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10295 assert(InVals[i].getNode() && 10296 "LowerFormalArguments emitted a null value!"); 10297 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10298 "LowerFormalArguments emitted a value with the wrong type!"); 10299 } 10300 }); 10301 10302 // Update the DAG with the new chain value resulting from argument lowering. 10303 DAG.setRoot(NewRoot); 10304 10305 // Set up the argument values. 10306 unsigned i = 0; 10307 if (!FuncInfo->CanLowerReturn) { 10308 // Create a virtual register for the sret pointer, and put in a copy 10309 // from the sret argument into it. 10310 SmallVector<EVT, 1> ValueVTs; 10311 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10312 F.getReturnType()->getPointerTo( 10313 DAG.getDataLayout().getAllocaAddrSpace()), 10314 ValueVTs); 10315 MVT VT = ValueVTs[0].getSimpleVT(); 10316 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10317 Optional<ISD::NodeType> AssertOp = None; 10318 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10319 nullptr, F.getCallingConv(), AssertOp); 10320 10321 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10322 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10323 Register SRetReg = 10324 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10325 FuncInfo->DemoteRegister = SRetReg; 10326 NewRoot = 10327 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10328 DAG.setRoot(NewRoot); 10329 10330 // i indexes lowered arguments. Bump it past the hidden sret argument. 10331 ++i; 10332 } 10333 10334 SmallVector<SDValue, 4> Chains; 10335 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10336 for (const Argument &Arg : F.args()) { 10337 SmallVector<SDValue, 4> ArgValues; 10338 SmallVector<EVT, 4> ValueVTs; 10339 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10340 unsigned NumValues = ValueVTs.size(); 10341 if (NumValues == 0) 10342 continue; 10343 10344 bool ArgHasUses = !Arg.use_empty(); 10345 10346 // Elide the copying store if the target loaded this argument from a 10347 // suitable fixed stack object. 10348 if (Ins[i].Flags.isCopyElisionCandidate()) { 10349 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10350 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10351 InVals[i], ArgHasUses); 10352 } 10353 10354 // If this argument is unused then remember its value. It is used to generate 10355 // debugging information. 10356 bool isSwiftErrorArg = 10357 TLI->supportSwiftError() && 10358 Arg.hasAttribute(Attribute::SwiftError); 10359 if (!ArgHasUses && !isSwiftErrorArg) { 10360 SDB->setUnusedArgValue(&Arg, InVals[i]); 10361 10362 // Also remember any frame index for use in FastISel. 10363 if (FrameIndexSDNode *FI = 10364 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10365 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10366 } 10367 10368 for (unsigned Val = 0; Val != NumValues; ++Val) { 10369 EVT VT = ValueVTs[Val]; 10370 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10371 F.getCallingConv(), VT); 10372 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10373 *CurDAG->getContext(), F.getCallingConv(), VT); 10374 10375 // Even an apparent 'unused' swifterror argument needs to be returned. So 10376 // we do generate a copy for it that can be used on return from the 10377 // function. 10378 if (ArgHasUses || isSwiftErrorArg) { 10379 Optional<ISD::NodeType> AssertOp; 10380 if (Arg.hasAttribute(Attribute::SExt)) 10381 AssertOp = ISD::AssertSext; 10382 else if (Arg.hasAttribute(Attribute::ZExt)) 10383 AssertOp = ISD::AssertZext; 10384 10385 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10386 PartVT, VT, nullptr, 10387 F.getCallingConv(), AssertOp)); 10388 } 10389 10390 i += NumParts; 10391 } 10392 10393 // We don't need to do anything else for unused arguments. 10394 if (ArgValues.empty()) 10395 continue; 10396 10397 // Note down frame index. 10398 if (FrameIndexSDNode *FI = 10399 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10400 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10401 10402 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10403 SDB->getCurSDLoc()); 10404 10405 SDB->setValue(&Arg, Res); 10406 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10407 // We want to associate the argument with the frame index, among 10408 // involved operands, that correspond to the lowest address. The 10409 // getCopyFromParts function, called earlier, is swapping the order of 10410 // the operands to BUILD_PAIR depending on endianness. The result of 10411 // that swapping is that the least significant bits of the argument will 10412 // be in the first operand of the BUILD_PAIR node, and the most 10413 // significant bits will be in the second operand. 10414 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10415 if (LoadSDNode *LNode = 10416 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10417 if (FrameIndexSDNode *FI = 10418 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10419 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10420 } 10421 10422 // Analyses past this point are naive and don't expect an assertion. 10423 if (Res.getOpcode() == ISD::AssertZext) 10424 Res = Res.getOperand(0); 10425 10426 // Update the SwiftErrorVRegDefMap. 10427 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10428 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10429 if (Register::isVirtualRegister(Reg)) 10430 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10431 Reg); 10432 } 10433 10434 // If this argument is live outside of the entry block, insert a copy from 10435 // wherever we got it to the vreg that other BB's will reference it as. 10436 if (Res.getOpcode() == ISD::CopyFromReg) { 10437 // If we can, though, try to skip creating an unnecessary vreg. 10438 // FIXME: This isn't very clean... it would be nice to make this more 10439 // general. 10440 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10441 if (Register::isVirtualRegister(Reg)) { 10442 FuncInfo->ValueMap[&Arg] = Reg; 10443 continue; 10444 } 10445 } 10446 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10447 FuncInfo->InitializeRegForValue(&Arg); 10448 SDB->CopyToExportRegsIfNeeded(&Arg); 10449 } 10450 } 10451 10452 if (!Chains.empty()) { 10453 Chains.push_back(NewRoot); 10454 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10455 } 10456 10457 DAG.setRoot(NewRoot); 10458 10459 assert(i == InVals.size() && "Argument register count mismatch!"); 10460 10461 // If any argument copy elisions occurred and we have debug info, update the 10462 // stale frame indices used in the dbg.declare variable info table. 10463 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10464 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10465 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10466 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10467 if (I != ArgCopyElisionFrameIndexMap.end()) 10468 VI.Slot = I->second; 10469 } 10470 } 10471 10472 // Finally, if the target has anything special to do, allow it to do so. 10473 emitFunctionEntryCode(); 10474 } 10475 10476 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10477 /// ensure constants are generated when needed. Remember the virtual registers 10478 /// that need to be added to the Machine PHI nodes as input. We cannot just 10479 /// directly add them, because expansion might result in multiple MBB's for one 10480 /// BB. As such, the start of the BB might correspond to a different MBB than 10481 /// the end. 10482 void 10483 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10484 const Instruction *TI = LLVMBB->getTerminator(); 10485 10486 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10487 10488 // Check PHI nodes in successors that expect a value to be available from this 10489 // block. 10490 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10491 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10492 if (!isa<PHINode>(SuccBB->begin())) continue; 10493 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10494 10495 // If this terminator has multiple identical successors (common for 10496 // switches), only handle each succ once. 10497 if (!SuccsHandled.insert(SuccMBB).second) 10498 continue; 10499 10500 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10501 10502 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10503 // nodes and Machine PHI nodes, but the incoming operands have not been 10504 // emitted yet. 10505 for (const PHINode &PN : SuccBB->phis()) { 10506 // Ignore dead phi's. 10507 if (PN.use_empty()) 10508 continue; 10509 10510 // Skip empty types 10511 if (PN.getType()->isEmptyTy()) 10512 continue; 10513 10514 unsigned Reg; 10515 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10516 10517 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10518 unsigned &RegOut = ConstantsOut[C]; 10519 if (RegOut == 0) { 10520 RegOut = FuncInfo.CreateRegs(C); 10521 CopyValueToVirtualRegister(C, RegOut); 10522 } 10523 Reg = RegOut; 10524 } else { 10525 DenseMap<const Value *, Register>::iterator I = 10526 FuncInfo.ValueMap.find(PHIOp); 10527 if (I != FuncInfo.ValueMap.end()) 10528 Reg = I->second; 10529 else { 10530 assert(isa<AllocaInst>(PHIOp) && 10531 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10532 "Didn't codegen value into a register!??"); 10533 Reg = FuncInfo.CreateRegs(PHIOp); 10534 CopyValueToVirtualRegister(PHIOp, Reg); 10535 } 10536 } 10537 10538 // Remember that this register needs to added to the machine PHI node as 10539 // the input for this MBB. 10540 SmallVector<EVT, 4> ValueVTs; 10541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10542 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10543 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10544 EVT VT = ValueVTs[vti]; 10545 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10546 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10547 FuncInfo.PHINodesToUpdate.push_back( 10548 std::make_pair(&*MBBI++, Reg + i)); 10549 Reg += NumRegisters; 10550 } 10551 } 10552 } 10553 10554 ConstantsOut.clear(); 10555 } 10556 10557 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10558 /// is 0. 10559 MachineBasicBlock * 10560 SelectionDAGBuilder::StackProtectorDescriptor:: 10561 AddSuccessorMBB(const BasicBlock *BB, 10562 MachineBasicBlock *ParentMBB, 10563 bool IsLikely, 10564 MachineBasicBlock *SuccMBB) { 10565 // If SuccBB has not been created yet, create it. 10566 if (!SuccMBB) { 10567 MachineFunction *MF = ParentMBB->getParent(); 10568 MachineFunction::iterator BBI(ParentMBB); 10569 SuccMBB = MF->CreateMachineBasicBlock(BB); 10570 MF->insert(++BBI, SuccMBB); 10571 } 10572 // Add it as a successor of ParentMBB. 10573 ParentMBB->addSuccessor( 10574 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10575 return SuccMBB; 10576 } 10577 10578 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10579 MachineFunction::iterator I(MBB); 10580 if (++I == FuncInfo.MF->end()) 10581 return nullptr; 10582 return &*I; 10583 } 10584 10585 /// During lowering new call nodes can be created (such as memset, etc.). 10586 /// Those will become new roots of the current DAG, but complications arise 10587 /// when they are tail calls. In such cases, the call lowering will update 10588 /// the root, but the builder still needs to know that a tail call has been 10589 /// lowered in order to avoid generating an additional return. 10590 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10591 // If the node is null, we do have a tail call. 10592 if (MaybeTC.getNode() != nullptr) 10593 DAG.setRoot(MaybeTC); 10594 else 10595 HasTailCall = true; 10596 } 10597 10598 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10599 MachineBasicBlock *SwitchMBB, 10600 MachineBasicBlock *DefaultMBB) { 10601 MachineFunction *CurMF = FuncInfo.MF; 10602 MachineBasicBlock *NextMBB = nullptr; 10603 MachineFunction::iterator BBI(W.MBB); 10604 if (++BBI != FuncInfo.MF->end()) 10605 NextMBB = &*BBI; 10606 10607 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10608 10609 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10610 10611 if (Size == 2 && W.MBB == SwitchMBB) { 10612 // If any two of the cases has the same destination, and if one value 10613 // is the same as the other, but has one bit unset that the other has set, 10614 // use bit manipulation to do two compares at once. For example: 10615 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10616 // TODO: This could be extended to merge any 2 cases in switches with 3 10617 // cases. 10618 // TODO: Handle cases where W.CaseBB != SwitchBB. 10619 CaseCluster &Small = *W.FirstCluster; 10620 CaseCluster &Big = *W.LastCluster; 10621 10622 if (Small.Low == Small.High && Big.Low == Big.High && 10623 Small.MBB == Big.MBB) { 10624 const APInt &SmallValue = Small.Low->getValue(); 10625 const APInt &BigValue = Big.Low->getValue(); 10626 10627 // Check that there is only one bit different. 10628 APInt CommonBit = BigValue ^ SmallValue; 10629 if (CommonBit.isPowerOf2()) { 10630 SDValue CondLHS = getValue(Cond); 10631 EVT VT = CondLHS.getValueType(); 10632 SDLoc DL = getCurSDLoc(); 10633 10634 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10635 DAG.getConstant(CommonBit, DL, VT)); 10636 SDValue Cond = DAG.getSetCC( 10637 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10638 ISD::SETEQ); 10639 10640 // Update successor info. 10641 // Both Small and Big will jump to Small.BB, so we sum up the 10642 // probabilities. 10643 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10644 if (BPI) 10645 addSuccessorWithProb( 10646 SwitchMBB, DefaultMBB, 10647 // The default destination is the first successor in IR. 10648 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10649 else 10650 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10651 10652 // Insert the true branch. 10653 SDValue BrCond = 10654 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10655 DAG.getBasicBlock(Small.MBB)); 10656 // Insert the false branch. 10657 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10658 DAG.getBasicBlock(DefaultMBB)); 10659 10660 DAG.setRoot(BrCond); 10661 return; 10662 } 10663 } 10664 } 10665 10666 if (TM.getOptLevel() != CodeGenOpt::None) { 10667 // Here, we order cases by probability so the most likely case will be 10668 // checked first. However, two clusters can have the same probability in 10669 // which case their relative ordering is non-deterministic. So we use Low 10670 // as a tie-breaker as clusters are guaranteed to never overlap. 10671 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10672 [](const CaseCluster &a, const CaseCluster &b) { 10673 return a.Prob != b.Prob ? 10674 a.Prob > b.Prob : 10675 a.Low->getValue().slt(b.Low->getValue()); 10676 }); 10677 10678 // Rearrange the case blocks so that the last one falls through if possible 10679 // without changing the order of probabilities. 10680 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10681 --I; 10682 if (I->Prob > W.LastCluster->Prob) 10683 break; 10684 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10685 std::swap(*I, *W.LastCluster); 10686 break; 10687 } 10688 } 10689 } 10690 10691 // Compute total probability. 10692 BranchProbability DefaultProb = W.DefaultProb; 10693 BranchProbability UnhandledProbs = DefaultProb; 10694 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10695 UnhandledProbs += I->Prob; 10696 10697 MachineBasicBlock *CurMBB = W.MBB; 10698 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10699 bool FallthroughUnreachable = false; 10700 MachineBasicBlock *Fallthrough; 10701 if (I == W.LastCluster) { 10702 // For the last cluster, fall through to the default destination. 10703 Fallthrough = DefaultMBB; 10704 FallthroughUnreachable = isa<UnreachableInst>( 10705 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10706 } else { 10707 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10708 CurMF->insert(BBI, Fallthrough); 10709 // Put Cond in a virtual register to make it available from the new blocks. 10710 ExportFromCurrentBlock(Cond); 10711 } 10712 UnhandledProbs -= I->Prob; 10713 10714 switch (I->Kind) { 10715 case CC_JumpTable: { 10716 // FIXME: Optimize away range check based on pivot comparisons. 10717 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10718 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10719 10720 // The jump block hasn't been inserted yet; insert it here. 10721 MachineBasicBlock *JumpMBB = JT->MBB; 10722 CurMF->insert(BBI, JumpMBB); 10723 10724 auto JumpProb = I->Prob; 10725 auto FallthroughProb = UnhandledProbs; 10726 10727 // If the default statement is a target of the jump table, we evenly 10728 // distribute the default probability to successors of CurMBB. Also 10729 // update the probability on the edge from JumpMBB to Fallthrough. 10730 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10731 SE = JumpMBB->succ_end(); 10732 SI != SE; ++SI) { 10733 if (*SI == DefaultMBB) { 10734 JumpProb += DefaultProb / 2; 10735 FallthroughProb -= DefaultProb / 2; 10736 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10737 JumpMBB->normalizeSuccProbs(); 10738 break; 10739 } 10740 } 10741 10742 if (FallthroughUnreachable) { 10743 // Skip the range check if the fallthrough block is unreachable. 10744 JTH->OmitRangeCheck = true; 10745 } 10746 10747 if (!JTH->OmitRangeCheck) 10748 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10749 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10750 CurMBB->normalizeSuccProbs(); 10751 10752 // The jump table header will be inserted in our current block, do the 10753 // range check, and fall through to our fallthrough block. 10754 JTH->HeaderBB = CurMBB; 10755 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10756 10757 // If we're in the right place, emit the jump table header right now. 10758 if (CurMBB == SwitchMBB) { 10759 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10760 JTH->Emitted = true; 10761 } 10762 break; 10763 } 10764 case CC_BitTests: { 10765 // FIXME: Optimize away range check based on pivot comparisons. 10766 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10767 10768 // The bit test blocks haven't been inserted yet; insert them here. 10769 for (BitTestCase &BTC : BTB->Cases) 10770 CurMF->insert(BBI, BTC.ThisBB); 10771 10772 // Fill in fields of the BitTestBlock. 10773 BTB->Parent = CurMBB; 10774 BTB->Default = Fallthrough; 10775 10776 BTB->DefaultProb = UnhandledProbs; 10777 // If the cases in bit test don't form a contiguous range, we evenly 10778 // distribute the probability on the edge to Fallthrough to two 10779 // successors of CurMBB. 10780 if (!BTB->ContiguousRange) { 10781 BTB->Prob += DefaultProb / 2; 10782 BTB->DefaultProb -= DefaultProb / 2; 10783 } 10784 10785 if (FallthroughUnreachable) { 10786 // Skip the range check if the fallthrough block is unreachable. 10787 BTB->OmitRangeCheck = true; 10788 } 10789 10790 // If we're in the right place, emit the bit test header right now. 10791 if (CurMBB == SwitchMBB) { 10792 visitBitTestHeader(*BTB, SwitchMBB); 10793 BTB->Emitted = true; 10794 } 10795 break; 10796 } 10797 case CC_Range: { 10798 const Value *RHS, *LHS, *MHS; 10799 ISD::CondCode CC; 10800 if (I->Low == I->High) { 10801 // Check Cond == I->Low. 10802 CC = ISD::SETEQ; 10803 LHS = Cond; 10804 RHS=I->Low; 10805 MHS = nullptr; 10806 } else { 10807 // Check I->Low <= Cond <= I->High. 10808 CC = ISD::SETLE; 10809 LHS = I->Low; 10810 MHS = Cond; 10811 RHS = I->High; 10812 } 10813 10814 // If Fallthrough is unreachable, fold away the comparison. 10815 if (FallthroughUnreachable) 10816 CC = ISD::SETTRUE; 10817 10818 // The false probability is the sum of all unhandled cases. 10819 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10820 getCurSDLoc(), I->Prob, UnhandledProbs); 10821 10822 if (CurMBB == SwitchMBB) 10823 visitSwitchCase(CB, SwitchMBB); 10824 else 10825 SL->SwitchCases.push_back(CB); 10826 10827 break; 10828 } 10829 } 10830 CurMBB = Fallthrough; 10831 } 10832 } 10833 10834 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10835 CaseClusterIt First, 10836 CaseClusterIt Last) { 10837 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10838 if (X.Prob != CC.Prob) 10839 return X.Prob > CC.Prob; 10840 10841 // Ties are broken by comparing the case value. 10842 return X.Low->getValue().slt(CC.Low->getValue()); 10843 }); 10844 } 10845 10846 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10847 const SwitchWorkListItem &W, 10848 Value *Cond, 10849 MachineBasicBlock *SwitchMBB) { 10850 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10851 "Clusters not sorted?"); 10852 10853 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10854 10855 // Balance the tree based on branch probabilities to create a near-optimal (in 10856 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10857 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10858 CaseClusterIt LastLeft = W.FirstCluster; 10859 CaseClusterIt FirstRight = W.LastCluster; 10860 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10861 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10862 10863 // Move LastLeft and FirstRight towards each other from opposite directions to 10864 // find a partitioning of the clusters which balances the probability on both 10865 // sides. If LeftProb and RightProb are equal, alternate which side is 10866 // taken to ensure 0-probability nodes are distributed evenly. 10867 unsigned I = 0; 10868 while (LastLeft + 1 < FirstRight) { 10869 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10870 LeftProb += (++LastLeft)->Prob; 10871 else 10872 RightProb += (--FirstRight)->Prob; 10873 I++; 10874 } 10875 10876 while (true) { 10877 // Our binary search tree differs from a typical BST in that ours can have up 10878 // to three values in each leaf. The pivot selection above doesn't take that 10879 // into account, which means the tree might require more nodes and be less 10880 // efficient. We compensate for this here. 10881 10882 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10883 unsigned NumRight = W.LastCluster - FirstRight + 1; 10884 10885 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10886 // If one side has less than 3 clusters, and the other has more than 3, 10887 // consider taking a cluster from the other side. 10888 10889 if (NumLeft < NumRight) { 10890 // Consider moving the first cluster on the right to the left side. 10891 CaseCluster &CC = *FirstRight; 10892 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10893 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10894 if (LeftSideRank <= RightSideRank) { 10895 // Moving the cluster to the left does not demote it. 10896 ++LastLeft; 10897 ++FirstRight; 10898 continue; 10899 } 10900 } else { 10901 assert(NumRight < NumLeft); 10902 // Consider moving the last element on the left to the right side. 10903 CaseCluster &CC = *LastLeft; 10904 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10905 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10906 if (RightSideRank <= LeftSideRank) { 10907 // Moving the cluster to the right does not demot it. 10908 --LastLeft; 10909 --FirstRight; 10910 continue; 10911 } 10912 } 10913 } 10914 break; 10915 } 10916 10917 assert(LastLeft + 1 == FirstRight); 10918 assert(LastLeft >= W.FirstCluster); 10919 assert(FirstRight <= W.LastCluster); 10920 10921 // Use the first element on the right as pivot since we will make less-than 10922 // comparisons against it. 10923 CaseClusterIt PivotCluster = FirstRight; 10924 assert(PivotCluster > W.FirstCluster); 10925 assert(PivotCluster <= W.LastCluster); 10926 10927 CaseClusterIt FirstLeft = W.FirstCluster; 10928 CaseClusterIt LastRight = W.LastCluster; 10929 10930 const ConstantInt *Pivot = PivotCluster->Low; 10931 10932 // New blocks will be inserted immediately after the current one. 10933 MachineFunction::iterator BBI(W.MBB); 10934 ++BBI; 10935 10936 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10937 // we can branch to its destination directly if it's squeezed exactly in 10938 // between the known lower bound and Pivot - 1. 10939 MachineBasicBlock *LeftMBB; 10940 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10941 FirstLeft->Low == W.GE && 10942 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10943 LeftMBB = FirstLeft->MBB; 10944 } else { 10945 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10946 FuncInfo.MF->insert(BBI, LeftMBB); 10947 WorkList.push_back( 10948 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10949 // Put Cond in a virtual register to make it available from the new blocks. 10950 ExportFromCurrentBlock(Cond); 10951 } 10952 10953 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10954 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10955 // directly if RHS.High equals the current upper bound. 10956 MachineBasicBlock *RightMBB; 10957 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10958 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10959 RightMBB = FirstRight->MBB; 10960 } else { 10961 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10962 FuncInfo.MF->insert(BBI, RightMBB); 10963 WorkList.push_back( 10964 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10965 // Put Cond in a virtual register to make it available from the new blocks. 10966 ExportFromCurrentBlock(Cond); 10967 } 10968 10969 // Create the CaseBlock record that will be used to lower the branch. 10970 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10971 getCurSDLoc(), LeftProb, RightProb); 10972 10973 if (W.MBB == SwitchMBB) 10974 visitSwitchCase(CB, SwitchMBB); 10975 else 10976 SL->SwitchCases.push_back(CB); 10977 } 10978 10979 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10980 // from the swith statement. 10981 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10982 BranchProbability PeeledCaseProb) { 10983 if (PeeledCaseProb == BranchProbability::getOne()) 10984 return BranchProbability::getZero(); 10985 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10986 10987 uint32_t Numerator = CaseProb.getNumerator(); 10988 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10989 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10990 } 10991 10992 // Try to peel the top probability case if it exceeds the threshold. 10993 // Return current MachineBasicBlock for the switch statement if the peeling 10994 // does not occur. 10995 // If the peeling is performed, return the newly created MachineBasicBlock 10996 // for the peeled switch statement. Also update Clusters to remove the peeled 10997 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10998 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10999 const SwitchInst &SI, CaseClusterVector &Clusters, 11000 BranchProbability &PeeledCaseProb) { 11001 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11002 // Don't perform if there is only one cluster or optimizing for size. 11003 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11004 TM.getOptLevel() == CodeGenOpt::None || 11005 SwitchMBB->getParent()->getFunction().hasMinSize()) 11006 return SwitchMBB; 11007 11008 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11009 unsigned PeeledCaseIndex = 0; 11010 bool SwitchPeeled = false; 11011 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11012 CaseCluster &CC = Clusters[Index]; 11013 if (CC.Prob < TopCaseProb) 11014 continue; 11015 TopCaseProb = CC.Prob; 11016 PeeledCaseIndex = Index; 11017 SwitchPeeled = true; 11018 } 11019 if (!SwitchPeeled) 11020 return SwitchMBB; 11021 11022 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11023 << TopCaseProb << "\n"); 11024 11025 // Record the MBB for the peeled switch statement. 11026 MachineFunction::iterator BBI(SwitchMBB); 11027 ++BBI; 11028 MachineBasicBlock *PeeledSwitchMBB = 11029 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11030 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11031 11032 ExportFromCurrentBlock(SI.getCondition()); 11033 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11034 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11035 nullptr, nullptr, TopCaseProb.getCompl()}; 11036 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11037 11038 Clusters.erase(PeeledCaseIt); 11039 for (CaseCluster &CC : Clusters) { 11040 LLVM_DEBUG( 11041 dbgs() << "Scale the probablity for one cluster, before scaling: " 11042 << CC.Prob << "\n"); 11043 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11044 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11045 } 11046 PeeledCaseProb = TopCaseProb; 11047 return PeeledSwitchMBB; 11048 } 11049 11050 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11051 // Extract cases from the switch. 11052 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11053 CaseClusterVector Clusters; 11054 Clusters.reserve(SI.getNumCases()); 11055 for (auto I : SI.cases()) { 11056 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11057 const ConstantInt *CaseVal = I.getCaseValue(); 11058 BranchProbability Prob = 11059 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11060 : BranchProbability(1, SI.getNumCases() + 1); 11061 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11062 } 11063 11064 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11065 11066 // Cluster adjacent cases with the same destination. We do this at all 11067 // optimization levels because it's cheap to do and will make codegen faster 11068 // if there are many clusters. 11069 sortAndRangeify(Clusters); 11070 11071 // The branch probablity of the peeled case. 11072 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11073 MachineBasicBlock *PeeledSwitchMBB = 11074 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11075 11076 // If there is only the default destination, jump there directly. 11077 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11078 if (Clusters.empty()) { 11079 assert(PeeledSwitchMBB == SwitchMBB); 11080 SwitchMBB->addSuccessor(DefaultMBB); 11081 if (DefaultMBB != NextBlock(SwitchMBB)) { 11082 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11083 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11084 } 11085 return; 11086 } 11087 11088 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11089 SL->findBitTestClusters(Clusters, &SI); 11090 11091 LLVM_DEBUG({ 11092 dbgs() << "Case clusters: "; 11093 for (const CaseCluster &C : Clusters) { 11094 if (C.Kind == CC_JumpTable) 11095 dbgs() << "JT:"; 11096 if (C.Kind == CC_BitTests) 11097 dbgs() << "BT:"; 11098 11099 C.Low->getValue().print(dbgs(), true); 11100 if (C.Low != C.High) { 11101 dbgs() << '-'; 11102 C.High->getValue().print(dbgs(), true); 11103 } 11104 dbgs() << ' '; 11105 } 11106 dbgs() << '\n'; 11107 }); 11108 11109 assert(!Clusters.empty()); 11110 SwitchWorkList WorkList; 11111 CaseClusterIt First = Clusters.begin(); 11112 CaseClusterIt Last = Clusters.end() - 1; 11113 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11114 // Scale the branchprobability for DefaultMBB if the peel occurs and 11115 // DefaultMBB is not replaced. 11116 if (PeeledCaseProb != BranchProbability::getZero() && 11117 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11118 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11119 WorkList.push_back( 11120 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11121 11122 while (!WorkList.empty()) { 11123 SwitchWorkListItem W = WorkList.pop_back_val(); 11124 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11125 11126 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11127 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11128 // For optimized builds, lower large range as a balanced binary tree. 11129 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11130 continue; 11131 } 11132 11133 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11134 } 11135 } 11136 11137 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11138 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11139 auto DL = getCurSDLoc(); 11140 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11141 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11142 } 11143 11144 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11145 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11146 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11147 11148 SDLoc DL = getCurSDLoc(); 11149 SDValue V = getValue(I.getOperand(0)); 11150 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11151 11152 if (VT.isScalableVector()) { 11153 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11154 return; 11155 } 11156 11157 // Use VECTOR_SHUFFLE for the fixed-length vector 11158 // to maintain existing behavior. 11159 SmallVector<int, 8> Mask; 11160 unsigned NumElts = VT.getVectorMinNumElements(); 11161 for (unsigned i = 0; i != NumElts; ++i) 11162 Mask.push_back(NumElts - 1 - i); 11163 11164 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11165 } 11166 11167 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11168 SmallVector<EVT, 4> ValueVTs; 11169 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11170 ValueVTs); 11171 unsigned NumValues = ValueVTs.size(); 11172 if (NumValues == 0) return; 11173 11174 SmallVector<SDValue, 4> Values(NumValues); 11175 SDValue Op = getValue(I.getOperand(0)); 11176 11177 for (unsigned i = 0; i != NumValues; ++i) 11178 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11179 SDValue(Op.getNode(), Op.getResNo() + i)); 11180 11181 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11182 DAG.getVTList(ValueVTs), Values)); 11183 } 11184 11185 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11186 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11187 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11188 11189 SDLoc DL = getCurSDLoc(); 11190 SDValue V1 = getValue(I.getOperand(0)); 11191 SDValue V2 = getValue(I.getOperand(1)); 11192 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11193 11194 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11195 if (VT.isScalableVector()) { 11196 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11197 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11198 DAG.getConstant(Imm, DL, IdxVT))); 11199 return; 11200 } 11201 11202 unsigned NumElts = VT.getVectorNumElements(); 11203 11204 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11205 // Result is undefined if immediate is out-of-bounds. 11206 setValue(&I, DAG.getUNDEF(VT)); 11207 return; 11208 } 11209 11210 uint64_t Idx = (NumElts + Imm) % NumElts; 11211 11212 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11213 SmallVector<int, 8> Mask; 11214 for (unsigned i = 0; i < NumElts; ++i) 11215 Mask.push_back(Idx + i); 11216 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11217 } 11218