1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //===----------------------------------------------------------------------===//
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BranchProbabilityInfo.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/EHPersonalities.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/FunctionLoweringInfo.h"
40 #include "llvm/CodeGen/GCMetadata.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineJumpTableInfo.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RuntimeLibcalls.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
56 #include "llvm/CodeGen/StackMaps.h"
57 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/PatternMatch.h"
92 #include "llvm/IR/Statepoint.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/User.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/MC/MCContext.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/Support/AtomicOrdering.h"
99 #include "llvm/Support/BranchProbability.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CodeGen.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/MachineValueType.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include "llvm/Target/TargetIntrinsicInfo.h"
110 #include "llvm/Target/TargetMachine.h"
111 #include "llvm/Target/TargetOptions.h"
112 #include "llvm/Transforms/Utils/Local.h"
125 using namespace llvm;
126 using namespace PatternMatch;
127 using namespace SwitchCG;
129 #define DEBUG_TYPE "isel"
131 /// LimitFloatPrecision - Generate low-precision inline sequences for
132 /// some float libcalls (6, 8 or 12 bits).
133 static unsigned LimitFloatPrecision;
135 static cl::opt<unsigned, true>
136 LimitFPPrecision("limit-float-precision",
137 cl::desc("Generate low-precision inline sequences "
138 "for some float libcalls"),
139 cl::location(LimitFloatPrecision), cl::Hidden,
142 static cl::opt<unsigned> SwitchPeelThreshold(
143 "switch-peel-threshold", cl::Hidden, cl::init(66),
144 cl::desc("Set the case probability threshold for peeling the case from a "
145 "switch statement. A value greater than 100 will void this "
148 // Limit the width of DAG chains. This is important in general to prevent
149 // DAG-based analysis from blowing up. For example, alias analysis and
150 // load clustering may not complete in reasonable time. It is difficult to
151 // recognize and avoid this situation within each individual analysis, and
152 // future analyses are likely to have the same behavior. Limiting DAG width is
153 // the safe approach and will be especially important with global DAGs.
155 // MaxParallelChains default is arbitrarily high to avoid affecting
156 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
157 // sequence over this should have been converted to llvm.memcpy by the
158 // frontend. It is easy to induce this behavior with .ll code such as:
159 // %buffer = alloca [4096 x i8]
160 // %data = load [4096 x i8]* %argPtr
161 // store [4096 x i8] %data, [4096 x i8]* %buffer
162 static const unsigned MaxParallelChains = 64;
164 // Return the calling convention if the Value passed requires ABI mangling as it
165 // is a parameter to a function or a return value from a function which is not
167 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
168 if (auto *R = dyn_cast<ReturnInst>(V))
169 return R->getParent()->getParent()->getCallingConv();
171 if (auto *CI = dyn_cast<CallInst>(V)) {
172 const bool IsInlineAsm = CI->isInlineAsm();
173 const bool IsIndirectFunctionCall =
174 !IsInlineAsm && !CI->getCalledFunction();
176 // It is possible that the call instruction is an inline asm statement or an
177 // indirect function call in which case the return value of
178 // getCalledFunction() would be nullptr.
179 const bool IsInstrinsicCall =
180 !IsInlineAsm && !IsIndirectFunctionCall &&
181 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
183 if (!IsInlineAsm && !IsInstrinsicCall)
184 return CI->getCallingConv();
190 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
191 const SDValue *Parts, unsigned NumParts,
192 MVT PartVT, EVT ValueVT, const Value *V,
193 Optional<CallingConv::ID> CC);
195 /// getCopyFromParts - Create a value that contains the specified legal parts
196 /// combined into the value they represent. If the parts combine to a type
197 /// larger than ValueVT then AssertOp can be used to specify whether the extra
198 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
199 /// (ISD::AssertSext).
200 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
201 const SDValue *Parts, unsigned NumParts,
202 MVT PartVT, EVT ValueVT, const Value *V,
203 Optional<CallingConv::ID> CC = None,
204 Optional<ISD::NodeType> AssertOp = None) {
205 if (ValueVT.isVector())
206 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
209 assert(NumParts > 0 && "No parts to assemble!");
210 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
211 SDValue Val = Parts[0];
214 // Assemble the value from multiple parts.
215 if (ValueVT.isInteger()) {
216 unsigned PartBits = PartVT.getSizeInBits();
217 unsigned ValueBits = ValueVT.getSizeInBits();
219 // Assemble the power of 2 part.
220 unsigned RoundParts =
221 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
222 unsigned RoundBits = PartBits * RoundParts;
223 EVT RoundVT = RoundBits == ValueBits ?
224 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
227 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
229 if (RoundParts > 2) {
230 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
232 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
233 RoundParts / 2, PartVT, HalfVT, V);
235 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
236 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
239 if (DAG.getDataLayout().isBigEndian())
242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
244 if (RoundParts < NumParts) {
245 // Assemble the trailing non-power-of-2 part.
246 unsigned OddParts = NumParts - RoundParts;
247 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
248 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
251 // Combine the round and odd parts.
253 if (DAG.getDataLayout().isBigEndian())
255 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
256 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
258 DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
259 DAG.getConstant(Lo.getValueSizeInBits(), DL,
260 TLI.getPointerTy(DAG.getDataLayout())));
261 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
262 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
264 } else if (PartVT.isFloatingPoint()) {
265 // FP split into multiple FP parts (for ppcf128)
266 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
269 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
270 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
271 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
273 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
275 // FP split into integer parts (soft fp)
276 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
277 !PartVT.isVector() && "Unexpected split");
278 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
279 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
283 // There is now one part, held in Val. Correct it to match ValueVT.
284 // PartEVT is the type of the register class that holds the value.
285 // ValueVT is the type of the inline asm operation.
286 EVT PartEVT = Val.getValueType();
288 if (PartEVT == ValueVT)
291 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
292 ValueVT.bitsLT(PartEVT)) {
293 // For an FP value in an integer part, we need to truncate to the right
295 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
296 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
299 // Handle types that have the same size.
300 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
301 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
303 // Handle types with different sizes.
304 if (PartEVT.isInteger() && ValueVT.isInteger()) {
305 if (ValueVT.bitsLT(PartEVT)) {
306 // For a truncate, see if we have any information to
307 // indicate whether the truncated bits will always be
308 // zero or sign-extension.
309 if (AssertOp.hasValue())
310 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
311 DAG.getValueType(ValueVT));
312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
314 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
317 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
318 // FP_ROUND's are always exact here.
319 if (ValueVT.bitsLT(Val.getValueType()))
321 ISD::FP_ROUND, DL, ValueVT, Val,
322 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
324 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
327 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
329 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
330 ValueVT.bitsLT(PartEVT)) {
331 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
332 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
335 report_fatal_error("Unknown mismatch in getCopyFromParts!");
338 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
339 const Twine &ErrMsg) {
340 const Instruction *I = dyn_cast_or_null<Instruction>(V);
342 return Ctx.emitError(ErrMsg);
344 const char *AsmError = ", possible invalid constraint for vector type";
345 if (const CallInst *CI = dyn_cast<CallInst>(I))
346 if (isa<InlineAsm>(CI->getCalledValue()))
347 return Ctx.emitError(I, ErrMsg + AsmError);
349 return Ctx.emitError(I, ErrMsg);
352 /// getCopyFromPartsVector - Create a value that contains the specified legal
353 /// parts combined into the value they represent. If the parts combine to a
354 /// type larger than ValueVT then AssertOp can be used to specify whether the
355 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
356 /// ValueVT (ISD::AssertSext).
357 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
358 const SDValue *Parts, unsigned NumParts,
359 MVT PartVT, EVT ValueVT, const Value *V,
360 Optional<CallingConv::ID> CallConv) {
361 assert(ValueVT.isVector() && "Not a vector value");
362 assert(NumParts > 0 && "No parts to assemble!");
363 const bool IsABIRegCopy = CallConv.hasValue();
365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
366 SDValue Val = Parts[0];
368 // Handle a multi-element vector.
372 unsigned NumIntermediates;
376 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
377 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
378 NumIntermediates, RegisterVT);
381 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
382 NumIntermediates, RegisterVT);
385 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
386 NumParts = NumRegs; // Silence a compiler warning.
387 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
388 assert(RegisterVT.getSizeInBits() ==
389 Parts[0].getSimpleValueType().getSizeInBits() &&
390 "Part type sizes don't match!");
392 // Assemble the parts into intermediate operands.
393 SmallVector<SDValue, 8> Ops(NumIntermediates);
394 if (NumIntermediates == NumParts) {
395 // If the register was not expanded, truncate or copy the value,
397 for (unsigned i = 0; i != NumParts; ++i)
398 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
399 PartVT, IntermediateVT, V);
400 } else if (NumParts > 0) {
401 // If the intermediate type was expanded, build the intermediate
402 // operands from the parts.
403 assert(NumParts % NumIntermediates == 0 &&
404 "Must expand into a divisible number of parts!");
405 unsigned Factor = NumParts / NumIntermediates;
406 for (unsigned i = 0; i != NumIntermediates; ++i)
407 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
408 PartVT, IntermediateVT, V);
411 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
412 // intermediate operands.
414 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
415 (IntermediateVT.isVector()
416 ? IntermediateVT.getVectorNumElements() * NumParts
417 : NumIntermediates));
418 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
420 DL, BuiltVectorTy, Ops);
423 // There is now one part, held in Val. Correct it to match ValueVT.
424 EVT PartEVT = Val.getValueType();
426 if (PartEVT == ValueVT)
429 if (PartEVT.isVector()) {
430 // If the element type of the source/dest vectors are the same, but the
431 // parts vector has more elements than the value vector, then we have a
432 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
434 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
435 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
436 "Cannot narrow, it would be a lossy transformation");
438 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
439 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
442 // Vector/Vector bitcast.
443 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
444 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
446 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
447 "Cannot handle this kind of promotion");
448 // Promoted vector extract
449 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
453 // Trivial bitcast if the types are the same size and the destination
454 // vector type is legal.
455 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
456 TLI.isTypeLegal(ValueVT))
457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
459 if (ValueVT.getVectorNumElements() != 1) {
460 // Certain ABIs require that vectors are passed as integers. For vectors
461 // are the same size, this is an obvious bitcast.
462 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
463 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
464 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
465 // Bitcast Val back the original type and extract the corresponding
467 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
468 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
469 ValueVT.getVectorElementType(), Elts);
470 Val = DAG.getBitcast(WiderVecType, Val);
472 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
473 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
476 diagnosePossiblyInvalidConstraint(
477 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
478 return DAG.getUNDEF(ValueVT);
481 // Handle cases such as i8 -> <1 x i1>
482 EVT ValueSVT = ValueVT.getVectorElementType();
483 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
484 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
485 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
487 return DAG.getBuildVector(ValueVT, DL, Val);
490 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
491 SDValue Val, SDValue *Parts, unsigned NumParts,
492 MVT PartVT, const Value *V,
493 Optional<CallingConv::ID> CallConv);
495 /// getCopyToParts - Create a series of nodes that contain the specified value
496 /// split into legal parts. If the parts contain more bits than Val, then, for
497 /// integers, ExtendKind can be used to specify how to generate the extra bits.
498 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
499 SDValue *Parts, unsigned NumParts, MVT PartVT,
501 Optional<CallingConv::ID> CallConv = None,
502 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
503 EVT ValueVT = Val.getValueType();
505 // Handle the vector case separately.
506 if (ValueVT.isVector())
507 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
510 unsigned PartBits = PartVT.getSizeInBits();
511 unsigned OrigNumParts = NumParts;
512 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
513 "Copying to an illegal type!");
518 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
519 EVT PartEVT = PartVT;
520 if (PartEVT == ValueVT) {
521 assert(NumParts == 1 && "No-op copy with multiple parts!");
526 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
527 // If the parts cover more bits than the value has, promote the value.
528 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
529 assert(NumParts == 1 && "Do not know what to promote to!");
530 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
532 if (ValueVT.isFloatingPoint()) {
533 // FP values need to be bitcast, then extended if they are being put
534 // into a larger container.
535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
536 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
538 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
539 ValueVT.isInteger() &&
540 "Unknown mismatch!");
541 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
542 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
543 if (PartVT == MVT::x86mmx)
544 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
546 } else if (PartBits == ValueVT.getSizeInBits()) {
547 // Different types of the same size.
548 assert(NumParts == 1 && PartEVT != ValueVT);
549 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
550 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
551 // If the parts cover less bits than value has, truncate the value.
552 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
553 ValueVT.isInteger() &&
554 "Unknown mismatch!");
555 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
556 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
557 if (PartVT == MVT::x86mmx)
558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561 // The value may have changed - recompute ValueVT.
562 ValueVT = Val.getValueType();
563 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
564 "Failed to tile the value with PartVT!");
567 if (PartEVT != ValueVT) {
568 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
569 "scalar-to-vector conversion failed");
570 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
577 // Expand the value into multiple parts.
578 if (NumParts & (NumParts - 1)) {
579 // The number of parts is not a power of 2. Split off and copy the tail.
580 assert(PartVT.isInteger() && ValueVT.isInteger() &&
581 "Do not know what to expand to!");
582 unsigned RoundParts = 1 << Log2_32(NumParts);
583 unsigned RoundBits = RoundParts * PartBits;
584 unsigned OddParts = NumParts - RoundParts;
585 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
586 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
588 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
591 if (DAG.getDataLayout().isBigEndian())
592 // The odd parts were reversed by getCopyToParts - unreverse them.
593 std::reverse(Parts + RoundParts, Parts + NumParts);
595 NumParts = RoundParts;
596 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
597 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
600 // The number of parts is a power of 2. Repeatedly bisect the value using
602 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
603 EVT::getIntegerVT(*DAG.getContext(),
604 ValueVT.getSizeInBits()),
607 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
608 for (unsigned i = 0; i < NumParts; i += StepSize) {
609 unsigned ThisBits = StepSize * PartBits / 2;
610 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
611 SDValue &Part0 = Parts[i];
612 SDValue &Part1 = Parts[i+StepSize/2];
614 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
615 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
616 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
617 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
619 if (ThisBits == PartBits && ThisVT != PartVT) {
620 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
621 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
626 if (DAG.getDataLayout().isBigEndian())
627 std::reverse(Parts, Parts + OrigNumParts);
630 static SDValue widenVectorToPartType(SelectionDAG &DAG,
631 SDValue Val, const SDLoc &DL, EVT PartVT) {
632 if (!PartVT.isVector())
635 EVT ValueVT = Val.getValueType();
636 unsigned PartNumElts = PartVT.getVectorNumElements();
637 unsigned ValueNumElts = ValueVT.getVectorNumElements();
638 if (PartNumElts > ValueNumElts &&
639 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
640 EVT ElementVT = PartVT.getVectorElementType();
641 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
643 SmallVector<SDValue, 16> Ops;
644 DAG.ExtractVectorElements(Val, Ops);
645 SDValue EltUndef = DAG.getUNDEF(ElementVT);
646 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
647 Ops.push_back(EltUndef);
649 // FIXME: Use CONCAT for 2x -> 4x.
650 return DAG.getBuildVector(PartVT, DL, Ops);
656 /// getCopyToPartsVector - Create a series of nodes that contain the specified
657 /// value split into legal parts.
658 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
659 SDValue Val, SDValue *Parts, unsigned NumParts,
660 MVT PartVT, const Value *V,
661 Optional<CallingConv::ID> CallConv) {
662 EVT ValueVT = Val.getValueType();
663 assert(ValueVT.isVector() && "Not a vector");
664 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
665 const bool IsABIRegCopy = CallConv.hasValue();
668 EVT PartEVT = PartVT;
669 if (PartEVT == ValueVT) {
671 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
672 // Bitconvert vector->vector case.
673 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
674 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
676 } else if (PartVT.isVector() &&
677 PartEVT.getVectorElementType().bitsGE(
678 ValueVT.getVectorElementType()) &&
679 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
681 // Promoted vector extract
682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
684 if (ValueVT.getVectorNumElements() == 1) {
686 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
687 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
689 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
690 "lossy conversion of vector to scalar type");
691 EVT IntermediateType =
692 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
693 Val = DAG.getBitcast(IntermediateType, Val);
694 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
698 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
703 // Handle a multi-element vector.
706 unsigned NumIntermediates;
709 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
710 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
711 NumIntermediates, RegisterVT);
714 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
715 NumIntermediates, RegisterVT);
718 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
719 NumParts = NumRegs; // Silence a compiler warning.
720 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
722 unsigned IntermediateNumElts = IntermediateVT.isVector() ?
723 IntermediateVT.getVectorNumElements() : 1;
725 // Convert the vector to the appropiate type if necessary.
726 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
728 EVT BuiltVectorTy = EVT::getVectorVT(
729 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
730 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
731 if (ValueVT != BuiltVectorTy) {
732 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
735 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
738 // Split the vector into intermediate operands.
739 SmallVector<SDValue, 8> Ops(NumIntermediates);
740 for (unsigned i = 0; i != NumIntermediates; ++i) {
741 if (IntermediateVT.isVector()) {
742 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
743 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
745 Ops[i] = DAG.getNode(
746 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
747 DAG.getConstant(i, DL, IdxVT));
751 // Split the intermediate operands into legal parts.
752 if (NumParts == NumIntermediates) {
753 // If the register was not expanded, promote or copy the value,
755 for (unsigned i = 0; i != NumParts; ++i)
756 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
757 } else if (NumParts > 0) {
758 // If the intermediate type was expanded, split each the value into
760 assert(NumIntermediates != 0 && "division by zero");
761 assert(NumParts % NumIntermediates == 0 &&
762 "Must expand into a divisible number of parts!");
763 unsigned Factor = NumParts / NumIntermediates;
764 for (unsigned i = 0; i != NumIntermediates; ++i)
765 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
770 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt,
771 EVT valuevt, Optional<CallingConv::ID> CC)
772 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
773 RegCount(1, regs.size()), CallConv(CC) {}
775 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
776 const DataLayout &DL, unsigned Reg, Type *Ty,
777 Optional<CallingConv::ID> CC) {
778 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
782 for (EVT ValueVT : ValueVTs) {
785 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
786 : TLI.getNumRegisters(Context, ValueVT);
789 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
790 : TLI.getRegisterType(Context, ValueVT);
791 for (unsigned i = 0; i != NumRegs; ++i)
792 Regs.push_back(Reg + i);
793 RegVTs.push_back(RegisterVT);
794 RegCount.push_back(NumRegs);
799 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
800 FunctionLoweringInfo &FuncInfo,
801 const SDLoc &dl, SDValue &Chain,
802 SDValue *Flag, const Value *V) const {
803 // A Value with type {} or [0 x %t] needs no registers.
804 if (ValueVTs.empty())
807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
809 // Assemble the legal parts into the final values.
810 SmallVector<SDValue, 4> Values(ValueVTs.size());
811 SmallVector<SDValue, 8> Parts;
812 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
813 // Copy the legal parts from the registers.
814 EVT ValueVT = ValueVTs[Value];
815 unsigned NumRegs = RegCount[Value];
816 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
818 CallConv.getValue(), RegVTs[Value])
821 Parts.resize(NumRegs);
822 for (unsigned i = 0; i != NumRegs; ++i) {
825 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
827 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
828 *Flag = P.getValue(2);
831 Chain = P.getValue(1);
834 // If the source register was virtual and if we know something about it,
835 // add an assert node.
836 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
837 !RegisterVT.isInteger())
840 const FunctionLoweringInfo::LiveOutInfo *LOI =
841 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
845 unsigned RegSize = RegisterVT.getScalarSizeInBits();
846 unsigned NumSignBits = LOI->NumSignBits;
847 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
849 if (NumZeroBits == RegSize) {
850 // The current value is a zero.
851 // Explicitly express that as it would be easier for
852 // optimizations to kick in.
853 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
857 // FIXME: We capture more information than the dag can represent. For
858 // now, just use the tightest assertzext/assertsext possible.
860 EVT FromVT(MVT::Other);
862 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
864 } else if (NumSignBits > 1) {
866 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
871 // Add an assertion node.
872 assert(FromVT != MVT::Other);
873 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
874 RegisterVT, P, DAG.getValueType(FromVT));
877 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
878 RegisterVT, ValueVT, V, CallConv);
883 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
886 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
887 const SDLoc &dl, SDValue &Chain, SDValue *Flag,
889 ISD::NodeType PreferredExtendType) const {
890 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
891 ISD::NodeType ExtendKind = PreferredExtendType;
893 // Get the list of the values's legal parts.
894 unsigned NumRegs = Regs.size();
895 SmallVector<SDValue, 8> Parts(NumRegs);
896 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
897 unsigned NumParts = RegCount[Value];
899 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
901 CallConv.getValue(), RegVTs[Value])
904 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
905 ExtendKind = ISD::ZERO_EXTEND;
907 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
908 NumParts, RegisterVT, V, CallConv, ExtendKind);
912 // Copy the parts into the registers.
913 SmallVector<SDValue, 8> Chains(NumRegs);
914 for (unsigned i = 0; i != NumRegs; ++i) {
917 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
919 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
920 *Flag = Part.getValue(1);
923 Chains[i] = Part.getValue(0);
926 if (NumRegs == 1 || Flag)
927 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
928 // flagged to it. That is the CopyToReg nodes and the user are considered
929 // a single scheduling unit. If we create a TokenFactor and return it as
930 // chain, then the TokenFactor is both a predecessor (operand) of the
931 // user as well as a successor (the TF operands are flagged to the user).
932 // c1, f1 = CopyToReg
933 // c2, f2 = CopyToReg
934 // c3 = TokenFactor c1, c2
937 Chain = Chains[NumRegs-1];
939 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
942 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
943 unsigned MatchingIdx, const SDLoc &dl,
945 std::vector<SDValue> &Ops) const {
946 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
948 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
950 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
951 else if (!Regs.empty() &&
952 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
953 // Put the register class of the virtual registers in the flag word. That
954 // way, later passes can recompute register class constraints for inline
955 // assembly as well as normal instructions.
956 // Don't do this for tied operands that can use the regclass information
958 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
959 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
960 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
963 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
966 if (Code == InlineAsm::Kind_Clobber) {
967 // Clobbers should always have a 1:1 mapping with registers, and may
968 // reference registers that have illegal (e.g. vector) types. Hence, we
969 // shouldn't try to apply any sort of splitting logic to them.
970 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
971 "No 1:1 mapping from clobbers to regs?");
972 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
974 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
975 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
978 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
979 "If we clobbered the stack pointer, MFI should know about it.");
984 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
985 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
986 MVT RegisterVT = RegVTs[Value];
987 for (unsigned i = 0; i != NumRegs; ++i) {
988 assert(Reg < Regs.size() && "Mismatch in # registers expected");
989 unsigned TheReg = Regs[Reg++];
990 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
995 SmallVector<std::pair<unsigned, unsigned>, 4>
996 RegsForValue::getRegsAndSizes() const {
997 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
999 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1000 unsigned RegCount = std::get<0>(CountAndVT);
1001 MVT RegisterVT = std::get<1>(CountAndVT);
1002 unsigned RegisterSize = RegisterVT.getSizeInBits();
1003 for (unsigned E = I + RegCount; I != E; ++I)
1004 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1009 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1010 const TargetLibraryInfo *li) {
1014 DL = &DAG.getDataLayout();
1015 Context = DAG.getContext();
1016 LPadToCallSiteMap.clear();
1017 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1020 void SelectionDAGBuilder::clear() {
1022 UnusedArgNodeMap.clear();
1023 PendingLoads.clear();
1024 PendingExports.clear();
1026 HasTailCall = false;
1027 SDNodeOrder = LowestSDNodeOrder;
1028 StatepointLowering.clear();
1031 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1032 DanglingDebugInfoMap.clear();
1035 SDValue SelectionDAGBuilder::getRoot() {
1036 if (PendingLoads.empty())
1037 return DAG.getRoot();
1039 if (PendingLoads.size() == 1) {
1040 SDValue Root = PendingLoads[0];
1042 PendingLoads.clear();
1046 // Otherwise, we have to make a token factor node.
1047 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1048 PendingLoads.clear();
1053 SDValue SelectionDAGBuilder::getControlRoot() {
1054 SDValue Root = DAG.getRoot();
1056 if (PendingExports.empty())
1059 // Turn all of the CopyToReg chains into one factored node.
1060 if (Root.getOpcode() != ISD::EntryToken) {
1061 unsigned i = 0, e = PendingExports.size();
1062 for (; i != e; ++i) {
1063 assert(PendingExports[i].getNode()->getNumOperands() > 1);
1064 if (PendingExports[i].getNode()->getOperand(0) == Root)
1065 break; // Don't add the root if we already indirectly depend on it.
1069 PendingExports.push_back(Root);
1072 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1074 PendingExports.clear();
1079 void SelectionDAGBuilder::visit(const Instruction &I) {
1080 // Set up outgoing PHI node register values before emitting the terminator.
1081 if (I.isTerminator()) {
1082 HandlePHINodesInSuccessorBlocks(I.getParent());
1085 // Increase the SDNodeOrder if dealing with a non-debug instruction.
1086 if (!isa<DbgInfoIntrinsic>(I))
1091 visit(I.getOpcode(), I);
1093 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1094 // Propagate the fast-math-flags of this IR instruction to the DAG node that
1095 // maps to this instruction.
1096 // TODO: We could handle all flags (nsw, etc) here.
1097 // TODO: If an IR instruction maps to >1 node, only the final node will have
1099 if (SDNode *Node = getNodeForIRValue(&I)) {
1100 SDNodeFlags IncomingFlags;
1101 IncomingFlags.copyFMF(*FPMO);
1102 if (!Node->getFlags().isDefined())
1103 Node->setFlags(IncomingFlags);
1105 Node->intersectFlagsWith(IncomingFlags);
1109 if (!I.isTerminator() && !HasTailCall &&
1110 !isStatepoint(&I)) // statepoints handle their exports internally
1111 CopyToExportRegsIfNeeded(&I);
1116 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1117 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1120 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1121 // Note: this doesn't use InstVisitor, because it has to work with
1122 // ConstantExpr's in addition to instructions.
1124 default: llvm_unreachable("Unknown instruction type encountered!");
1125 // Build the switch statement using the Instruction.def file.
1126 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1127 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1128 #include "llvm/IR/Instruction.def"
1132 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1133 const DIExpression *Expr) {
1134 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1135 const DbgValueInst *DI = DDI.getDI();
1136 DIVariable *DanglingVariable = DI->getVariable();
1137 DIExpression *DanglingExpr = DI->getExpression();
1138 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1139 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1145 for (auto &DDIMI : DanglingDebugInfoMap) {
1146 DanglingDebugInfoVector &DDIV = DDIMI.second;
1148 // If debug info is to be dropped, run it through final checks to see
1149 // whether it can be salvaged.
1150 for (auto &DDI : DDIV)
1151 if (isMatchingDbgValue(DDI))
1152 salvageUnresolvedDbgValue(DDI);
1154 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1158 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1159 // generate the debug data structures now that we've seen its definition.
1160 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1162 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1163 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1166 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1167 for (auto &DDI : DDIV) {
1168 const DbgValueInst *DI = DDI.getDI();
1169 assert(DI && "Ill-formed DanglingDebugInfo");
1170 DebugLoc dl = DDI.getdl();
1171 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1172 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1173 DILocalVariable *Variable = DI->getVariable();
1174 DIExpression *Expr = DI->getExpression();
1175 assert(Variable->isValidLocationForIntrinsic(dl) &&
1176 "Expected inlined-at fields to agree");
1178 if (Val.getNode()) {
1179 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1180 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1181 // we couldn't resolve it directly when examining the DbgValue intrinsic
1182 // in the first place we should not be more successful here). Unless we
1183 // have some test case that prove this to be correct we should avoid
1184 // calling EmitFuncArgumentDbgValue here.
1185 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1186 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1187 << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
1188 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1189 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1190 // inserted after the definition of Val when emitting the instructions
1191 // after ISel. An alternative could be to teach
1192 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1193 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1194 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1195 << ValSDNodeOrder << "\n");
1196 SDV = getDbgValue(Val, Variable, Expr, dl,
1197 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1198 DAG.AddDbgValue(SDV, Val.getNode(), false);
1200 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1201 << "in EmitFuncArgumentDbgValue\n");
1203 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1205 UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1207 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1208 DAG.AddDbgValue(SDV, nullptr, false);
1214 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1215 Value *V = DDI.getDI()->getValue();
1216 DILocalVariable *Var = DDI.getDI()->getVariable();
1217 DIExpression *Expr = DDI.getDI()->getExpression();
1218 DebugLoc DL = DDI.getdl();
1219 DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1220 unsigned SDOrder = DDI.getSDNodeOrder();
1222 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1223 // that DW_OP_stack_value is desired.
1224 assert(isa<DbgValueInst>(DDI.getDI()));
1225 bool StackValue = true;
1227 // Can this Value can be encoded without any further work?
1228 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1231 // Attempt to salvage back through as many instructions as possible. Bail if
1232 // a non-instruction is seen, such as a constant expression or global
1233 // variable. FIXME: Further work could recover those too.
1234 while (isa<Instruction>(V)) {
1235 Instruction &VAsInst = *cast<Instruction>(V);
1236 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1238 // If we cannot salvage any further, and haven't yet found a suitable debug
1239 // expression, bail out.
1243 // New value and expr now represent this debuginfo.
1244 V = VAsInst.getOperand(0);
1247 // Some kind of simplification occurred: check whether the operand of the
1248 // salvaged debug expression can be encoded in this DAG.
1249 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1250 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
1251 << DDI.getDI() << "\nBy stripping back to:\n " << V);
1256 // This was the final opportunity to salvage this debug information, and it
1257 // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1258 // any earlier variable location.
1259 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1260 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1261 DAG.AddDbgValue(SDV, nullptr, false);
1263 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
1265 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
1269 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1270 DIExpression *Expr, DebugLoc dl,
1271 DebugLoc InstDL, unsigned Order) {
1272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1274 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1275 isa<ConstantPointerNull>(V)) {
1276 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1277 DAG.AddDbgValue(SDV, nullptr, false);
1281 // If the Value is a frame index, we can create a FrameIndex debug value
1282 // without relying on the DAG at all.
1283 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1284 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1285 if (SI != FuncInfo.StaticAllocaMap.end()) {
1287 DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1288 /*IsIndirect*/ false, dl, SDNodeOrder);
1289 // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1290 // is still available even if the SDNode gets optimized out.
1291 DAG.AddDbgValue(SDV, nullptr, false);
1296 // Do not use getValue() in here; we don't want to generate code at
1297 // this point if it hasn't been done yet.
1298 SDValue N = NodeMap[V];
1299 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1300 N = UnusedArgNodeMap[V];
1302 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1304 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1305 DAG.AddDbgValue(SDV, N.getNode(), false);
1309 // Special rules apply for the first dbg.values of parameter variables in a
1310 // function. Identify them by the fact they reference Argument Values, that
1311 // they're parameters, and they are parameters of the current function. We
1312 // need to let them dangle until they get an SDNode.
1313 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1314 !InstDL.getInlinedAt();
1315 if (!IsParamOfFunc) {
1316 // The value is not used in this block yet (or it would have an SDNode).
1317 // We still want the value to appear for the user if possible -- if it has
1318 // an associated VReg, we can refer to that instead.
1319 auto VMI = FuncInfo.ValueMap.find(V);
1320 if (VMI != FuncInfo.ValueMap.end()) {
1321 unsigned Reg = VMI->second;
1322 // If this is a PHI node, it may be split up into several MI PHI nodes
1323 // (in FunctionLoweringInfo::set).
1324 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1325 V->getType(), None);
1326 if (RFV.occupiesMultipleRegs()) {
1327 unsigned Offset = 0;
1328 unsigned BitsToDescribe = 0;
1329 if (auto VarSize = Var->getSizeInBits())
1330 BitsToDescribe = *VarSize;
1331 if (auto Fragment = Expr->getFragmentInfo())
1332 BitsToDescribe = Fragment->SizeInBits;
1333 for (auto RegAndSize : RFV.getRegsAndSizes()) {
1334 unsigned RegisterSize = RegAndSize.second;
1335 // Bail out if all bits are described already.
1336 if (Offset >= BitsToDescribe)
1338 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1339 ? BitsToDescribe - Offset
1341 auto FragmentExpr = DIExpression::createFragmentExpression(
1342 Expr, Offset, FragmentSize);
1345 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1346 false, dl, SDNodeOrder);
1347 DAG.AddDbgValue(SDV, nullptr, false);
1348 Offset += RegisterSize;
1351 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1352 DAG.AddDbgValue(SDV, nullptr, false);
1361 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1362 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1363 for (auto &Pair : DanglingDebugInfoMap)
1364 for (auto &DDI : Pair.second)
1365 salvageUnresolvedDbgValue(DDI);
1366 clearDanglingDebugInfo();
1369 /// getCopyFromRegs - If there was virtual register allocated for the value V
1370 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1371 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1372 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1375 if (It != FuncInfo.ValueMap.end()) {
1376 unsigned InReg = It->second;
1378 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1379 DAG.getDataLayout(), InReg, Ty,
1380 None); // This is not an ABI copy.
1381 SDValue Chain = DAG.getEntryNode();
1382 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1384 resolveDanglingDebugInfo(V, Result);
1390 /// getValue - Return an SDValue for the given Value.
1391 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1392 // If we already have an SDValue for this value, use it. It's important
1393 // to do this first, so that we don't create a CopyFromReg if we already
1394 // have a regular SDValue.
1395 SDValue &N = NodeMap[V];
1396 if (N.getNode()) return N;
1398 // If there's a virtual register allocated and initialized for this
1400 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1403 // Otherwise create a new SDValue and remember it.
1404 SDValue Val = getValueImpl(V);
1406 resolveDanglingDebugInfo(V, Val);
1410 // Return true if SDValue exists for the given Value
1411 bool SelectionDAGBuilder::findValue(const Value *V) const {
1412 return (NodeMap.find(V) != NodeMap.end()) ||
1413 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1416 /// getNonRegisterValue - Return an SDValue for the given Value, but
1417 /// don't look in FuncInfo.ValueMap for a virtual register.
1418 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1419 // If we already have an SDValue for this value, use it.
1420 SDValue &N = NodeMap[V];
1422 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1423 // Remove the debug location from the node as the node is about to be used
1424 // in a location which may differ from the original debug location. This
1425 // is relevant to Constant and ConstantFP nodes because they can appear
1426 // as constant expressions inside PHI nodes.
1427 N->setDebugLoc(DebugLoc());
1432 // Otherwise create a new SDValue and remember it.
1433 SDValue Val = getValueImpl(V);
1435 resolveDanglingDebugInfo(V, Val);
1439 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1440 /// Create an SDValue for the given value.
1441 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1442 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1444 if (const Constant *C = dyn_cast<Constant>(V)) {
1445 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1447 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1448 return DAG.getConstant(*CI, getCurSDLoc(), VT);
1450 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1451 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1453 if (isa<ConstantPointerNull>(C)) {
1454 unsigned AS = V->getType()->getPointerAddressSpace();
1455 return DAG.getConstant(0, getCurSDLoc(),
1456 TLI.getPointerTy(DAG.getDataLayout(), AS));
1459 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1460 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1462 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1463 return DAG.getUNDEF(VT);
1465 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1466 visit(CE->getOpcode(), *CE);
1467 SDValue N1 = NodeMap[V];
1468 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1472 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1473 SmallVector<SDValue, 4> Constants;
1474 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1476 SDNode *Val = getValue(*OI).getNode();
1477 // If the operand is an empty aggregate, there are no values.
1479 // Add each leaf value from the operand to the Constants list
1480 // to form a flattened list of all the values.
1481 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1482 Constants.push_back(SDValue(Val, i));
1485 return DAG.getMergeValues(Constants, getCurSDLoc());
1488 if (const ConstantDataSequential *CDS =
1489 dyn_cast<ConstantDataSequential>(C)) {
1490 SmallVector<SDValue, 4> Ops;
1491 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1492 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1493 // Add each leaf value from the operand to the Constants list
1494 // to form a flattened list of all the values.
1495 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1496 Ops.push_back(SDValue(Val, i));
1499 if (isa<ArrayType>(CDS->getType()))
1500 return DAG.getMergeValues(Ops, getCurSDLoc());
1501 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1504 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1505 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1506 "Unknown struct or array constant!");
1508 SmallVector<EVT, 4> ValueVTs;
1509 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1510 unsigned NumElts = ValueVTs.size();
1512 return SDValue(); // empty struct
1513 SmallVector<SDValue, 4> Constants(NumElts);
1514 for (unsigned i = 0; i != NumElts; ++i) {
1515 EVT EltVT = ValueVTs[i];
1516 if (isa<UndefValue>(C))
1517 Constants[i] = DAG.getUNDEF(EltVT);
1518 else if (EltVT.isFloatingPoint())
1519 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1521 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1524 return DAG.getMergeValues(Constants, getCurSDLoc());
1527 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1528 return DAG.getBlockAddress(BA, VT);
1530 VectorType *VecTy = cast<VectorType>(V->getType());
1531 unsigned NumElements = VecTy->getNumElements();
1533 // Now that we know the number and type of the elements, get that number of
1534 // elements into the Ops array based on what kind of constant it is.
1535 SmallVector<SDValue, 16> Ops;
1536 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1537 for (unsigned i = 0; i != NumElements; ++i)
1538 Ops.push_back(getValue(CV->getOperand(i)));
1540 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1542 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1545 if (EltVT.isFloatingPoint())
1546 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1548 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1549 Ops.assign(NumElements, Op);
1552 // Create a BUILD_VECTOR node.
1553 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1556 // If this is a static alloca, generate it as the frameindex instead of
1558 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1559 DenseMap<const AllocaInst*, int>::iterator SI =
1560 FuncInfo.StaticAllocaMap.find(AI);
1561 if (SI != FuncInfo.StaticAllocaMap.end())
1562 return DAG.getFrameIndex(SI->second,
1563 TLI.getFrameIndexTy(DAG.getDataLayout()));
1566 // If this is an instruction which fast-isel has deferred, select it now.
1567 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1568 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1570 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1571 Inst->getType(), getABIRegCopyCC(V));
1572 SDValue Chain = DAG.getEntryNode();
1573 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1576 llvm_unreachable("Can't get register for value!");
1579 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1580 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1581 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1582 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1583 bool IsSEH = isAsynchronousEHPersonality(Pers);
1584 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1585 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1587 CatchPadMBB->setIsEHScopeEntry();
1588 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1589 if (IsMSVCCXX || IsCoreCLR)
1590 CatchPadMBB->setIsEHFuncletEntry();
1591 // Wasm does not need catchpads anymore
1593 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1597 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1598 // Update machine-CFG edge.
1599 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1600 FuncInfo.MBB->addSuccessor(TargetMBB);
1602 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1603 bool IsSEH = isAsynchronousEHPersonality(Pers);
1605 // If this is not a fall-through branch or optimizations are switched off,
1607 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1608 TM.getOptLevel() == CodeGenOpt::None)
1609 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1610 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1614 // Figure out the funclet membership for the catchret's successor.
1615 // This will be used by the FuncletLayout pass to determine how to order the
1617 // A 'catchret' returns to the outer scope's color.
1618 Value *ParentPad = I.getCatchSwitchParentPad();
1619 const BasicBlock *SuccessorColor;
1620 if (isa<ConstantTokenNone>(ParentPad))
1621 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1623 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1624 assert(SuccessorColor && "No parent funclet for catchret!");
1625 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1626 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1628 // Create the terminator node.
1629 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1630 getControlRoot(), DAG.getBasicBlock(TargetMBB),
1631 DAG.getBasicBlock(SuccessorColorMBB));
1635 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1636 // Don't emit any special code for the cleanuppad instruction. It just marks
1637 // the start of an EH scope/funclet.
1638 FuncInfo.MBB->setIsEHScopeEntry();
1639 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1640 if (Pers != EHPersonality::Wasm_CXX) {
1641 FuncInfo.MBB->setIsEHFuncletEntry();
1642 FuncInfo.MBB->setIsCleanupFuncletEntry();
1646 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1647 // the control flow always stops at the single catch pad, as it does for a
1648 // cleanup pad. In case the exception caught is not of the types the catch pad
1649 // catches, it will be rethrown by a rethrow.
1650 static void findWasmUnwindDestinations(
1651 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1652 BranchProbability Prob,
1653 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1656 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1657 if (isa<CleanupPadInst>(Pad)) {
1658 // Stop on cleanup pads.
1659 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1660 UnwindDests.back().first->setIsEHScopeEntry();
1662 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1663 // Add the catchpad handlers to the possible destinations. We don't
1664 // continue to the unwind destination of the catchswitch for wasm.
1665 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1666 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1667 UnwindDests.back().first->setIsEHScopeEntry();
1676 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1677 /// many places it could ultimately go. In the IR, we have a single unwind
1678 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1679 /// This function skips over imaginary basic blocks that hold catchswitch
1680 /// instructions, and finds all the "real" machine
1681 /// basic block destinations. As those destinations may not be successors of
1682 /// EHPadBB, here we also calculate the edge probability to those destinations.
1683 /// The passed-in Prob is the edge probability to EHPadBB.
1684 static void findUnwindDestinations(
1685 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1686 BranchProbability Prob,
1687 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1689 EHPersonality Personality =
1690 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1691 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1692 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1693 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1694 bool IsSEH = isAsynchronousEHPersonality(Personality);
1697 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1698 assert(UnwindDests.size() <= 1 &&
1699 "There should be at most one unwind destination for wasm");
1704 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1705 BasicBlock *NewEHPadBB = nullptr;
1706 if (isa<LandingPadInst>(Pad)) {
1707 // Stop on landingpads. They are not funclets.
1708 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1710 } else if (isa<CleanupPadInst>(Pad)) {
1711 // Stop on cleanup pads. Cleanups are always funclet entries for all known
1713 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1714 UnwindDests.back().first->setIsEHScopeEntry();
1715 UnwindDests.back().first->setIsEHFuncletEntry();
1717 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1718 // Add the catchpad handlers to the possible destinations.
1719 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1720 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1721 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1722 if (IsMSVCCXX || IsCoreCLR)
1723 UnwindDests.back().first->setIsEHFuncletEntry();
1725 UnwindDests.back().first->setIsEHScopeEntry();
1727 NewEHPadBB = CatchSwitch->getUnwindDest();
1732 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1733 if (BPI && NewEHPadBB)
1734 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1735 EHPadBB = NewEHPadBB;
1739 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1740 // Update successor info.
1741 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1742 auto UnwindDest = I.getUnwindDest();
1743 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1744 BranchProbability UnwindDestProb =
1746 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1747 : BranchProbability::getZero();
1748 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1749 for (auto &UnwindDest : UnwindDests) {
1750 UnwindDest.first->setIsEHPad();
1751 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1753 FuncInfo.MBB->normalizeSuccProbs();
1755 // Create the terminator node.
1757 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1761 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1762 report_fatal_error("visitCatchSwitch not yet implemented!");
1765 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1766 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1767 auto &DL = DAG.getDataLayout();
1768 SDValue Chain = getControlRoot();
1769 SmallVector<ISD::OutputArg, 8> Outs;
1770 SmallVector<SDValue, 8> OutVals;
1772 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1775 // %val = call <ty> @llvm.experimental.deoptimize()
1779 if (I.getParent()->getTerminatingDeoptimizeCall()) {
1780 LowerDeoptimizingReturn();
1784 if (!FuncInfo.CanLowerReturn) {
1785 unsigned DemoteReg = FuncInfo.DemoteRegister;
1786 const Function *F = I.getParent()->getParent();
1788 // Emit a store of the return value through the virtual register.
1789 // Leave Outs empty so that LowerReturn won't try to load return
1790 // registers the usual way.
1791 SmallVector<EVT, 1> PtrValueVTs;
1792 ComputeValueVTs(TLI, DL,
1793 F->getReturnType()->getPointerTo(
1794 DAG.getDataLayout().getAllocaAddrSpace()),
1797 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1798 DemoteReg, PtrValueVTs[0]);
1799 SDValue RetOp = getValue(I.getOperand(0));
1801 SmallVector<EVT, 4> ValueVTs, MemVTs;
1802 SmallVector<uint64_t, 4> Offsets;
1803 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1805 unsigned NumValues = ValueVTs.size();
1807 SmallVector<SDValue, 4> Chains(NumValues);
1808 for (unsigned i = 0; i != NumValues; ++i) {
1809 // An aggregate return value cannot wrap around the address space, so
1810 // offsets to its parts don't wrap either.
1811 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1813 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1814 if (MemVTs[i] != ValueVTs[i])
1815 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1816 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1817 // FIXME: better loc info would be nice.
1818 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1821 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1822 MVT::Other, Chains);
1823 } else if (I.getNumOperands() != 0) {
1824 SmallVector<EVT, 4> ValueVTs;
1825 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1826 unsigned NumValues = ValueVTs.size();
1828 SDValue RetOp = getValue(I.getOperand(0));
1830 const Function *F = I.getParent()->getParent();
1832 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1833 I.getOperand(0)->getType(), F->getCallingConv(),
1834 /*IsVarArg*/ false);
1836 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1837 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1839 ExtendKind = ISD::SIGN_EXTEND;
1840 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1842 ExtendKind = ISD::ZERO_EXTEND;
1844 LLVMContext &Context = F->getContext();
1845 bool RetInReg = F->getAttributes().hasAttribute(
1846 AttributeList::ReturnIndex, Attribute::InReg);
1848 for (unsigned j = 0; j != NumValues; ++j) {
1849 EVT VT = ValueVTs[j];
1851 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1852 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1854 CallingConv::ID CC = F->getCallingConv();
1856 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1857 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1858 SmallVector<SDValue, 4> Parts(NumParts);
1859 getCopyToParts(DAG, getCurSDLoc(),
1860 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1861 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1863 // 'inreg' on function refers to return value
1864 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1868 if (I.getOperand(0)->getType()->isPointerTy()) {
1870 Flags.setPointerAddrSpace(
1871 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1874 if (NeedsRegBlock) {
1875 Flags.setInConsecutiveRegs();
1876 if (j == NumValues - 1)
1877 Flags.setInConsecutiveRegsLast();
1880 // Propagate extension type if any
1881 if (ExtendKind == ISD::SIGN_EXTEND)
1883 else if (ExtendKind == ISD::ZERO_EXTEND)
1886 for (unsigned i = 0; i < NumParts; ++i) {
1887 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1888 VT, /*isfixed=*/true, 0, 0));
1889 OutVals.push_back(Parts[i]);
1895 // Push in swifterror virtual register as the last element of Outs. This makes
1896 // sure swifterror virtual register will be returned in the swifterror
1897 // physical register.
1898 const Function *F = I.getParent()->getParent();
1899 if (TLI.supportSwiftError() &&
1900 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1901 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1902 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1903 Flags.setSwiftError();
1904 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1905 EVT(TLI.getPointerTy(DL)) /*argvt*/,
1906 true /*isfixed*/, 1 /*origidx*/,
1908 // Create SDNode for the swifterror virtual register.
1910 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1911 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1912 EVT(TLI.getPointerTy(DL))));
1915 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1916 CallingConv::ID CallConv =
1917 DAG.getMachineFunction().getFunction().getCallingConv();
1918 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1919 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1921 // Verify that the target's LowerReturn behaved as expected.
1922 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1923 "LowerReturn didn't return a valid chain!");
1925 // Update the DAG with the new chain value resulting from return lowering.
1929 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1930 /// created for it, emit nodes to copy the value into the virtual
1932 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1934 if (V->getType()->isEmptyTy())
1937 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1938 if (VMI != FuncInfo.ValueMap.end()) {
1939 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1940 CopyValueToVirtualRegister(V, VMI->second);
1944 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1945 /// the current basic block, add it to ValueMap now so that we'll get a
1947 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1948 // No need to export constants.
1949 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1951 // Already exported?
1952 if (FuncInfo.isExportedInst(V)) return;
1954 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1955 CopyValueToVirtualRegister(V, Reg);
1958 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1959 const BasicBlock *FromBB) {
1960 // The operands of the setcc have to be in this block. We don't know
1961 // how to export them from some other block.
1962 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1963 // Can export from current BB.
1964 if (VI->getParent() == FromBB)
1967 // Is already exported, noop.
1968 return FuncInfo.isExportedInst(V);
1971 // If this is an argument, we can export it if the BB is the entry block or
1972 // if it is already exported.
1973 if (isa<Argument>(V)) {
1974 if (FromBB == &FromBB->getParent()->getEntryBlock())
1977 // Otherwise, can only export this if it is already exported.
1978 return FuncInfo.isExportedInst(V);
1981 // Otherwise, constants can always be exported.
1985 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1987 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1988 const MachineBasicBlock *Dst) const {
1989 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1990 const BasicBlock *SrcBB = Src->getBasicBlock();
1991 const BasicBlock *DstBB = Dst->getBasicBlock();
1993 // If BPI is not available, set the default probability as 1 / N, where N is
1994 // the number of successors.
1995 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1996 return BranchProbability(1, SuccSize);
1998 return BPI->getEdgeProbability(SrcBB, DstBB);
2001 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2002 MachineBasicBlock *Dst,
2003 BranchProbability Prob) {
2005 Src->addSuccessorWithoutProb(Dst);
2007 if (Prob.isUnknown())
2008 Prob = getEdgeProbability(Src, Dst);
2009 Src->addSuccessor(Dst, Prob);
2013 static bool InBlock(const Value *V, const BasicBlock *BB) {
2014 if (const Instruction *I = dyn_cast<Instruction>(V))
2015 return I->getParent() == BB;
2019 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2020 /// This function emits a branch and is used at the leaves of an OR or an
2021 /// AND operator tree.
2023 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2024 MachineBasicBlock *TBB,
2025 MachineBasicBlock *FBB,
2026 MachineBasicBlock *CurBB,
2027 MachineBasicBlock *SwitchBB,
2028 BranchProbability TProb,
2029 BranchProbability FProb,
2031 const BasicBlock *BB = CurBB->getBasicBlock();
2033 // If the leaf of the tree is a comparison, merge the condition into
2035 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2036 // The operands of the cmp have to be in this block. We don't know
2037 // how to export them from some other block. If this is the first block
2038 // of the sequence, no exporting is needed.
2039 if (CurBB == SwitchBB ||
2040 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2041 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2042 ISD::CondCode Condition;
2043 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2044 ICmpInst::Predicate Pred =
2045 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2046 Condition = getICmpCondCode(Pred);
2048 const FCmpInst *FC = cast<FCmpInst>(Cond);
2049 FCmpInst::Predicate Pred =
2050 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2051 Condition = getFCmpCondCode(Pred);
2052 if (TM.Options.NoNaNsFPMath)
2053 Condition = getFCmpCodeWithoutNaN(Condition);
2056 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2057 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2058 SL->SwitchCases.push_back(CB);
2063 // Create a CaseBlock record representing this branch.
2064 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2065 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2066 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2067 SL->SwitchCases.push_back(CB);
2070 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2071 MachineBasicBlock *TBB,
2072 MachineBasicBlock *FBB,
2073 MachineBasicBlock *CurBB,
2074 MachineBasicBlock *SwitchBB,
2075 Instruction::BinaryOps Opc,
2076 BranchProbability TProb,
2077 BranchProbability FProb,
2079 // Skip over not part of the tree and remember to invert op and operands at
2082 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2083 InBlock(NotCond, CurBB->getBasicBlock())) {
2084 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2089 const Instruction *BOp = dyn_cast<Instruction>(Cond);
2090 // Compute the effective opcode for Cond, taking into account whether it needs
2091 // to be inverted, e.g.
2092 // and (not (or A, B)), C
2094 // and (and (not A, not B), C)
2097 BOpc = BOp->getOpcode();
2099 if (BOpc == Instruction::And)
2100 BOpc = Instruction::Or;
2101 else if (BOpc == Instruction::Or)
2102 BOpc = Instruction::And;
2106 // If this node is not part of the or/and tree, emit it as a branch.
2107 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2108 BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2109 BOp->getParent() != CurBB->getBasicBlock() ||
2110 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2111 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2112 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2113 TProb, FProb, InvertCond);
2117 // Create TmpBB after CurBB.
2118 MachineFunction::iterator BBI(CurBB);
2119 MachineFunction &MF = DAG.getMachineFunction();
2120 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2121 CurBB->getParent()->insert(++BBI, TmpBB);
2123 if (Opc == Instruction::Or) {
2124 // Codegen X | Y as:
2133 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2134 // The requirement is that
2135 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2136 // = TrueProb for original BB.
2137 // Assuming the original probabilities are A and B, one choice is to set
2138 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2139 // A/(1+B) and 2B/(1+B). This choice assumes that
2140 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2141 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2142 // TmpBB, but the math is more complicated.
2144 auto NewTrueProb = TProb / 2;
2145 auto NewFalseProb = TProb / 2 + FProb;
2146 // Emit the LHS condition.
2147 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2148 NewTrueProb, NewFalseProb, InvertCond);
2150 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2151 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2152 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2153 // Emit the RHS condition into TmpBB.
2154 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2155 Probs[0], Probs[1], InvertCond);
2157 assert(Opc == Instruction::And && "Unknown merge op!");
2158 // Codegen X & Y as:
2166 // This requires creation of TmpBB after CurBB.
2168 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2169 // The requirement is that
2170 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2171 // = FalseProb for original BB.
2172 // Assuming the original probabilities are A and B, one choice is to set
2173 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2174 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2175 // TrueProb for BB1 * FalseProb for TmpBB.
2177 auto NewTrueProb = TProb + FProb / 2;
2178 auto NewFalseProb = FProb / 2;
2179 // Emit the LHS condition.
2180 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2181 NewTrueProb, NewFalseProb, InvertCond);
2183 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2184 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2185 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2186 // Emit the RHS condition into TmpBB.
2187 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2188 Probs[0], Probs[1], InvertCond);
2192 /// If the set of cases should be emitted as a series of branches, return true.
2193 /// If we should emit this as a bunch of and/or'd together conditions, return
2196 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2197 if (Cases.size() != 2) return true;
2199 // If this is two comparisons of the same values or'd or and'd together, they
2200 // will get folded into a single comparison, so don't emit two blocks.
2201 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2202 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2203 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2204 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2208 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2209 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2210 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2211 Cases[0].CC == Cases[1].CC &&
2212 isa<Constant>(Cases[0].CmpRHS) &&
2213 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2214 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2216 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2223 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2224 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2226 // Update machine-CFG edges.
2227 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2229 if (I.isUnconditional()) {
2230 // Update machine-CFG edges.
2231 BrMBB->addSuccessor(Succ0MBB);
2233 // If this is not a fall-through branch or optimizations are switched off,
2235 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2236 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2237 MVT::Other, getControlRoot(),
2238 DAG.getBasicBlock(Succ0MBB)));
2243 // If this condition is one of the special cases we handle, do special stuff
2245 const Value *CondVal = I.getCondition();
2246 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2248 // If this is a series of conditions that are or'd or and'd together, emit
2249 // this as a sequence of branches instead of setcc's with and/or operations.
2250 // As long as jumps are not expensive, this should improve performance.
2251 // For example, instead of something like:
2263 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2264 Instruction::BinaryOps Opcode = BOp->getOpcode();
2265 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2266 !I.getMetadata(LLVMContext::MD_unpredictable) &&
2267 (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2268 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2270 getEdgeProbability(BrMBB, Succ0MBB),
2271 getEdgeProbability(BrMBB, Succ1MBB),
2272 /*InvertCond=*/false);
2273 // If the compares in later blocks need to use values not currently
2274 // exported from this block, export them now. This block should always
2275 // be the first entry.
2276 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2278 // Allow some cases to be rejected.
2279 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2280 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2281 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2282 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2285 // Emit the branch for this block.
2286 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2287 SL->SwitchCases.erase(SL->SwitchCases.begin());
2291 // Okay, we decided not to do this, remove any inserted MBB's and clear
2293 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2294 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2296 SL->SwitchCases.clear();
2300 // Create a CaseBlock record representing this branch.
2301 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2302 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2304 // Use visitSwitchCase to actually insert the fast branch sequence for this
2306 visitSwitchCase(CB, BrMBB);
2309 /// visitSwitchCase - Emits the necessary code to represent a single node in
2310 /// the binary search tree resulting from lowering a switch instruction.
2311 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2312 MachineBasicBlock *SwitchBB) {
2314 SDValue CondLHS = getValue(CB.CmpLHS);
2317 if (CB.CC == ISD::SETTRUE) {
2318 // Branch or fall through to TrueBB.
2319 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2320 SwitchBB->normalizeSuccProbs();
2321 if (CB.TrueBB != NextBlock(SwitchBB)) {
2322 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2323 DAG.getBasicBlock(CB.TrueBB)));
2328 auto &TLI = DAG.getTargetLoweringInfo();
2329 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2331 // Build the setcc now.
2333 // Fold "(X == true)" to X and "(X == false)" to !X to
2334 // handle common cases produced by branch lowering.
2335 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2336 CB.CC == ISD::SETEQ)
2338 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2339 CB.CC == ISD::SETEQ) {
2340 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2341 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2343 SDValue CondRHS = getValue(CB.CmpRHS);
2345 // If a pointer's DAG type is larger than its memory type then the DAG
2346 // values are zero-extended. This breaks signed comparisons so truncate
2347 // back to the underlying type before doing the compare.
2348 if (CondLHS.getValueType() != MemVT) {
2349 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2350 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2352 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2355 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2357 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2358 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2360 SDValue CmpOp = getValue(CB.CmpMHS);
2361 EVT VT = CmpOp.getValueType();
2363 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2364 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2367 SDValue SUB = DAG.getNode(ISD::SUB, dl,
2368 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2369 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2370 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2374 // Update successor info
2375 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2376 // TrueBB and FalseBB are always different unless the incoming IR is
2377 // degenerate. This only happens when running llc on weird IR.
2378 if (CB.TrueBB != CB.FalseBB)
2379 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2380 SwitchBB->normalizeSuccProbs();
2382 // If the lhs block is the next block, invert the condition so that we can
2383 // fall through to the lhs instead of the rhs block.
2384 if (CB.TrueBB == NextBlock(SwitchBB)) {
2385 std::swap(CB.TrueBB, CB.FalseBB);
2386 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2387 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2390 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2391 MVT::Other, getControlRoot(), Cond,
2392 DAG.getBasicBlock(CB.TrueBB));
2394 // Insert the false branch. Do this even if it's a fall through branch,
2395 // this makes it easier to do DAG optimizations which require inverting
2396 // the branch condition.
2397 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2398 DAG.getBasicBlock(CB.FalseBB));
2400 DAG.setRoot(BrCond);
2403 /// visitJumpTable - Emit JumpTable node in the current MBB
2404 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2405 // Emit the code for the jump table
2406 assert(JT.Reg != -1U && "Should lower JT Header first!");
2407 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2408 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2410 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2411 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2412 MVT::Other, Index.getValue(1),
2414 DAG.setRoot(BrJumpTable);
2417 /// visitJumpTableHeader - This function emits necessary code to produce index
2418 /// in the JumpTable from switch case.
2419 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2420 JumpTableHeader &JTH,
2421 MachineBasicBlock *SwitchBB) {
2422 SDLoc dl = getCurSDLoc();
2424 // Subtract the lowest switch case value from the value being switched on.
2425 SDValue SwitchOp = getValue(JTH.SValue);
2426 EVT VT = SwitchOp.getValueType();
2427 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2428 DAG.getConstant(JTH.First, dl, VT));
2430 // The SDNode we just created, which holds the value being switched on minus
2431 // the smallest case value, needs to be copied to a virtual register so it
2432 // can be used as an index into the jump table in a subsequent basic block.
2433 // This value may be smaller or larger than the target's pointer type, and
2434 // therefore require extension or truncating.
2435 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2436 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2438 unsigned JumpTableReg =
2439 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2440 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2441 JumpTableReg, SwitchOp);
2442 JT.Reg = JumpTableReg;
2444 if (!JTH.OmitRangeCheck) {
2445 // Emit the range check for the jump table, and branch to the default block
2446 // for the switch statement if the value being switched on exceeds the
2447 // largest case in the switch.
2448 SDValue CMP = DAG.getSetCC(
2449 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2450 Sub.getValueType()),
2451 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2453 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2454 MVT::Other, CopyTo, CMP,
2455 DAG.getBasicBlock(JT.Default));
2457 // Avoid emitting unnecessary branches to the next block.
2458 if (JT.MBB != NextBlock(SwitchBB))
2459 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2460 DAG.getBasicBlock(JT.MBB));
2462 DAG.setRoot(BrCond);
2464 // Avoid emitting unnecessary branches to the next block.
2465 if (JT.MBB != NextBlock(SwitchBB))
2466 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2467 DAG.getBasicBlock(JT.MBB)));
2469 DAG.setRoot(CopyTo);
2473 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2474 /// variable if there exists one.
2475 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2478 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2479 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2480 MachineFunction &MF = DAG.getMachineFunction();
2481 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2482 MachineSDNode *Node =
2483 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2485 MachinePointerInfo MPInfo(Global);
2486 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2487 MachineMemOperand::MODereferenceable;
2488 MachineMemOperand *MemRef = MF.getMachineMemOperand(
2489 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2490 DAG.setNodeMemRefs(Node, {MemRef});
2492 if (PtrTy != PtrMemTy)
2493 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2494 return SDValue(Node, 0);
2497 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2498 /// tail spliced into a stack protector check success bb.
2500 /// For a high level explanation of how this fits into the stack protector
2501 /// generation see the comment on the declaration of class
2502 /// StackProtectorDescriptor.
2503 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2504 MachineBasicBlock *ParentBB) {
2506 // First create the loads to the guard/stack slot for the comparison.
2507 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2508 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2509 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2511 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2512 int FI = MFI.getStackProtectorIndex();
2515 SDLoc dl = getCurSDLoc();
2516 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2517 const Module &M = *ParentBB->getParent()->getFunction().getParent();
2518 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2520 // Generate code to load the content of the guard slot.
2521 SDValue GuardVal = DAG.getLoad(
2522 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2523 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2524 MachineMemOperand::MOVolatile);
2526 if (TLI.useStackGuardXorFP())
2527 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2529 // Retrieve guard check function, nullptr if instrumentation is inlined.
2530 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2531 // The target provides a guard check function to validate the guard value.
2532 // Generate a call to that function with the content of the guard slot as
2534 FunctionType *FnTy = GuardCheckFn->getFunctionType();
2535 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2537 TargetLowering::ArgListTy Args;
2538 TargetLowering::ArgListEntry Entry;
2539 Entry.Node = GuardVal;
2540 Entry.Ty = FnTy->getParamType(0);
2541 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2542 Entry.IsInReg = true;
2543 Args.push_back(Entry);
2545 TargetLowering::CallLoweringInfo CLI(DAG);
2546 CLI.setDebugLoc(getCurSDLoc())
2547 .setChain(DAG.getEntryNode())
2548 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2549 getValue(GuardCheckFn), std::move(Args));
2551 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2552 DAG.setRoot(Result.second);
2556 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2557 // Otherwise, emit a volatile load to retrieve the stack guard value.
2558 SDValue Chain = DAG.getEntryNode();
2559 if (TLI.useLoadStackGuardNode()) {
2560 Guard = getLoadStackGuard(DAG, dl, Chain);
2562 const Value *IRGuard = TLI.getSDagStackGuard(M);
2563 SDValue GuardPtr = getValue(IRGuard);
2565 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2566 MachinePointerInfo(IRGuard, 0), Align,
2567 MachineMemOperand::MOVolatile);
2570 // Perform the comparison via a subtract/getsetcc.
2571 EVT VT = Guard.getValueType();
2572 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2574 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2576 Sub.getValueType()),
2577 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2579 // If the sub is not 0, then we know the guard/stackslot do not equal, so
2580 // branch to failure MBB.
2581 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2582 MVT::Other, GuardVal.getOperand(0),
2583 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2584 // Otherwise branch to success MBB.
2585 SDValue Br = DAG.getNode(ISD::BR, dl,
2587 DAG.getBasicBlock(SPD.getSuccessMBB()));
2592 /// Codegen the failure basic block for a stack protector check.
2594 /// A failure stack protector machine basic block consists simply of a call to
2595 /// __stack_chk_fail().
2597 /// For a high level explanation of how this fits into the stack protector
2598 /// generation see the comment on the declaration of class
2599 /// StackProtectorDescriptor.
2601 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2602 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2604 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2605 None, false, getCurSDLoc(), false, false).second;
2606 // On PS4, the "return address" must still be within the calling function,
2607 // even if it's at the very end, so emit an explicit TRAP here.
2608 // Passing 'true' for doesNotReturn above won't generate the trap for us.
2609 if (TM.getTargetTriple().isPS4CPU())
2610 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2615 /// visitBitTestHeader - This function emits necessary code to produce value
2616 /// suitable for "bit tests"
2617 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2618 MachineBasicBlock *SwitchBB) {
2619 SDLoc dl = getCurSDLoc();
2621 // Subtract the minimum value
2622 SDValue SwitchOp = getValue(B.SValue);
2623 EVT VT = SwitchOp.getValueType();
2624 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2625 DAG.getConstant(B.First, dl, VT));
2628 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2629 SDValue RangeCmp = DAG.getSetCC(
2630 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2631 Sub.getValueType()),
2632 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2634 // Determine the type of the test operands.
2635 bool UsePtrType = false;
2636 if (!TLI.isTypeLegal(VT))
2639 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2640 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2641 // Switch table case range are encoded into series of masks.
2642 // Just use pointer type, it's guaranteed to fit.
2648 VT = TLI.getPointerTy(DAG.getDataLayout());
2649 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2652 B.RegVT = VT.getSimpleVT();
2653 B.Reg = FuncInfo.CreateReg(B.RegVT);
2654 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2656 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2658 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2659 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2660 SwitchBB->normalizeSuccProbs();
2662 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2663 MVT::Other, CopyTo, RangeCmp,
2664 DAG.getBasicBlock(B.Default));
2666 // Avoid emitting unnecessary branches to the next block.
2667 if (MBB != NextBlock(SwitchBB))
2668 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2669 DAG.getBasicBlock(MBB));
2671 DAG.setRoot(BrRange);
2674 /// visitBitTestCase - this function produces one "bit test"
2675 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2676 MachineBasicBlock* NextMBB,
2677 BranchProbability BranchProbToNext,
2680 MachineBasicBlock *SwitchBB) {
2681 SDLoc dl = getCurSDLoc();
2683 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2685 unsigned PopCount = countPopulation(B.Mask);
2686 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2687 if (PopCount == 1) {
2688 // Testing for a single bit; just compare the shift count with what it
2689 // would need to be to shift a 1 bit in that position.
2691 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2692 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2694 } else if (PopCount == BB.Range) {
2695 // There is only one zero bit in the range, test for it directly.
2697 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2698 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2701 // Make desired shift
2702 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2703 DAG.getConstant(1, dl, VT), ShiftOp);
2705 // Emit bit tests and jumps
2706 SDValue AndOp = DAG.getNode(ISD::AND, dl,
2707 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2709 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2710 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2713 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2714 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2715 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2716 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2717 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2718 // one as they are relative probabilities (and thus work more like weights),
2719 // and hence we need to normalize them to let the sum of them become one.
2720 SwitchBB->normalizeSuccProbs();
2722 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2723 MVT::Other, getControlRoot(),
2724 Cmp, DAG.getBasicBlock(B.TargetBB));
2726 // Avoid emitting unnecessary branches to the next block.
2727 if (NextMBB != NextBlock(SwitchBB))
2728 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2729 DAG.getBasicBlock(NextMBB));
2734 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2735 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2737 // Retrieve successors. Look through artificial IR level blocks like
2738 // catchswitch for successors.
2739 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2740 const BasicBlock *EHPadBB = I.getSuccessor(1);
2742 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2743 // have to do anything here to lower funclet bundles.
2744 assert(!I.hasOperandBundlesOtherThan(
2745 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2746 "Cannot lower invokes with arbitrary operand bundles yet!");
2748 const Value *Callee(I.getCalledValue());
2749 const Function *Fn = dyn_cast<Function>(Callee);
2750 if (isa<InlineAsm>(Callee))
2752 else if (Fn && Fn->isIntrinsic()) {
2753 switch (Fn->getIntrinsicID()) {
2755 llvm_unreachable("Cannot invoke this intrinsic");
2756 case Intrinsic::donothing:
2757 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2759 case Intrinsic::experimental_patchpoint_void:
2760 case Intrinsic::experimental_patchpoint_i64:
2761 visitPatchpoint(&I, EHPadBB);
2763 case Intrinsic::experimental_gc_statepoint:
2764 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2766 case Intrinsic::wasm_rethrow_in_catch: {
2767 // This is usually done in visitTargetIntrinsic, but this intrinsic is
2768 // special because it can be invoked, so we manually lower it to a DAG
2770 SmallVector<SDValue, 8> Ops;
2771 Ops.push_back(getRoot()); // inchain
2772 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2774 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2775 TLI.getPointerTy(DAG.getDataLayout())));
2776 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2777 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2781 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2782 // Currently we do not lower any intrinsic calls with deopt operand bundles.
2783 // Eventually we will support lowering the @llvm.experimental.deoptimize
2784 // intrinsic, and right now there are no plans to support other intrinsics
2785 // with deopt state.
2786 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2788 LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2791 // If the value of the invoke is used outside of its defining block, make it
2792 // available as a virtual register.
2793 // We already took care of the exported value for the statepoint instruction
2794 // during call to the LowerStatepoint.
2795 if (!isStatepoint(I)) {
2796 CopyToExportRegsIfNeeded(&I);
2799 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2800 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2801 BranchProbability EHPadBBProb =
2802 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2803 : BranchProbability::getZero();
2804 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2806 // Update successor info.
2807 addSuccessorWithProb(InvokeMBB, Return);
2808 for (auto &UnwindDest : UnwindDests) {
2809 UnwindDest.first->setIsEHPad();
2810 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2812 InvokeMBB->normalizeSuccProbs();
2814 // Drop into normal successor.
2815 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2816 DAG.getBasicBlock(Return)));
2819 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2820 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2822 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2823 // have to do anything here to lower funclet bundles.
2824 assert(!I.hasOperandBundlesOtherThan(
2825 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2826 "Cannot lower callbrs with arbitrary operand bundles yet!");
2828 assert(isa<InlineAsm>(I.getCalledValue()) &&
2829 "Only know how to handle inlineasm callbr");
2832 // Retrieve successors.
2833 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2835 // Update successor info.
2836 addSuccessorWithProb(CallBrMBB, Return);
2837 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2838 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2839 addSuccessorWithProb(CallBrMBB, Target);
2841 CallBrMBB->normalizeSuccProbs();
2843 // Drop into default successor.
2844 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2845 MVT::Other, getControlRoot(),
2846 DAG.getBasicBlock(Return)));
2849 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2850 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2853 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2854 assert(FuncInfo.MBB->isEHPad() &&
2855 "Call to landingpad not in landing pad!");
2857 // If there aren't registers to copy the values into (e.g., during SjLj
2858 // exceptions), then don't bother to create these DAG nodes.
2859 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2860 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2861 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2862 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2865 // If landingpad's return type is token type, we don't create DAG nodes
2866 // for its exception pointer and selector value. The extraction of exception
2867 // pointer or selector value from token type landingpads is not currently
2869 if (LP.getType()->isTokenTy())
2872 SmallVector<EVT, 2> ValueVTs;
2873 SDLoc dl = getCurSDLoc();
2874 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2875 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2877 // Get the two live-in registers as SDValues. The physregs have already been
2878 // copied into virtual registers.
2880 if (FuncInfo.ExceptionPointerVirtReg) {
2881 Ops[0] = DAG.getZExtOrTrunc(
2882 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2883 FuncInfo.ExceptionPointerVirtReg,
2884 TLI.getPointerTy(DAG.getDataLayout())),
2887 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2889 Ops[1] = DAG.getZExtOrTrunc(
2890 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2891 FuncInfo.ExceptionSelectorVirtReg,
2892 TLI.getPointerTy(DAG.getDataLayout())),
2896 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2897 DAG.getVTList(ValueVTs), Ops);
2901 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2902 MachineBasicBlock *Last) {
2904 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2905 if (SL->JTCases[i].first.HeaderBB == First)
2906 SL->JTCases[i].first.HeaderBB = Last;
2908 // Update BitTestCases.
2909 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2910 if (SL->BitTestCases[i].Parent == First)
2911 SL->BitTestCases[i].Parent = Last;
2914 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2915 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2917 // Update machine-CFG edges with unique successors.
2918 SmallSet<BasicBlock*, 32> Done;
2919 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2920 BasicBlock *BB = I.getSuccessor(i);
2921 bool Inserted = Done.insert(BB).second;
2925 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2926 addSuccessorWithProb(IndirectBrMBB, Succ);
2928 IndirectBrMBB->normalizeSuccProbs();
2930 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2931 MVT::Other, getControlRoot(),
2932 getValue(I.getAddress())));
2935 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2936 if (!DAG.getTarget().Options.TrapUnreachable)
2939 // We may be able to ignore unreachable behind a noreturn call.
2940 if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2941 const BasicBlock &BB = *I.getParent();
2942 if (&I != &BB.front()) {
2943 BasicBlock::const_iterator PredI =
2944 std::prev(BasicBlock::const_iterator(&I));
2945 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2946 if (Call->doesNotReturn())
2952 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2955 void SelectionDAGBuilder::visitFSub(const User &I) {
2956 // -0.0 - X --> fneg
2957 Type *Ty = I.getType();
2958 if (isa<Constant>(I.getOperand(0)) &&
2959 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2960 SDValue Op2 = getValue(I.getOperand(1));
2961 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2962 Op2.getValueType(), Op2));
2966 visitBinary(I, ISD::FSUB);
2969 /// Checks if the given instruction performs a vector reduction, in which case
2970 /// we have the freedom to alter the elements in the result as long as the
2971 /// reduction of them stays unchanged.
2972 static bool isVectorReductionOp(const User *I) {
2973 const Instruction *Inst = dyn_cast<Instruction>(I);
2974 if (!Inst || !Inst->getType()->isVectorTy())
2977 auto OpCode = Inst->getOpcode();
2979 case Instruction::Add:
2980 case Instruction::Mul:
2981 case Instruction::And:
2982 case Instruction::Or:
2983 case Instruction::Xor:
2985 case Instruction::FAdd:
2986 case Instruction::FMul:
2987 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2988 if (FPOp->getFastMathFlags().isFast())
2995 unsigned ElemNum = Inst->getType()->getVectorNumElements();
2996 // Ensure the reduction size is a power of 2.
2997 if (!isPowerOf2_32(ElemNum))
3000 unsigned ElemNumToReduce = ElemNum;
3002 // Do DFS search on the def-use chain from the given instruction. We only
3003 // allow four kinds of operations during the search until we reach the
3004 // instruction that extracts the first element from the vector:
3006 // 1. The reduction operation of the same opcode as the given instruction.
3010 // 3. ShuffleVector instruction together with a reduction operation that
3011 // does a partial reduction.
3013 // 4. ExtractElement that extracts the first element from the vector, and we
3014 // stop searching the def-use chain here.
3016 // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3017 // from 1-3 to the stack to continue the DFS. The given instruction is not
3018 // a reduction operation if we meet any other instructions other than those
3021 SmallVector<const User *, 16> UsersToVisit{Inst};
3022 SmallPtrSet<const User *, 16> Visited;
3023 bool ReduxExtracted = false;
3025 while (!UsersToVisit.empty()) {
3026 auto User = UsersToVisit.back();
3027 UsersToVisit.pop_back();
3028 if (!Visited.insert(User).second)
3031 for (const auto &U : User->users()) {
3032 auto Inst = dyn_cast<Instruction>(U);
3036 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3037 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3038 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3040 UsersToVisit.push_back(U);
3041 } else if (const ShuffleVectorInst *ShufInst =
3042 dyn_cast<ShuffleVectorInst>(U)) {
3043 // Detect the following pattern: A ShuffleVector instruction together
3044 // with a reduction that do partial reduction on the first and second
3045 // ElemNumToReduce / 2 elements, and store the result in
3046 // ElemNumToReduce / 2 elements in another vector.
3048 unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3049 if (ResultElements < ElemNum)
3052 if (ElemNumToReduce == 1)
3054 if (!isa<UndefValue>(U->getOperand(1)))
3056 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3057 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3059 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3060 if (ShufInst->getMaskValue(i) != -1)
3063 // There is only one user of this ShuffleVector instruction, which
3064 // must be a reduction operation.
3065 if (!U->hasOneUse())
3068 auto U2 = dyn_cast<Instruction>(*U->user_begin());
3069 if (!U2 || U2->getOpcode() != OpCode)
3072 // Check operands of the reduction operation.
3073 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3074 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3075 UsersToVisit.push_back(U2);
3076 ElemNumToReduce /= 2;
3079 } else if (isa<ExtractElementInst>(U)) {
3080 // At this moment we should have reduced all elements in the vector.
3081 if (ElemNumToReduce != 1)
3084 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3085 if (!Val || !Val->isZero())
3088 ReduxExtracted = true;
3093 return ReduxExtracted;
3096 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3099 SDValue Op = getValue(I.getOperand(0));
3100 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3102 setValue(&I, UnNodeValue);
3105 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3107 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3108 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3109 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3111 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3112 Flags.setExact(ExactOp->isExact());
3114 if (isVectorReductionOp(&I)) {
3115 Flags.setVectorReduction(true);
3116 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3119 SDValue Op1 = getValue(I.getOperand(0));
3120 SDValue Op2 = getValue(I.getOperand(1));
3121 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3123 setValue(&I, BinNodeValue);
3126 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3127 SDValue Op1 = getValue(I.getOperand(0));
3128 SDValue Op2 = getValue(I.getOperand(1));
3130 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3131 Op1.getValueType(), DAG.getDataLayout());
3133 // Coerce the shift amount to the right type if we can.
3134 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3135 unsigned ShiftSize = ShiftTy.getSizeInBits();
3136 unsigned Op2Size = Op2.getValueSizeInBits();
3137 SDLoc DL = getCurSDLoc();
3139 // If the operand is smaller than the shift count type, promote it.
3140 if (ShiftSize > Op2Size)
3141 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3143 // If the operand is larger than the shift count type but the shift
3144 // count type has enough bits to represent any shift value, truncate
3145 // it now. This is a common case and it exposes the truncate to
3146 // optimization early.
3147 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3148 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3149 // Otherwise we'll need to temporarily settle for some other convenient
3150 // type. Type legalization will make adjustments once the shiftee is split.
3152 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3159 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3161 if (const OverflowingBinaryOperator *OFBinOp =
3162 dyn_cast<const OverflowingBinaryOperator>(&I)) {
3163 nuw = OFBinOp->hasNoUnsignedWrap();
3164 nsw = OFBinOp->hasNoSignedWrap();
3166 if (const PossiblyExactOperator *ExactOp =
3167 dyn_cast<const PossiblyExactOperator>(&I))
3168 exact = ExactOp->isExact();
3171 Flags.setExact(exact);
3172 Flags.setNoSignedWrap(nsw);
3173 Flags.setNoUnsignedWrap(nuw);
3174 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3179 void SelectionDAGBuilder::visitSDiv(const User &I) {
3180 SDValue Op1 = getValue(I.getOperand(0));
3181 SDValue Op2 = getValue(I.getOperand(1));
3184 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3185 cast<PossiblyExactOperator>(&I)->isExact());
3186 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3190 void SelectionDAGBuilder::visitICmp(const User &I) {
3191 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3192 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3193 predicate = IC->getPredicate();
3194 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3195 predicate = ICmpInst::Predicate(IC->getPredicate());
3196 SDValue Op1 = getValue(I.getOperand(0));
3197 SDValue Op2 = getValue(I.getOperand(1));
3198 ISD::CondCode Opcode = getICmpCondCode(predicate);
3200 auto &TLI = DAG.getTargetLoweringInfo();
3202 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3204 // If a pointer's DAG type is larger than its memory type then the DAG values
3205 // are zero-extended. This breaks signed comparisons so truncate back to the
3206 // underlying type before doing the compare.
3207 if (Op1.getValueType() != MemVT) {
3208 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3209 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3212 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3214 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3217 void SelectionDAGBuilder::visitFCmp(const User &I) {
3218 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3219 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3220 predicate = FC->getPredicate();
3221 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3222 predicate = FCmpInst::Predicate(FC->getPredicate());
3223 SDValue Op1 = getValue(I.getOperand(0));
3224 SDValue Op2 = getValue(I.getOperand(1));
3226 ISD::CondCode Condition = getFCmpCondCode(predicate);
3227 auto *FPMO = dyn_cast<FPMathOperator>(&I);
3228 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3229 Condition = getFCmpCodeWithoutNaN(Condition);
3231 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3233 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3236 // Check if the condition of the select has one use or two users that are both
3237 // selects with the same condition.
3238 static bool hasOnlySelectUsers(const Value *Cond) {
3239 return llvm::all_of(Cond->users(), [](const Value *V) {
3240 return isa<SelectInst>(V);
3244 void SelectionDAGBuilder::visitSelect(const User &I) {
3245 SmallVector<EVT, 4> ValueVTs;
3246 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3248 unsigned NumValues = ValueVTs.size();
3249 if (NumValues == 0) return;
3251 SmallVector<SDValue, 4> Values(NumValues);
3252 SDValue Cond = getValue(I.getOperand(0));
3253 SDValue LHSVal = getValue(I.getOperand(1));
3254 SDValue RHSVal = getValue(I.getOperand(2));
3255 auto BaseOps = {Cond};
3256 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3257 ISD::VSELECT : ISD::SELECT;
3259 bool IsUnaryAbs = false;
3261 // Min/max matching is only viable if all output VTs are the same.
3262 if (is_splat(ValueVTs)) {
3263 EVT VT = ValueVTs[0];
3264 LLVMContext &Ctx = *DAG.getContext();
3265 auto &TLI = DAG.getTargetLoweringInfo();
3267 // We care about the legality of the operation after it has been type
3269 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3270 VT != TLI.getTypeToTransformTo(Ctx, VT))
3271 VT = TLI.getTypeToTransformTo(Ctx, VT);
3273 // If the vselect is legal, assume we want to leave this as a vector setcc +
3274 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3275 // min/max is legal on the scalar type.
3276 bool UseScalarMinMax = VT.isVector() &&
3277 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3280 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3281 ISD::NodeType Opc = ISD::DELETED_NODE;
3282 switch (SPR.Flavor) {
3283 case SPF_UMAX: Opc = ISD::UMAX; break;
3284 case SPF_UMIN: Opc = ISD::UMIN; break;
3285 case SPF_SMAX: Opc = ISD::SMAX; break;
3286 case SPF_SMIN: Opc = ISD::SMIN; break;
3288 switch (SPR.NaNBehavior) {
3289 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3290 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
3291 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3292 case SPNB_RETURNS_ANY: {
3293 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3295 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3296 Opc = ISD::FMINIMUM;
3297 else if (UseScalarMinMax)
3298 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3299 ISD::FMINNUM : ISD::FMINIMUM;
3305 switch (SPR.NaNBehavior) {
3306 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3307 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
3308 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3309 case SPNB_RETURNS_ANY:
3311 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3313 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3314 Opc = ISD::FMAXIMUM;
3315 else if (UseScalarMinMax)
3316 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3317 ISD::FMAXNUM : ISD::FMAXIMUM;
3326 // TODO: we need to produce sub(0, abs(X)).
3330 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3331 (TLI.isOperationLegalOrCustom(Opc, VT) ||
3333 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3334 // If the underlying comparison instruction is used by any other
3335 // instruction, the consumed instructions won't be destroyed, so it is
3336 // not profitable to convert to a min/max.
3337 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3339 LHSVal = getValue(LHS);
3340 RHSVal = getValue(RHS);
3346 LHSVal = getValue(LHS);
3352 for (unsigned i = 0; i != NumValues; ++i) {
3354 DAG.getNode(OpCode, getCurSDLoc(),
3355 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3356 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3359 for (unsigned i = 0; i != NumValues; ++i) {
3360 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3361 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3362 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3363 Values[i] = DAG.getNode(
3364 OpCode, getCurSDLoc(),
3365 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3369 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3370 DAG.getVTList(ValueVTs), Values));
3373 void SelectionDAGBuilder::visitTrunc(const User &I) {
3374 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3375 SDValue N = getValue(I.getOperand(0));
3376 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3378 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3381 void SelectionDAGBuilder::visitZExt(const User &I) {
3382 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3383 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3384 SDValue N = getValue(I.getOperand(0));
3385 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3387 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3390 void SelectionDAGBuilder::visitSExt(const User &I) {
3391 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3392 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3393 SDValue N = getValue(I.getOperand(0));
3394 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3396 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3399 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3400 // FPTrunc is never a no-op cast, no need to check
3401 SDValue N = getValue(I.getOperand(0));
3402 SDLoc dl = getCurSDLoc();
3403 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3404 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3405 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3406 DAG.getTargetConstant(
3407 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3410 void SelectionDAGBuilder::visitFPExt(const User &I) {
3411 // FPExt is never a no-op cast, no need to check
3412 SDValue N = getValue(I.getOperand(0));
3413 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3415 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3418 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3419 // FPToUI is never a no-op cast, no need to check
3420 SDValue N = getValue(I.getOperand(0));
3421 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3423 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3426 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3427 // FPToSI is never a no-op cast, no need to check
3428 SDValue N = getValue(I.getOperand(0));
3429 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3431 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3434 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3435 // UIToFP is never a no-op cast, no need to check
3436 SDValue N = getValue(I.getOperand(0));
3437 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3439 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3442 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3443 // SIToFP is never a no-op cast, no need to check
3444 SDValue N = getValue(I.getOperand(0));
3445 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3447 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3450 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3451 // What to do depends on the size of the integer and the size of the pointer.
3452 // We can either truncate, zero extend, or no-op, accordingly.
3453 SDValue N = getValue(I.getOperand(0));
3454 auto &TLI = DAG.getTargetLoweringInfo();
3455 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3458 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3459 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3460 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3464 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3465 // What to do depends on the size of the integer and the size of the pointer.
3466 // We can either truncate, zero extend, or no-op, accordingly.
3467 SDValue N = getValue(I.getOperand(0));
3468 auto &TLI = DAG.getTargetLoweringInfo();
3469 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3470 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3471 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3472 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3476 void SelectionDAGBuilder::visitBitCast(const User &I) {
3477 SDValue N = getValue(I.getOperand(0));
3478 SDLoc dl = getCurSDLoc();
3479 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3482 // BitCast assures us that source and destination are the same size so this is
3483 // either a BITCAST or a no-op.
3484 if (DestVT != N.getValueType())
3485 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3486 DestVT, N)); // convert types.
3487 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3488 // might fold any kind of constant expression to an integer constant and that
3489 // is not what we are looking for. Only recognize a bitcast of a genuine
3490 // constant integer as an opaque constant.
3491 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3492 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3495 setValue(&I, N); // noop cast.
3498 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3499 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3500 const Value *SV = I.getOperand(0);
3501 SDValue N = getValue(SV);
3502 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3504 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3505 unsigned DestAS = I.getType()->getPointerAddressSpace();
3507 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3508 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3513 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3514 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3515 SDValue InVec = getValue(I.getOperand(0));
3516 SDValue InVal = getValue(I.getOperand(1));
3517 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3518 TLI.getVectorIdxTy(DAG.getDataLayout()));
3519 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3520 TLI.getValueType(DAG.getDataLayout(), I.getType()),
3521 InVec, InVal, InIdx));
3524 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3525 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3526 SDValue InVec = getValue(I.getOperand(0));
3527 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3528 TLI.getVectorIdxTy(DAG.getDataLayout()));
3529 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3530 TLI.getValueType(DAG.getDataLayout(), I.getType()),
3534 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3535 SDValue Src1 = getValue(I.getOperand(0));
3536 SDValue Src2 = getValue(I.getOperand(1));
3537 SDLoc DL = getCurSDLoc();
3539 SmallVector<int, 8> Mask;
3540 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3541 unsigned MaskNumElts = Mask.size();
3543 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3544 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3545 EVT SrcVT = Src1.getValueType();
3546 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3548 if (SrcNumElts == MaskNumElts) {
3549 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3553 // Normalize the shuffle vector since mask and vector length don't match.
3554 if (SrcNumElts < MaskNumElts) {
3555 // Mask is longer than the source vectors. We can use concatenate vector to
3556 // make the mask and vectors lengths match.
3558 if (MaskNumElts % SrcNumElts == 0) {
3559 // Mask length is a multiple of the source vector length.
3560 // Check if the shuffle is some kind of concatenation of the input
3562 unsigned NumConcat = MaskNumElts / SrcNumElts;
3563 bool IsConcat = true;
3564 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3565 for (unsigned i = 0; i != MaskNumElts; ++i) {
3569 // Ensure the indices in each SrcVT sized piece are sequential and that
3570 // the same source is used for the whole piece.
3571 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3572 (ConcatSrcs[i / SrcNumElts] >= 0 &&
3573 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3577 // Remember which source this index came from.
3578 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3581 // The shuffle is concatenating multiple vectors together. Just emit
3582 // a CONCAT_VECTORS operation.
3584 SmallVector<SDValue, 8> ConcatOps;
3585 for (auto Src : ConcatSrcs) {
3587 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3589 ConcatOps.push_back(Src1);
3591 ConcatOps.push_back(Src2);
3593 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3598 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3599 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3600 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3603 // Pad both vectors with undefs to make them the same length as the mask.
3604 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3606 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3607 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3611 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3612 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3614 // Readjust mask for new input vector length.
3615 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3616 for (unsigned i = 0; i != MaskNumElts; ++i) {
3618 if (Idx >= (int)SrcNumElts)
3619 Idx -= SrcNumElts - PaddedMaskNumElts;
3623 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3625 // If the concatenated vector was padded, extract a subvector with the
3626 // correct number of elements.
3627 if (MaskNumElts != PaddedMaskNumElts)
3628 Result = DAG.getNode(
3629 ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3630 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3632 setValue(&I, Result);
3636 if (SrcNumElts > MaskNumElts) {
3637 // Analyze the access pattern of the vector to see if we can extract
3638 // two subvectors and do the shuffle.
3639 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
3640 bool CanExtract = true;
3641 for (int Idx : Mask) {
3646 if (Idx >= (int)SrcNumElts) {
3651 // If all the indices come from the same MaskNumElts sized portion of
3652 // the sources we can use extract. Also make sure the extract wouldn't
3653 // extract past the end of the source.
3654 int NewStartIdx = alignDown(Idx, MaskNumElts);
3655 if (NewStartIdx + MaskNumElts > SrcNumElts ||
3656 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3658 // Make sure we always update StartIdx as we use it to track if all
3659 // elements are undef.
3660 StartIdx[Input] = NewStartIdx;
3663 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3664 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3668 // Extract appropriate subvector and generate a vector shuffle
3669 for (unsigned Input = 0; Input < 2; ++Input) {
3670 SDValue &Src = Input == 0 ? Src1 : Src2;
3671 if (StartIdx[Input] < 0)
3672 Src = DAG.getUNDEF(VT);
3675 ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3676 DAG.getConstant(StartIdx[Input], DL,
3677 TLI.getVectorIdxTy(DAG.getDataLayout())));
3681 // Calculate new mask.
3682 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3683 for (int &Idx : MappedOps) {
3684 if (Idx >= (int)SrcNumElts)
3685 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3690 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3695 // We can't use either concat vectors or extract subvectors so fall back to
3696 // replacing the shuffle with extract and build vector.
3697 // to insert and build vector.
3698 EVT EltVT = VT.getVectorElementType();
3699 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3700 SmallVector<SDValue,8> Ops;
3701 for (int Idx : Mask) {
3705 Res = DAG.getUNDEF(EltVT);
3707 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3708 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3710 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3711 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3717 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3720 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3721 ArrayRef<unsigned> Indices;
3722 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3723 Indices = IV->getIndices();
3725 Indices = cast<ConstantExpr>(&I)->getIndices();
3727 const Value *Op0 = I.getOperand(0);
3728 const Value *Op1 = I.getOperand(1);
3729 Type *AggTy = I.getType();
3730 Type *ValTy = Op1->getType();
3731 bool IntoUndef = isa<UndefValue>(Op0);
3732 bool FromUndef = isa<UndefValue>(Op1);
3734 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3736 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3737 SmallVector<EVT, 4> AggValueVTs;
3738 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3739 SmallVector<EVT, 4> ValValueVTs;
3740 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3742 unsigned NumAggValues = AggValueVTs.size();
3743 unsigned NumValValues = ValValueVTs.size();
3744 SmallVector<SDValue, 4> Values(NumAggValues);
3746 // Ignore an insertvalue that produces an empty object
3747 if (!NumAggValues) {
3748 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3752 SDValue Agg = getValue(Op0);
3754 // Copy the beginning value(s) from the original aggregate.
3755 for (; i != LinearIndex; ++i)
3756 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3757 SDValue(Agg.getNode(), Agg.getResNo() + i);
3758 // Copy values from the inserted value(s).
3760 SDValue Val = getValue(Op1);
3761 for (; i != LinearIndex + NumValValues; ++i)
3762 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3763 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3765 // Copy remaining value(s) from the original aggregate.
3766 for (; i != NumAggValues; ++i)
3767 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3768 SDValue(Agg.getNode(), Agg.getResNo() + i);
3770 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3771 DAG.getVTList(AggValueVTs), Values));
3774 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3775 ArrayRef<unsigned> Indices;
3776 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3777 Indices = EV->getIndices();
3779 Indices = cast<ConstantExpr>(&I)->getIndices();
3781 const Value *Op0 = I.getOperand(0);
3782 Type *AggTy = Op0->getType();
3783 Type *ValTy = I.getType();
3784 bool OutOfUndef = isa<UndefValue>(Op0);
3786 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3788 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3789 SmallVector<EVT, 4> ValValueVTs;
3790 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3792 unsigned NumValValues = ValValueVTs.size();
3794 // Ignore a extractvalue that produces an empty object
3795 if (!NumValValues) {
3796 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3800 SmallVector<SDValue, 4> Values(NumValValues);
3802 SDValue Agg = getValue(Op0);
3803 // Copy out the selected value(s).
3804 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3805 Values[i - LinearIndex] =
3807 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3808 SDValue(Agg.getNode(), Agg.getResNo() + i);
3810 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3811 DAG.getVTList(ValValueVTs), Values));
3814 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3815 Value *Op0 = I.getOperand(0);
3816 // Note that the pointer operand may be a vector of pointers. Take the scalar
3817 // element which holds a pointer.
3818 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3819 SDValue N = getValue(Op0);
3820 SDLoc dl = getCurSDLoc();
3821 auto &TLI = DAG.getTargetLoweringInfo();
3822 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3823 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3825 // Normalize Vector GEP - all scalar operands should be converted to the
3827 unsigned VectorWidth = I.getType()->isVectorTy() ?
3828 cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3830 if (VectorWidth && !N.getValueType().isVector()) {
3831 LLVMContext &Context = *DAG.getContext();
3832 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3833 N = DAG.getSplatBuildVector(VT, dl, N);
3836 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3838 const Value *Idx = GTI.getOperand();
3839 if (StructType *StTy = GTI.getStructTypeOrNull()) {
3840 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3843 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3845 // In an inbounds GEP with an offset that is nonnegative even when
3846 // interpreted as signed, assume there is no unsigned overflow.
3848 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3849 Flags.setNoUnsignedWrap(true);
3851 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3852 DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3855 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3856 MVT IdxTy = MVT::getIntegerVT(IdxSize);
3857 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3859 // If this is a scalar constant or a splat vector of constants,
3860 // handle it quickly.
3861 const auto *CI = dyn_cast<ConstantInt>(Idx);
3862 if (!CI && isa<ConstantDataVector>(Idx) &&
3863 cast<ConstantDataVector>(Idx)->getSplatValue())
3864 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3869 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3870 LLVMContext &Context = *DAG.getContext();
3871 SDValue OffsVal = VectorWidth ?
3872 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3873 DAG.getConstant(Offs, dl, IdxTy);
3875 // In an inbouds GEP with an offset that is nonnegative even when
3876 // interpreted as signed, assume there is no unsigned overflow.
3878 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3879 Flags.setNoUnsignedWrap(true);
3881 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3883 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3887 // N = N + Idx * ElementSize;
3888 SDValue IdxN = getValue(Idx);
3890 if (!IdxN.getValueType().isVector() && VectorWidth) {
3891 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3892 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3895 // If the index is smaller or larger than intptr_t, truncate or extend
3897 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3899 // If this is a multiply by a power of two, turn it into a shl
3900 // immediately. This is a very common case.
3901 if (ElementSize != 1) {
3902 if (ElementSize.isPowerOf2()) {
3903 unsigned Amt = ElementSize.logBase2();
3904 IdxN = DAG.getNode(ISD::SHL, dl,
3905 N.getValueType(), IdxN,
3906 DAG.getConstant(Amt, dl, IdxN.getValueType()));
3908 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3909 IdxN.getValueType());
3910 IdxN = DAG.getNode(ISD::MUL, dl,
3911 N.getValueType(), IdxN, Scale);
3915 N = DAG.getNode(ISD::ADD, dl,
3916 N.getValueType(), N, IdxN);
3920 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3921 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3926 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3927 // If this is a fixed sized alloca in the entry block of the function,
3928 // allocate it statically on the stack.
3929 if (FuncInfo.StaticAllocaMap.count(&I))
3930 return; // getValue will auto-populate this.
3932 SDLoc dl = getCurSDLoc();
3933 Type *Ty = I.getAllocatedType();
3934 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3935 auto &DL = DAG.getDataLayout();
3936 uint64_t TySize = DL.getTypeAllocSize(Ty);
3938 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3940 SDValue AllocSize = getValue(I.getArraySize());
3942 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3943 if (AllocSize.getValueType() != IntPtr)
3944 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3946 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3948 DAG.getConstant(TySize, dl, IntPtr));
3950 // Handle alignment. If the requested alignment is less than or equal to
3951 // the stack alignment, ignore it. If the size is greater than or equal to
3952 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3953 unsigned StackAlign =
3954 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3955 if (Align <= StackAlign)
3958 // Round the size of the allocation up to the stack alignment size
3959 // by add SA-1 to the size. This doesn't overflow because we're computing
3960 // an address inside an alloca.
3962 Flags.setNoUnsignedWrap(true);
3963 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3964 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3966 // Mask out the low bits for alignment purposes.
3968 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3969 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3971 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3972 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3973 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3975 DAG.setRoot(DSA.getValue(1));
3977 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3980 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3982 return visitAtomicLoad(I);
3984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3985 const Value *SV = I.getOperand(0);
3986 if (TLI.supportSwiftError()) {
3987 // Swifterror values can come from either a function parameter with
3988 // swifterror attribute or an alloca with swifterror attribute.
3989 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3990 if (Arg->hasSwiftErrorAttr())
3991 return visitLoadFromSwiftError(I);
3994 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3995 if (Alloca->isSwiftError())
3996 return visitLoadFromSwiftError(I);
4000 SDValue Ptr = getValue(SV);
4002 Type *Ty = I.getType();
4004 bool isVolatile = I.isVolatile();
4005 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
4006 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
4007 bool isDereferenceable =
4008 isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
4009 unsigned Alignment = I.getAlignment();
4012 I.getAAMetadata(AAInfo);
4013 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4015 SmallVector<EVT, 4> ValueVTs, MemVTs;
4016 SmallVector<uint64_t, 4> Offsets;
4017 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4018 unsigned NumValues = ValueVTs.size();
4023 bool ConstantMemory = false;
4024 if (isVolatile || NumValues > MaxParallelChains)
4025 // Serialize volatile loads with other side effects.
4028 AA->pointsToConstantMemory(MemoryLocation(
4030 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4032 // Do not serialize (non-volatile) loads of constant memory with anything.
4033 Root = DAG.getEntryNode();
4034 ConstantMemory = true;
4036 // Do not serialize non-volatile loads against each other.
4037 Root = DAG.getRoot();
4040 SDLoc dl = getCurSDLoc();
4043 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4045 // An aggregate load cannot wrap around the address space, so offsets to its
4046 // parts don't wrap either.
4048 Flags.setNoUnsignedWrap(true);
4050 SmallVector<SDValue, 4> Values(NumValues);
4051 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4052 EVT PtrVT = Ptr.getValueType();
4053 unsigned ChainI = 0;
4054 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4055 // Serializing loads here may result in excessive register pressure, and
4056 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4057 // could recover a bit by hoisting nodes upward in the chain by recognizing
4058 // they are side-effect free or do not alias. The optimizer should really
4059 // avoid this case by converting large object/array copies to llvm.memcpy
4060 // (MaxParallelChains should always remain as failsafe).
4061 if (ChainI == MaxParallelChains) {
4062 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4063 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4064 makeArrayRef(Chains.data(), ChainI));
4068 SDValue A = DAG.getNode(ISD::ADD, dl,
4070 DAG.getConstant(Offsets[i], dl, PtrVT),
4072 auto MMOFlags = MachineMemOperand::MONone;
4074 MMOFlags |= MachineMemOperand::MOVolatile;
4076 MMOFlags |= MachineMemOperand::MONonTemporal;
4078 MMOFlags |= MachineMemOperand::MOInvariant;
4079 if (isDereferenceable)
4080 MMOFlags |= MachineMemOperand::MODereferenceable;
4081 MMOFlags |= TLI.getMMOFlags(I);
4083 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4084 MachinePointerInfo(SV, Offsets[i]), Alignment,
4085 MMOFlags, AAInfo, Ranges);
4086 Chains[ChainI] = L.getValue(1);
4088 if (MemVTs[i] != ValueVTs[i])
4089 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4094 if (!ConstantMemory) {
4095 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4096 makeArrayRef(Chains.data(), ChainI));
4100 PendingLoads.push_back(Chain);
4103 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4104 DAG.getVTList(ValueVTs), Values));
4107 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4108 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4109 "call visitStoreToSwiftError when backend supports swifterror");
4111 SmallVector<EVT, 4> ValueVTs;
4112 SmallVector<uint64_t, 4> Offsets;
4113 const Value *SrcV = I.getOperand(0);
4114 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4115 SrcV->getType(), ValueVTs, &Offsets);
4116 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4117 "expect a single EVT for swifterror");
4119 SDValue Src = getValue(SrcV);
4120 // Create a virtual register, then update the virtual register.
4122 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4123 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4124 // Chain can be getRoot or getControlRoot.
4125 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4126 SDValue(Src.getNode(), Src.getResNo()));
4127 DAG.setRoot(CopyNode);
4130 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4131 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4132 "call visitLoadFromSwiftError when backend supports swifterror");
4134 assert(!I.isVolatile() &&
4135 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
4136 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
4137 "Support volatile, non temporal, invariant for load_from_swift_error");
4139 const Value *SV = I.getOperand(0);
4140 Type *Ty = I.getType();
4142 I.getAAMetadata(AAInfo);
4145 !AA->pointsToConstantMemory(MemoryLocation(
4146 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4148 "load_from_swift_error should not be constant memory");
4150 SmallVector<EVT, 4> ValueVTs;
4151 SmallVector<uint64_t, 4> Offsets;
4152 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4153 ValueVTs, &Offsets);
4154 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4155 "expect a single EVT for swifterror");
4157 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4158 SDValue L = DAG.getCopyFromReg(
4159 getRoot(), getCurSDLoc(),
4160 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4165 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4167 return visitAtomicStore(I);
4169 const Value *SrcV = I.getOperand(0);
4170 const Value *PtrV = I.getOperand(1);
4172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4173 if (TLI.supportSwiftError()) {
4174 // Swifterror values can come from either a function parameter with
4175 // swifterror attribute or an alloca with swifterror attribute.
4176 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4177 if (Arg->hasSwiftErrorAttr())
4178 return visitStoreToSwiftError(I);
4181 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4182 if (Alloca->isSwiftError())
4183 return visitStoreToSwiftError(I);
4187 SmallVector<EVT, 4> ValueVTs, MemVTs;
4188 SmallVector<uint64_t, 4> Offsets;
4189 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4190 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4191 unsigned NumValues = ValueVTs.size();
4195 // Get the lowered operands. Note that we do this after
4196 // checking if NumResults is zero, because with zero results
4197 // the operands won't have values in the map.
4198 SDValue Src = getValue(SrcV);
4199 SDValue Ptr = getValue(PtrV);
4201 SDValue Root = getRoot();
4202 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4203 SDLoc dl = getCurSDLoc();
4204 EVT PtrVT = Ptr.getValueType();
4205 unsigned Alignment = I.getAlignment();
4207 I.getAAMetadata(AAInfo);
4209 auto MMOFlags = MachineMemOperand::MONone;
4211 MMOFlags |= MachineMemOperand::MOVolatile;
4212 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
4213 MMOFlags |= MachineMemOperand::MONonTemporal;
4214 MMOFlags |= TLI.getMMOFlags(I);
4216 // An aggregate load cannot wrap around the address space, so offsets to its
4217 // parts don't wrap either.
4219 Flags.setNoUnsignedWrap(true);
4221 unsigned ChainI = 0;
4222 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4223 // See visitLoad comments.
4224 if (ChainI == MaxParallelChains) {
4225 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4226 makeArrayRef(Chains.data(), ChainI));
4230 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4231 DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4232 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4233 if (MemVTs[i] != ValueVTs[i])
4234 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4236 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4237 Alignment, MMOFlags, AAInfo);
4238 Chains[ChainI] = St;
4241 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4242 makeArrayRef(Chains.data(), ChainI));
4243 DAG.setRoot(StoreNode);
4246 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4247 bool IsCompressing) {
4248 SDLoc sdl = getCurSDLoc();
4250 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4251 unsigned& Alignment) {
4252 // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4253 Src0 = I.getArgOperand(0);
4254 Ptr = I.getArgOperand(1);
4255 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4256 Mask = I.getArgOperand(3);
4258 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4259 unsigned& Alignment) {
4260 // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4261 Src0 = I.getArgOperand(0);
4262 Ptr = I.getArgOperand(1);
4263 Mask = I.getArgOperand(2);
4267 Value *PtrOperand, *MaskOperand, *Src0Operand;
4270 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4272 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4274 SDValue Ptr = getValue(PtrOperand);
4275 SDValue Src0 = getValue(Src0Operand);
4276 SDValue Mask = getValue(MaskOperand);
4278 EVT VT = Src0.getValueType();
4280 Alignment = DAG.getEVTAlignment(VT);
4283 I.getAAMetadata(AAInfo);
4285 MachineMemOperand *MMO =
4286 DAG.getMachineFunction().
4287 getMachineMemOperand(MachinePointerInfo(PtrOperand),
4288 MachineMemOperand::MOStore, VT.getStoreSize(),
4290 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4291 MMO, false /* Truncating */,
4293 DAG.setRoot(StoreNode);
4294 setValue(&I, StoreNode);
4297 // Get a uniform base for the Gather/Scatter intrinsic.
4298 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4299 // We try to represent it as a base pointer + vector of indices.
4300 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4301 // The first operand of the GEP may be a single pointer or a vector of pointers
4303 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4305 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
4306 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4308 // When the first GEP operand is a single pointer - it is the uniform base we
4309 // are looking for. If first operand of the GEP is a splat vector - we
4310 // extract the splat value and use it as a uniform base.
4311 // In all other cases the function returns 'false'.
4312 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4313 SDValue &Scale, SelectionDAGBuilder* SDB) {
4314 SelectionDAG& DAG = SDB->DAG;
4315 LLVMContext &Context = *DAG.getContext();
4317 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4318 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4322 const Value *GEPPtr = GEP->getPointerOperand();
4323 if (!GEPPtr->getType()->isVectorTy())
4325 else if (!(Ptr = getSplatValue(GEPPtr)))
4328 unsigned FinalIndex = GEP->getNumOperands() - 1;
4329 Value *IndexVal = GEP->getOperand(FinalIndex);
4331 // Ensure all the other indices are 0.
4332 for (unsigned i = 1; i < FinalIndex; ++i) {
4333 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4334 if (!C || !C->isZero())
4338 // The operands of the GEP may be defined in another basic block.
4339 // In this case we'll not find nodes for the operands.
4340 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4344 const DataLayout &DL = DAG.getDataLayout();
4345 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4346 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4347 Base = SDB->getValue(Ptr);
4348 Index = SDB->getValue(IndexVal);
4350 if (!Index.getValueType().isVector()) {
4351 unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4352 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4353 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4358 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4359 SDLoc sdl = getCurSDLoc();
4361 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4362 const Value *Ptr = I.getArgOperand(1);
4363 SDValue Src0 = getValue(I.getArgOperand(0));
4364 SDValue Mask = getValue(I.getArgOperand(3));
4365 EVT VT = Src0.getValueType();
4366 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4368 Alignment = DAG.getEVTAlignment(VT);
4369 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4372 I.getAAMetadata(AAInfo);
4377 const Value *BasePtr = Ptr;
4378 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4380 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4381 MachineMemOperand *MMO = DAG.getMachineFunction().
4382 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4383 MachineMemOperand::MOStore, VT.getStoreSize(),
4386 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4387 Index = getValue(Ptr);
4388 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4390 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4391 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4393 DAG.setRoot(Scatter);
4394 setValue(&I, Scatter);
4397 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4398 SDLoc sdl = getCurSDLoc();
4400 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4401 unsigned& Alignment) {
4402 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4403 Ptr = I.getArgOperand(0);
4404 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4405 Mask = I.getArgOperand(2);
4406 Src0 = I.getArgOperand(3);
4408 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4409 unsigned& Alignment) {
4410 // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4411 Ptr = I.getArgOperand(0);
4413 Mask = I.getArgOperand(1);
4414 Src0 = I.getArgOperand(2);
4417 Value *PtrOperand, *MaskOperand, *Src0Operand;
4420 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4422 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4424 SDValue Ptr = getValue(PtrOperand);
4425 SDValue Src0 = getValue(Src0Operand);
4426 SDValue Mask = getValue(MaskOperand);
4428 EVT VT = Src0.getValueType();
4430 Alignment = DAG.getEVTAlignment(VT);
4433 I.getAAMetadata(AAInfo);
4434 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4436 // Do not serialize masked loads of constant memory with anything.
4438 !AA || !AA->pointsToConstantMemory(MemoryLocation(
4440 LocationSize::precise(
4441 DAG.getDataLayout().getTypeStoreSize(I.getType())),
4443 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4445 MachineMemOperand *MMO =
4446 DAG.getMachineFunction().
4447 getMachineMemOperand(MachinePointerInfo(PtrOperand),
4448 MachineMemOperand::MOLoad, VT.getStoreSize(),
4449 Alignment, AAInfo, Ranges);
4451 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4452 ISD::NON_EXTLOAD, IsExpanding);
4454 PendingLoads.push_back(Load.getValue(1));
4458 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4459 SDLoc sdl = getCurSDLoc();
4461 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4462 const Value *Ptr = I.getArgOperand(0);
4463 SDValue Src0 = getValue(I.getArgOperand(3));
4464 SDValue Mask = getValue(I.getArgOperand(2));
4466 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4467 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4468 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4470 Alignment = DAG.getEVTAlignment(VT);
4473 I.getAAMetadata(AAInfo);
4474 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4476 SDValue Root = DAG.getRoot();
4480 const Value *BasePtr = Ptr;
4481 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4482 bool ConstantMemory = false;
4483 if (UniformBase && AA &&
4484 AA->pointsToConstantMemory(
4485 MemoryLocation(BasePtr,
4486 LocationSize::precise(
4487 DAG.getDataLayout().getTypeStoreSize(I.getType())),
4489 // Do not serialize (non-volatile) loads of constant memory with anything.
4490 Root = DAG.getEntryNode();
4491 ConstantMemory = true;
4494 MachineMemOperand *MMO =
4495 DAG.getMachineFunction().
4496 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4497 MachineMemOperand::MOLoad, VT.getStoreSize(),
4498 Alignment, AAInfo, Ranges);
4501 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4502 Index = getValue(Ptr);
4503 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4505 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4506 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4509 SDValue OutChain = Gather.getValue(1);
4510 if (!ConstantMemory)
4511 PendingLoads.push_back(OutChain);
4512 setValue(&I, Gather);
4515 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4516 SDLoc dl = getCurSDLoc();
4517 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4518 AtomicOrdering FailureOrdering = I.getFailureOrdering();
4519 SyncScope::ID SSID = I.getSyncScopeID();
4521 SDValue InChain = getRoot();
4523 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4524 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4526 auto Alignment = DAG.getEVTAlignment(MemVT);
4528 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4530 Flags |= MachineMemOperand::MOVolatile;
4531 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4533 MachineFunction &MF = DAG.getMachineFunction();
4534 MachineMemOperand *MMO =
4535 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4536 Flags, MemVT.getStoreSize(), Alignment,
4537 AAMDNodes(), nullptr, SSID, SuccessOrdering,
4540 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4541 dl, MemVT, VTs, InChain,
4542 getValue(I.getPointerOperand()),
4543 getValue(I.getCompareOperand()),
4544 getValue(I.getNewValOperand()), MMO);
4546 SDValue OutChain = L.getValue(2);
4549 DAG.setRoot(OutChain);
4552 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4553 SDLoc dl = getCurSDLoc();
4555 switch (I.getOperation()) {
4556 default: llvm_unreachable("Unknown atomicrmw operation");
4557 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4558 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
4559 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
4560 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
4561 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4562 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
4563 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
4564 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
4565 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
4566 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4567 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4568 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4569 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4571 AtomicOrdering Ordering = I.getOrdering();
4572 SyncScope::ID SSID = I.getSyncScopeID();
4574 SDValue InChain = getRoot();
4576 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4577 auto Alignment = DAG.getEVTAlignment(MemVT);
4579 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4581 Flags |= MachineMemOperand::MOVolatile;
4582 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4584 MachineFunction &MF = DAG.getMachineFunction();
4585 MachineMemOperand *MMO =
4586 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4587 MemVT.getStoreSize(), Alignment, AAMDNodes(),
4588 nullptr, SSID, Ordering);
4591 DAG.getAtomic(NT, dl, MemVT, InChain,
4592 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4595 SDValue OutChain = L.getValue(1);
4598 DAG.setRoot(OutChain);
4601 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4602 SDLoc dl = getCurSDLoc();
4603 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4606 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4607 TLI.getFenceOperandTy(DAG.getDataLayout()));
4608 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4609 TLI.getFenceOperandTy(DAG.getDataLayout()));
4610 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4613 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4614 SDLoc dl = getCurSDLoc();
4615 AtomicOrdering Order = I.getOrdering();
4616 SyncScope::ID SSID = I.getSyncScopeID();
4618 SDValue InChain = getRoot();
4620 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4621 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4622 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4624 if (!TLI.supportsUnalignedAtomics() &&
4625 I.getAlignment() < MemVT.getSizeInBits() / 8)
4626 report_fatal_error("Cannot generate unaligned atomic load");
4628 auto Flags = MachineMemOperand::MOLoad;
4630 Flags |= MachineMemOperand::MOVolatile;
4631 if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
4632 Flags |= MachineMemOperand::MOInvariant;
4633 if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
4634 DAG.getDataLayout()))
4635 Flags |= MachineMemOperand::MODereferenceable;
4637 Flags |= TLI.getMMOFlags(I);
4639 MachineMemOperand *MMO =
4640 DAG.getMachineFunction().
4641 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4642 Flags, MemVT.getStoreSize(),
4643 I.getAlignment() ? I.getAlignment() :
4644 DAG.getEVTAlignment(MemVT),
4645 AAMDNodes(), nullptr, SSID, Order);
4647 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4649 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4650 getValue(I.getPointerOperand()), MMO);
4652 SDValue OutChain = L.getValue(1);
4654 L = DAG.getPtrExtOrTrunc(L, dl, VT);
4657 DAG.setRoot(OutChain);
4660 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4661 SDLoc dl = getCurSDLoc();
4663 AtomicOrdering Ordering = I.getOrdering();
4664 SyncScope::ID SSID = I.getSyncScopeID();
4666 SDValue InChain = getRoot();
4668 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4670 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4672 if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4673 report_fatal_error("Cannot generate unaligned atomic store");
4675 auto Flags = MachineMemOperand::MOStore;
4677 Flags |= MachineMemOperand::MOVolatile;
4678 Flags |= TLI.getMMOFlags(I);
4680 MachineFunction &MF = DAG.getMachineFunction();
4681 MachineMemOperand *MMO =
4682 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4683 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4684 nullptr, SSID, Ordering);
4686 SDValue Val = getValue(I.getValueOperand());
4687 if (Val.getValueType() != MemVT)
4688 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4690 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4691 getValue(I.getPointerOperand()), Val, MMO);
4694 DAG.setRoot(OutChain);
4697 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4699 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4700 unsigned Intrinsic) {
4701 // Ignore the callsite's attributes. A specific call site may be marked with
4702 // readnone, but the lowering code will expect the chain based on the
4704 const Function *F = I.getCalledFunction();
4705 bool HasChain = !F->doesNotAccessMemory();
4706 bool OnlyLoad = HasChain && F->onlyReadsMemory();
4708 // Build the operand list.
4709 SmallVector<SDValue, 8> Ops;
4710 if (HasChain) { // If this intrinsic has side-effects, chainify it.
4712 // We don't need to serialize loads against other loads.
4713 Ops.push_back(DAG.getRoot());
4715 Ops.push_back(getRoot());
4719 // Info is set by getTgtMemInstrinsic
4720 TargetLowering::IntrinsicInfo Info;
4721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4722 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4723 DAG.getMachineFunction(),
4726 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4727 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4728 Info.opc == ISD::INTRINSIC_W_CHAIN)
4729 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4730 TLI.getPointerTy(DAG.getDataLayout())));
4732 // Add all operands of the call to the operand list.
4733 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4734 SDValue Op = getValue(I.getArgOperand(i));
4738 SmallVector<EVT, 4> ValueVTs;
4739 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4742 ValueVTs.push_back(MVT::Other);
4744 SDVTList VTs = DAG.getVTList(ValueVTs);
4748 if (IsTgtIntrinsic) {
4749 // This is target intrinsic that touches memory
4751 I.getAAMetadata(AAInfo);
4753 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4754 MachinePointerInfo(Info.ptrVal, Info.offset),
4755 Info.align, Info.flags, Info.size, AAInfo);
4756 } else if (!HasChain) {
4757 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4758 } else if (!I.getType()->isVoidTy()) {
4759 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4761 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4765 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4767 PendingLoads.push_back(Chain);
4772 if (!I.getType()->isVoidTy()) {
4773 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4774 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4775 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4777 Result = lowerRangeToAssertZExt(DAG, I, Result);
4779 setValue(&I, Result);
4783 /// GetSignificand - Get the significand and build it into a floating-point
4784 /// number with exponent of 1:
4786 /// Op = (Op & 0x007fffff) | 0x3f800000;
4788 /// where Op is the hexadecimal representation of floating point value.
4789 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4790 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4791 DAG.getConstant(0x007fffff, dl, MVT::i32));
4792 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4793 DAG.getConstant(0x3f800000, dl, MVT::i32));
4794 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4797 /// GetExponent - Get the exponent:
4799 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4801 /// where Op is the hexadecimal representation of floating point value.
4802 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4803 const TargetLowering &TLI, const SDLoc &dl) {
4804 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4805 DAG.getConstant(0x7f800000, dl, MVT::i32));
4806 SDValue t1 = DAG.getNode(
4807 ISD::SRL, dl, MVT::i32, t0,
4808 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4809 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4810 DAG.getConstant(127, dl, MVT::i32));
4811 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4814 /// getF32Constant - Get 32-bit floating point constant.
4815 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4817 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4821 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4822 SelectionDAG &DAG) {
4823 // TODO: What fast-math-flags should be set on the floating-point nodes?
4825 // IntegerPartOfX = ((int32_t)(t0);
4826 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4828 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
4829 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4830 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4832 // IntegerPartOfX <<= 23;
4833 IntegerPartOfX = DAG.getNode(
4834 ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4835 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4836 DAG.getDataLayout())));
4838 SDValue TwoToFractionalPartOfX;
4839 if (LimitFloatPrecision <= 6) {
4840 // For floating-point precision of 6:
4842 // TwoToFractionalPartOfX =
4844 // (0.735607626f + 0.252464424f * x) * x;
4846 // error 0.0144103317, which is 6 bits
4847 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4848 getF32Constant(DAG, 0x3e814304, dl));
4849 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4850 getF32Constant(DAG, 0x3f3c50c8, dl));
4851 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4852 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4853 getF32Constant(DAG, 0x3f7f5e7e, dl));
4854 } else if (LimitFloatPrecision <= 12) {
4855 // For floating-point precision of 12:
4857 // TwoToFractionalPartOfX =
4860 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4862 // error 0.000107046256, which is 13 to 14 bits
4863 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4864 getF32Constant(DAG, 0x3da235e3, dl));
4865 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4866 getF32Constant(DAG, 0x3e65b8f3, dl));
4867 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4868 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4869 getF32Constant(DAG, 0x3f324b07, dl));
4870 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4871 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4872 getF32Constant(DAG, 0x3f7ff8fd, dl));
4873 } else { // LimitFloatPrecision <= 18
4874 // For floating-point precision of 18:
4876 // TwoToFractionalPartOfX =
4880 // (0.554906021e-1f +
4881 // (0.961591928e-2f +
4882 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4883 // error 2.47208000*10^(-7), which is better than 18 bits
4884 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4885 getF32Constant(DAG, 0x3924b03e, dl));
4886 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4887 getF32Constant(DAG, 0x3ab24b87, dl));
4888 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4889 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4890 getF32Constant(DAG, 0x3c1d8c17, dl));
4891 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4892 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4893 getF32Constant(DAG, 0x3d634a1d, dl));
4894 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4895 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4896 getF32Constant(DAG, 0x3e75fe14, dl));
4897 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4898 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4899 getF32Constant(DAG, 0x3f317234, dl));
4900 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4901 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4902 getF32Constant(DAG, 0x3f800000, dl));
4905 // Add the exponent into the result in integer domain.
4906 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4907 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4908 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4911 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4912 /// limited-precision mode.
4913 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4914 const TargetLowering &TLI) {
4915 if (Op.getValueType() == MVT::f32 &&
4916 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4918 // Put the exponent in the right bit position for later addition to the
4921 // #define LOG2OFe 1.4426950f
4922 // t0 = Op * LOG2OFe
4924 // TODO: What fast-math-flags should be set here?
4925 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4926 getF32Constant(DAG, 0x3fb8aa3b, dl));
4927 return getLimitedPrecisionExp2(t0, dl, DAG);
4930 // No special expansion.
4931 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4934 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4935 /// limited-precision mode.
4936 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4937 const TargetLowering &TLI) {
4938 // TODO: What fast-math-flags should be set on the floating-point nodes?
4940 if (Op.getValueType() == MVT::f32 &&
4941 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4942 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4944 // Scale the exponent by log(2) [0.69314718f].
4945 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4946 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4947 getF32Constant(DAG, 0x3f317218, dl));
4949 // Get the significand and build it into a floating-point number with
4951 SDValue X = GetSignificand(DAG, Op1, dl);
4953 SDValue LogOfMantissa;
4954 if (LimitFloatPrecision <= 6) {
4955 // For floating-point precision of 6:
4959 // (1.4034025f - 0.23903021f * x) * x;
4961 // error 0.0034276066, which is better than 8 bits
4962 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4963 getF32Constant(DAG, 0xbe74c456, dl));
4964 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4965 getF32Constant(DAG, 0x3fb3a2b1, dl));
4966 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4967 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4968 getF32Constant(DAG, 0x3f949a29, dl));
4969 } else if (LimitFloatPrecision <= 12) {
4970 // For floating-point precision of 12:
4976 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4978 // error 0.000061011436, which is 14 bits
4979 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4980 getF32Constant(DAG, 0xbd67b6d6, dl));
4981 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4982 getF32Constant(DAG, 0x3ee4f4b8, dl));
4983 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4984 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4985 getF32Constant(DAG, 0x3fbc278b, dl));
4986 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4987 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4988 getF32Constant(DAG, 0x40348e95, dl));
4989 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4990 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4991 getF32Constant(DAG, 0x3fdef31a, dl));
4992 } else { // LimitFloatPrecision <= 18
4993 // For floating-point precision of 18:
5001 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5003 // error 0.0000023660568, which is better than 18 bits
5004 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5005 getF32Constant(DAG, 0xbc91e5ac, dl));
5006 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5007 getF32Constant(DAG, 0x3e4350aa, dl));
5008 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5009 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5010 getF32Constant(DAG, 0x3f60d3e3, dl));
5011 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5012 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5013 getF32Constant(DAG, 0x4011cdf0, dl));
5014 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5015 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5016 getF32Constant(DAG, 0x406cfd1c, dl));
5017 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5018 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5019 getF32Constant(DAG, 0x408797cb, dl));
5020 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5021 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5022 getF32Constant(DAG, 0x4006dcab, dl));
5025 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5028 // No special expansion.
5029 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5032 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5033 /// limited-precision mode.
5034 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5035 const TargetLowering &TLI) {
5036 // TODO: What fast-math-flags should be set on the floating-point nodes?
5038 if (Op.getValueType() == MVT::f32 &&
5039 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5040 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5042 // Get the exponent.
5043 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5045 // Get the significand and build it into a floating-point number with
5047 SDValue X = GetSignificand(DAG, Op1, dl);
5049 // Different possible minimax approximations of significand in
5050 // floating-point for various degrees of accuracy over [1,2].
5051 SDValue Log2ofMantissa;
5052 if (LimitFloatPrecision <= 6) {
5053 // For floating-point precision of 6:
5055 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5057 // error 0.0049451742, which is more than 7 bits
5058 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5059 getF32Constant(DAG, 0xbeb08fe0, dl));
5060 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5061 getF32Constant(DAG, 0x40019463, dl));
5062 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5063 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5064 getF32Constant(DAG, 0x3fd6633d, dl));
5065 } else if (LimitFloatPrecision <= 12) {
5066 // For floating-point precision of 12:
5072 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5074 // error 0.0000876136000, which is better than 13 bits
5075 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5076 getF32Constant(DAG, 0xbda7262e, dl));
5077 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5078 getF32Constant(DAG, 0x3f25280b, dl));
5079 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5080 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5081 getF32Constant(DAG, 0x4007b923, dl));
5082 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5083 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5084 getF32Constant(DAG, 0x40823e2f, dl));
5085 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5086 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5087 getF32Constant(DAG, 0x4020d29c, dl));
5088 } else { // LimitFloatPrecision <= 18
5089 // For floating-point precision of 18:
5098 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5100 // error 0.0000018516, which is better than 18 bits
5101 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5102 getF32Constant(DAG, 0xbcd2769e, dl));
5103 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5104 getF32Constant(DAG, 0x3e8ce0b9, dl));
5105 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5106 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5107 getF32Constant(DAG, 0x3fa22ae7, dl));
5108 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5109 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5110 getF32Constant(DAG, 0x40525723, dl));
5111 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5112 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5113 getF32Constant(DAG, 0x40aaf200, dl));
5114 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5115 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5116 getF32Constant(DAG, 0x40c39dad, dl));
5117 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5118 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5119 getF32Constant(DAG, 0x4042902c, dl));
5122 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5125 // No special expansion.
5126 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5129 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5130 /// limited-precision mode.
5131 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5132 const TargetLowering &TLI) {
5133 // TODO: What fast-math-flags should be set on the floating-point nodes?
5135 if (Op.getValueType() == MVT::f32 &&
5136 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5137 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5139 // Scale the exponent by log10(2) [0.30102999f].
5140 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5141 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5142 getF32Constant(DAG, 0x3e9a209a, dl));
5144 // Get the significand and build it into a floating-point number with
5146 SDValue X = GetSignificand(DAG, Op1, dl);
5148 SDValue Log10ofMantissa;
5149 if (LimitFloatPrecision <= 6) {
5150 // For floating-point precision of 6:
5152 // Log10ofMantissa =
5154 // (0.60948995f - 0.10380950f * x) * x;
5156 // error 0.0014886165, which is 6 bits
5157 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5158 getF32Constant(DAG, 0xbdd49a13, dl));
5159 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5160 getF32Constant(DAG, 0x3f1c0789, dl));
5161 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5162 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5163 getF32Constant(DAG, 0x3f011300, dl));
5164 } else if (LimitFloatPrecision <= 12) {
5165 // For floating-point precision of 12:
5167 // Log10ofMantissa =
5170 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5172 // error 0.00019228036, which is better than 12 bits
5173 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5174 getF32Constant(DAG, 0x3d431f31, dl));
5175 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5176 getF32Constant(DAG, 0x3ea21fb2, dl));
5177 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5178 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5179 getF32Constant(DAG, 0x3f6ae232, dl));
5180 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5181 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5182 getF32Constant(DAG, 0x3f25f7c3, dl));
5183 } else { // LimitFloatPrecision <= 18
5184 // For floating-point precision of 18:
5186 // Log10ofMantissa =
5191 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5193 // error 0.0000037995730, which is better than 18 bits
5194 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5195 getF32Constant(DAG, 0x3c5d51ce, dl));
5196 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5197 getF32Constant(DAG, 0x3e00685a, dl));
5198 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5199 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5200 getF32Constant(DAG, 0x3efb6798, dl));
5201 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5202 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5203 getF32Constant(DAG, 0x3f88d192, dl));
5204 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5205 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5206 getF32Constant(DAG, 0x3fc4316c, dl));
5207 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5208 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5209 getF32Constant(DAG, 0x3f57ce70, dl));
5212 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5215 // No special expansion.
5216 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5219 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5220 /// limited-precision mode.
5221 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5222 const TargetLowering &TLI) {
5223 if (Op.getValueType() == MVT::f32 &&
5224 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5225 return getLimitedPrecisionExp2(Op, dl, DAG);
5227 // No special expansion.
5228 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5231 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5232 /// limited-precision mode with x == 10.0f.
5233 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5234 SelectionDAG &DAG, const TargetLowering &TLI) {
5235 bool IsExp10 = false;
5236 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5237 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5238 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5240 IsExp10 = LHSC->isExactlyValue(Ten);
5244 // TODO: What fast-math-flags should be set on the FMUL node?
5246 // Put the exponent in the right bit position for later addition to the
5249 // #define LOG2OF10 3.3219281f
5250 // t0 = Op * LOG2OF10;
5251 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5252 getF32Constant(DAG, 0x40549a78, dl));
5253 return getLimitedPrecisionExp2(t0, dl, DAG);
5256 // No special expansion.
5257 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5260 /// ExpandPowI - Expand a llvm.powi intrinsic.
5261 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5262 SelectionDAG &DAG) {
5263 // If RHS is a constant, we can expand this out to a multiplication tree,
5264 // otherwise we end up lowering to a call to __powidf2 (for example). When
5265 // optimizing for size, we only want to do this if the expansion would produce
5266 // a small number of multiplies, otherwise we do the full expansion.
5267 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5268 // Get the exponent as a positive value.
5269 unsigned Val = RHSC->getSExtValue();
5270 if ((int)Val < 0) Val = -Val;
5272 // powi(x, 0) -> 1.0
5274 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5276 const Function &F = DAG.getMachineFunction().getFunction();
5277 if (!F.hasOptSize() ||
5278 // If optimizing for size, don't insert too many multiplies.
5279 // This inserts up to 5 multiplies.
5280 countPopulation(Val) + Log2_32(Val) < 7) {
5281 // We use the simple binary decomposition method to generate the multiply
5282 // sequence. There are more optimal ways to do this (for example,
5283 // powi(x,15) generates one more multiply than it should), but this has
5284 // the benefit of being both really simple and much better than a libcall.
5285 SDValue Res; // Logically starts equal to 1.0
5286 SDValue CurSquare = LHS;
5287 // TODO: Intrinsics should have fast-math-flags that propagate to these
5292 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5294 Res = CurSquare; // 1.0*CurSquare.
5297 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5298 CurSquare, CurSquare);
5302 // If the original was negative, invert the result, producing 1/(x*x*x).
5303 if (RHSC->getSExtValue() < 0)
5304 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5305 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5310 // Otherwise, expand to a libcall.
5311 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5314 // getUnderlyingArgReg - Find underlying register used for a truncated or
5315 // bitcasted argument.
5316 static unsigned getUnderlyingArgReg(const SDValue &N) {
5317 switch (N.getOpcode()) {
5318 case ISD::CopyFromReg:
5319 return cast<RegisterSDNode>(N.getOperand(1))->getReg();
5321 case ISD::AssertZext:
5322 case ISD::AssertSext:
5324 return getUnderlyingArgReg(N.getOperand(0));
5330 /// If the DbgValueInst is a dbg_value of a function argument, create the
5331 /// corresponding DBG_VALUE machine instruction for it now. At the end of
5332 /// instruction selection, they will be inserted to the entry BB.
5333 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5334 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5335 DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5336 const Argument *Arg = dyn_cast<Argument>(V);
5340 if (!IsDbgDeclare) {
5341 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5342 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5344 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5345 if (!IsInEntryBlock)
5348 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5349 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5350 // variable that also is a param.
5352 // Although, if we are at the top of the entry block already, we can still
5353 // emit using ArgDbgValue. This might catch some situations when the
5354 // dbg.value refers to an argument that isn't used in the entry block, so
5355 // any CopyToReg node would be optimized out and the only way to express
5356 // this DBG_VALUE is by using the physical reg (or FI) as done in this
5357 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
5358 // we should only emit as ArgDbgValue if the Variable is an argument to the
5359 // current function, and the dbg.value intrinsic is found in the entry
5361 bool VariableIsFunctionInputArg = Variable->isParameter() &&
5362 !DL->getInlinedAt();
5363 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5364 if (!IsInPrologue && !VariableIsFunctionInputArg)
5367 // Here we assume that a function argument on IR level only can be used to
5368 // describe one input parameter on source level. If we for example have
5369 // source code like this
5371 // struct A { long x, y; };
5372 // void foo(struct A a, long b) {
5380 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
5382 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5383 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5384 // call void @llvm.dbg.value(metadata i32 %b, "b",
5386 // call void @llvm.dbg.value(metadata i32 %a1, "b"
5389 // then the last dbg.value is describing a parameter "b" using a value that
5390 // is an argument. But since we already has used %a1 to describe a parameter
5391 // we should not handle that last dbg.value here (that would result in an
5392 // incorrect hoisting of the DBG_VALUE to the function entry).
5393 // Notice that we allow one dbg.value per IR level argument, to accomodate
5394 // for the situation with fragments above.
5395 if (VariableIsFunctionInputArg) {
5396 unsigned ArgNo = Arg->getArgNo();
5397 if (ArgNo >= FuncInfo.DescribedArgs.size())
5398 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5399 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5401 FuncInfo.DescribedArgs.set(ArgNo);
5405 MachineFunction &MF = DAG.getMachineFunction();
5406 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5408 bool IsIndirect = false;
5409 Optional<MachineOperand> Op;
5410 // Some arguments' frame index is recorded during argument lowering.
5411 int FI = FuncInfo.getArgumentFrameIndex(Arg);
5412 if (FI != std::numeric_limits<int>::max())
5413 Op = MachineOperand::CreateFI(FI);
5415 if (!Op && N.getNode()) {
5416 unsigned Reg = getUnderlyingArgReg(N);
5417 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5418 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5419 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5424 Op = MachineOperand::CreateReg(Reg, false);
5425 IsIndirect = IsDbgDeclare;
5429 if (!Op && N.getNode()) {
5430 // Check if frame index is available.
5431 SDValue LCandidate = peekThroughBitcasts(N);
5432 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5433 if (FrameIndexSDNode *FINode =
5434 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5435 Op = MachineOperand::CreateFI(FINode->getIndex());
5439 // Check if ValueMap has reg number.
5440 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5441 if (VMI != FuncInfo.ValueMap.end()) {
5442 const auto &TLI = DAG.getTargetLoweringInfo();
5443 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5444 V->getType(), getABIRegCopyCC(V));
5445 if (RFV.occupiesMultipleRegs()) {
5446 unsigned Offset = 0;
5447 for (auto RegAndSize : RFV.getRegsAndSizes()) {
5448 Op = MachineOperand::CreateReg(RegAndSize.first, false);
5449 auto FragmentExpr = DIExpression::createFragmentExpression(
5450 Expr, Offset, RegAndSize.second);
5453 FuncInfo.ArgDbgValues.push_back(
5454 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5455 Op->getReg(), Variable, *FragmentExpr));
5456 Offset += RegAndSize.second;
5460 Op = MachineOperand::CreateReg(VMI->second, false);
5461 IsIndirect = IsDbgDeclare;
5468 assert(Variable->isValidLocationForIntrinsic(DL) &&
5469 "Expected inlined-at fields to agree");
5470 IsIndirect = (Op->isReg()) ? IsIndirect : true;
5471 FuncInfo.ArgDbgValues.push_back(
5472 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5473 *Op, Variable, Expr));
5478 /// Return the appropriate SDDbgValue based on N.
5479 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5480 DILocalVariable *Variable,
5483 unsigned DbgSDNodeOrder) {
5484 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5485 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5486 // stack slot locations.
5488 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5489 // debug values here after optimization:
5491 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
5492 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5494 // Both describe the direct values of their associated variables.
5495 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5496 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5498 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5499 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5502 // VisualStudio defines setjmp as _setjmp
5503 #if defined(_MSC_VER) && defined(setjmp) && \
5504 !defined(setjmp_undefined_for_msvc)
5505 # pragma push_macro("setjmp")
5507 # define setjmp_undefined_for_msvc
5510 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5511 switch (Intrinsic) {
5512 case Intrinsic::smul_fix:
5513 return ISD::SMULFIX;
5514 case Intrinsic::umul_fix:
5515 return ISD::UMULFIX;
5517 llvm_unreachable("Unhandled fixed point intrinsic");
5521 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5522 const char *FunctionName) {
5523 assert(FunctionName && "FunctionName must not be nullptr");
5524 SDValue Callee = DAG.getExternalSymbol(
5526 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5527 LowerCallTo(&I, Callee, I.isTailCall());
5530 /// Lower the call to the specified intrinsic function.
5531 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5532 unsigned Intrinsic) {
5533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5534 SDLoc sdl = getCurSDLoc();
5535 DebugLoc dl = getCurDebugLoc();
5538 switch (Intrinsic) {
5540 // By default, turn this into a target intrinsic node.
5541 visitTargetIntrinsic(I, Intrinsic);
5543 case Intrinsic::vastart: visitVAStart(I); return;
5544 case Intrinsic::vaend: visitVAEnd(I); return;
5545 case Intrinsic::vacopy: visitVACopy(I); return;
5546 case Intrinsic::returnaddress:
5547 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5548 TLI.getPointerTy(DAG.getDataLayout()),
5549 getValue(I.getArgOperand(0))));
5551 case Intrinsic::addressofreturnaddress:
5552 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5553 TLI.getPointerTy(DAG.getDataLayout())));
5555 case Intrinsic::sponentry:
5556 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5557 TLI.getPointerTy(DAG.getDataLayout())));
5559 case Intrinsic::frameaddress:
5560 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5561 TLI.getPointerTy(DAG.getDataLayout()),
5562 getValue(I.getArgOperand(0))));
5564 case Intrinsic::read_register: {
5565 Value *Reg = I.getArgOperand(0);
5566 SDValue Chain = getRoot();
5568 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5569 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5570 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5571 DAG.getVTList(VT, MVT::Other), Chain, RegName);
5573 DAG.setRoot(Res.getValue(1));
5576 case Intrinsic::write_register: {
5577 Value *Reg = I.getArgOperand(0);
5578 Value *RegValue = I.getArgOperand(1);
5579 SDValue Chain = getRoot();
5581 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5582 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5583 RegName, getValue(RegValue)));
5586 case Intrinsic::setjmp:
5587 lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
5589 case Intrinsic::longjmp:
5590 lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
5592 case Intrinsic::memcpy: {
5593 const auto &MCI = cast<MemCpyInst>(I);
5594 SDValue Op1 = getValue(I.getArgOperand(0));
5595 SDValue Op2 = getValue(I.getArgOperand(1));
5596 SDValue Op3 = getValue(I.getArgOperand(2));
5597 // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5598 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5599 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5600 unsigned Align = MinAlign(DstAlign, SrcAlign);
5601 bool isVol = MCI.isVolatile();
5602 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5603 // FIXME: Support passing different dest/src alignments to the memcpy DAG
5605 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5607 MachinePointerInfo(I.getArgOperand(0)),
5608 MachinePointerInfo(I.getArgOperand(1)));
5609 updateDAGForMaybeTailCall(MC);
5612 case Intrinsic::memset: {
5613 const auto &MSI = cast<MemSetInst>(I);
5614 SDValue Op1 = getValue(I.getArgOperand(0));
5615 SDValue Op2 = getValue(I.getArgOperand(1));
5616 SDValue Op3 = getValue(I.getArgOperand(2));
5617 // @llvm.memset defines 0 and 1 to both mean no alignment.
5618 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5619 bool isVol = MSI.isVolatile();
5620 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5621 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5622 isTC, MachinePointerInfo(I.getArgOperand(0)));
5623 updateDAGForMaybeTailCall(MS);
5626 case Intrinsic::memmove: {
5627 const auto &MMI = cast<MemMoveInst>(I);
5628 SDValue Op1 = getValue(I.getArgOperand(0));
5629 SDValue Op2 = getValue(I.getArgOperand(1));
5630 SDValue Op3 = getValue(I.getArgOperand(2));
5631 // @llvm.memmove defines 0 and 1 to both mean no alignment.
5632 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5633 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5634 unsigned Align = MinAlign(DstAlign, SrcAlign);
5635 bool isVol = MMI.isVolatile();
5636 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5637 // FIXME: Support passing different dest/src alignments to the memmove DAG
5639 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5640 isTC, MachinePointerInfo(I.getArgOperand(0)),
5641 MachinePointerInfo(I.getArgOperand(1)));
5642 updateDAGForMaybeTailCall(MM);
5645 case Intrinsic::memcpy_element_unordered_atomic: {
5646 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5647 SDValue Dst = getValue(MI.getRawDest());
5648 SDValue Src = getValue(MI.getRawSource());
5649 SDValue Length = getValue(MI.getLength());
5651 unsigned DstAlign = MI.getDestAlignment();
5652 unsigned SrcAlign = MI.getSourceAlignment();
5653 Type *LengthTy = MI.getLength()->getType();
5654 unsigned ElemSz = MI.getElementSizeInBytes();
5655 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5656 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5657 SrcAlign, Length, LengthTy, ElemSz, isTC,
5658 MachinePointerInfo(MI.getRawDest()),
5659 MachinePointerInfo(MI.getRawSource()));
5660 updateDAGForMaybeTailCall(MC);
5663 case Intrinsic::memmove_element_unordered_atomic: {
5664 auto &MI = cast<AtomicMemMoveInst>(I);
5665 SDValue Dst = getValue(MI.getRawDest());
5666 SDValue Src = getValue(MI.getRawSource());
5667 SDValue Length = getValue(MI.getLength());
5669 unsigned DstAlign = MI.getDestAlignment();
5670 unsigned SrcAlign = MI.getSourceAlignment();
5671 Type *LengthTy = MI.getLength()->getType();
5672 unsigned ElemSz = MI.getElementSizeInBytes();
5673 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5674 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5675 SrcAlign, Length, LengthTy, ElemSz, isTC,
5676 MachinePointerInfo(MI.getRawDest()),
5677 MachinePointerInfo(MI.getRawSource()));
5678 updateDAGForMaybeTailCall(MC);
5681 case Intrinsic::memset_element_unordered_atomic: {
5682 auto &MI = cast<AtomicMemSetInst>(I);
5683 SDValue Dst = getValue(MI.getRawDest());
5684 SDValue Val = getValue(MI.getValue());
5685 SDValue Length = getValue(MI.getLength());
5687 unsigned DstAlign = MI.getDestAlignment();
5688 Type *LengthTy = MI.getLength()->getType();
5689 unsigned ElemSz = MI.getElementSizeInBytes();
5690 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5691 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5692 LengthTy, ElemSz, isTC,
5693 MachinePointerInfo(MI.getRawDest()));
5694 updateDAGForMaybeTailCall(MC);
5697 case Intrinsic::dbg_addr:
5698 case Intrinsic::dbg_declare: {
5699 const auto &DI = cast<DbgVariableIntrinsic>(I);
5700 DILocalVariable *Variable = DI.getVariable();
5701 DIExpression *Expression = DI.getExpression();
5702 dropDanglingDebugInfo(Variable, Expression);
5703 assert(Variable && "Missing variable");
5705 // Check if address has undef value.
5706 const Value *Address = DI.getVariableLocation();
5707 if (!Address || isa<UndefValue>(Address) ||
5708 (Address->use_empty() && !isa<Argument>(Address))) {
5709 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5713 bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5715 // Check if this variable can be described by a frame index, typically
5716 // either as a static alloca or a byval parameter.
5717 int FI = std::numeric_limits<int>::max();
5718 if (const auto *AI =
5719 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5720 if (AI->isStaticAlloca()) {
5721 auto I = FuncInfo.StaticAllocaMap.find(AI);
5722 if (I != FuncInfo.StaticAllocaMap.end())
5725 } else if (const auto *Arg = dyn_cast<Argument>(
5726 Address->stripInBoundsConstantOffsets())) {
5727 FI = FuncInfo.getArgumentFrameIndex(Arg);
5730 // llvm.dbg.addr is control dependent and always generates indirect
5731 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5732 // the MachineFunction variable table.
5733 if (FI != std::numeric_limits<int>::max()) {
5734 if (Intrinsic == Intrinsic::dbg_addr) {
5735 SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5736 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5737 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5742 SDValue &N = NodeMap[Address];
5743 if (!N.getNode() && isa<Argument>(Address))
5744 // Check unused arguments map.
5745 N = UnusedArgNodeMap[Address];
5748 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5749 Address = BCI->getOperand(0);
5750 // Parameters are handled specially.
5751 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5752 if (isParameter && FINode) {
5753 // Byval parameter. We have a frame index at this point.
5755 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5756 /*IsIndirect*/ true, dl, SDNodeOrder);
5757 } else if (isa<Argument>(Address)) {
5758 // Address is an argument, so try to emit its dbg value using
5759 // virtual register info from the FuncInfo.ValueMap.
5760 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5763 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5764 true, dl, SDNodeOrder);
5766 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5768 // If Address is an argument then try to emit its dbg value using
5769 // virtual register info from the FuncInfo.ValueMap.
5770 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5772 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5777 case Intrinsic::dbg_label: {
5778 const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5779 DILabel *Label = DI.getLabel();
5780 assert(Label && "Missing label");
5783 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5784 DAG.AddDbgLabel(SDV);
5787 case Intrinsic::dbg_value: {
5788 const DbgValueInst &DI = cast<DbgValueInst>(I);
5789 assert(DI.getVariable() && "Missing variable");
5791 DILocalVariable *Variable = DI.getVariable();
5792 DIExpression *Expression = DI.getExpression();
5793 dropDanglingDebugInfo(Variable, Expression);
5794 const Value *V = DI.getValue();
5798 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5802 // TODO: Dangling debug info will eventually either be resolved or produce
5803 // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5804 // between the original dbg.value location and its resolved DBG_VALUE, which
5805 // we should ideally fill with an extra Undef DBG_VALUE.
5807 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5811 case Intrinsic::eh_typeid_for: {
5812 // Find the type id for the given typeinfo.
5813 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5814 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5815 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5820 case Intrinsic::eh_return_i32:
5821 case Intrinsic::eh_return_i64:
5822 DAG.getMachineFunction().setCallsEHReturn(true);
5823 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5826 getValue(I.getArgOperand(0)),
5827 getValue(I.getArgOperand(1))));
5829 case Intrinsic::eh_unwind_init:
5830 DAG.getMachineFunction().setCallsUnwindInit(true);
5832 case Intrinsic::eh_dwarf_cfa:
5833 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5834 TLI.getPointerTy(DAG.getDataLayout()),
5835 getValue(I.getArgOperand(0))));
5837 case Intrinsic::eh_sjlj_callsite: {
5838 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5839 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5840 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5841 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5843 MMI.setCurrentCallSite(CI->getZExtValue());
5846 case Intrinsic::eh_sjlj_functioncontext: {
5847 // Get and store the index of the function context.
5848 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5850 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5851 int FI = FuncInfo.StaticAllocaMap[FnCtx];
5852 MFI.setFunctionContextIndex(FI);
5855 case Intrinsic::eh_sjlj_setjmp: {
5858 Ops[1] = getValue(I.getArgOperand(0));
5859 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5860 DAG.getVTList(MVT::i32, MVT::Other), Ops);
5861 setValue(&I, Op.getValue(0));
5862 DAG.setRoot(Op.getValue(1));
5865 case Intrinsic::eh_sjlj_longjmp:
5866 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5867 getRoot(), getValue(I.getArgOperand(0))));
5869 case Intrinsic::eh_sjlj_setup_dispatch:
5870 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5873 case Intrinsic::masked_gather:
5874 visitMaskedGather(I);
5876 case Intrinsic::masked_load:
5879 case Intrinsic::masked_scatter:
5880 visitMaskedScatter(I);
5882 case Intrinsic::masked_store:
5883 visitMaskedStore(I);
5885 case Intrinsic::masked_expandload:
5886 visitMaskedLoad(I, true /* IsExpanding */);
5888 case Intrinsic::masked_compressstore:
5889 visitMaskedStore(I, true /* IsCompressing */);
5891 case Intrinsic::x86_mmx_pslli_w:
5892 case Intrinsic::x86_mmx_pslli_d:
5893 case Intrinsic::x86_mmx_pslli_q:
5894 case Intrinsic::x86_mmx_psrli_w:
5895 case Intrinsic::x86_mmx_psrli_d:
5896 case Intrinsic::x86_mmx_psrli_q:
5897 case Intrinsic::x86_mmx_psrai_w:
5898 case Intrinsic::x86_mmx_psrai_d: {
5899 SDValue ShAmt = getValue(I.getArgOperand(1));
5900 if (isa<ConstantSDNode>(ShAmt)) {
5901 visitTargetIntrinsic(I, Intrinsic);
5904 unsigned NewIntrinsic = 0;
5905 EVT ShAmtVT = MVT::v2i32;
5906 switch (Intrinsic) {
5907 case Intrinsic::x86_mmx_pslli_w:
5908 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5910 case Intrinsic::x86_mmx_pslli_d:
5911 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5913 case Intrinsic::x86_mmx_pslli_q:
5914 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5916 case Intrinsic::x86_mmx_psrli_w:
5917 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5919 case Intrinsic::x86_mmx_psrli_d:
5920 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5922 case Intrinsic::x86_mmx_psrli_q:
5923 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5925 case Intrinsic::x86_mmx_psrai_w:
5926 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5928 case Intrinsic::x86_mmx_psrai_d:
5929 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5931 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5934 // The vector shift intrinsics with scalars uses 32b shift amounts but
5935 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5937 // We must do this early because v2i32 is not a legal type.
5940 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5941 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5942 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5943 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5944 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5945 DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5946 getValue(I.getArgOperand(0)), ShAmt);
5950 case Intrinsic::powi:
5951 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5952 getValue(I.getArgOperand(1)), DAG));
5954 case Intrinsic::log:
5955 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5957 case Intrinsic::log2:
5958 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5960 case Intrinsic::log10:
5961 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5963 case Intrinsic::exp:
5964 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5966 case Intrinsic::exp2:
5967 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5969 case Intrinsic::pow:
5970 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5971 getValue(I.getArgOperand(1)), DAG, TLI));
5973 case Intrinsic::sqrt:
5974 case Intrinsic::fabs:
5975 case Intrinsic::sin:
5976 case Intrinsic::cos:
5977 case Intrinsic::floor:
5978 case Intrinsic::ceil:
5979 case Intrinsic::trunc:
5980 case Intrinsic::rint:
5981 case Intrinsic::nearbyint:
5982 case Intrinsic::round:
5983 case Intrinsic::canonicalize: {
5985 switch (Intrinsic) {
5986 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5987 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5988 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5989 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5990 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5991 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5992 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5993 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5994 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5995 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5996 case Intrinsic::round: Opcode = ISD::FROUND; break;
5997 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6000 setValue(&I, DAG.getNode(Opcode, sdl,
6001 getValue(I.getArgOperand(0)).getValueType(),
6002 getValue(I.getArgOperand(0))));
6005 case Intrinsic::lround:
6006 case Intrinsic::llround:
6007 case Intrinsic::lrint:
6008 case Intrinsic::llrint: {
6010 switch (Intrinsic) {
6011 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6012 case Intrinsic::lround: Opcode = ISD::LROUND; break;
6013 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6014 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
6015 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
6018 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6019 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6020 getValue(I.getArgOperand(0))));
6023 case Intrinsic::minnum:
6024 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6025 getValue(I.getArgOperand(0)).getValueType(),
6026 getValue(I.getArgOperand(0)),
6027 getValue(I.getArgOperand(1))));
6029 case Intrinsic::maxnum:
6030 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6031 getValue(I.getArgOperand(0)).getValueType(),
6032 getValue(I.getArgOperand(0)),
6033 getValue(I.getArgOperand(1))));
6035 case Intrinsic::minimum:
6036 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6037 getValue(I.getArgOperand(0)).getValueType(),
6038 getValue(I.getArgOperand(0)),
6039 getValue(I.getArgOperand(1))));
6041 case Intrinsic::maximum:
6042 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6043 getValue(I.getArgOperand(0)).getValueType(),
6044 getValue(I.getArgOperand(0)),
6045 getValue(I.getArgOperand(1))));
6047 case Intrinsic::copysign:
6048 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6049 getValue(I.getArgOperand(0)).getValueType(),
6050 getValue(I.getArgOperand(0)),
6051 getValue(I.getArgOperand(1))));
6053 case Intrinsic::fma:
6054 setValue(&I, DAG.getNode(ISD::FMA, sdl,
6055 getValue(I.getArgOperand(0)).getValueType(),
6056 getValue(I.getArgOperand(0)),
6057 getValue(I.getArgOperand(1)),
6058 getValue(I.getArgOperand(2))));
6060 case Intrinsic::experimental_constrained_fadd:
6061 case Intrinsic::experimental_constrained_fsub:
6062 case Intrinsic::experimental_constrained_fmul:
6063 case Intrinsic::experimental_constrained_fdiv:
6064 case Intrinsic::experimental_constrained_frem:
6065 case Intrinsic::experimental_constrained_fma:
6066 case Intrinsic::experimental_constrained_fptrunc:
6067 case Intrinsic::experimental_constrained_fpext:
6068 case Intrinsic::experimental_constrained_sqrt:
6069 case Intrinsic::experimental_constrained_pow:
6070 case Intrinsic::experimental_constrained_powi:
6071 case Intrinsic::experimental_constrained_sin:
6072 case Intrinsic::experimental_constrained_cos:
6073 case Intrinsic::experimental_constrained_exp:
6074 case Intrinsic::experimental_constrained_exp2:
6075 case Intrinsic::experimental_constrained_log:
6076 case Intrinsic::experimental_constrained_log10:
6077 case Intrinsic::experimental_constrained_log2:
6078 case Intrinsic::experimental_constrained_rint:
6079 case Intrinsic::experimental_constrained_nearbyint:
6080 case Intrinsic::experimental_constrained_maxnum:
6081 case Intrinsic::experimental_constrained_minnum:
6082 case Intrinsic::experimental_constrained_ceil:
6083 case Intrinsic::experimental_constrained_floor:
6084 case Intrinsic::experimental_constrained_round:
6085 case Intrinsic::experimental_constrained_trunc:
6086 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6088 case Intrinsic::fmuladd: {
6089 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6090 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6091 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
6092 setValue(&I, DAG.getNode(ISD::FMA, sdl,
6093 getValue(I.getArgOperand(0)).getValueType(),
6094 getValue(I.getArgOperand(0)),
6095 getValue(I.getArgOperand(1)),
6096 getValue(I.getArgOperand(2))));
6098 // TODO: Intrinsic calls should have fast-math-flags.
6099 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6100 getValue(I.getArgOperand(0)).getValueType(),
6101 getValue(I.getArgOperand(0)),
6102 getValue(I.getArgOperand(1)));
6103 SDValue Add = DAG.getNode(ISD::FADD, sdl,
6104 getValue(I.getArgOperand(0)).getValueType(),
6106 getValue(I.getArgOperand(2)));
6111 case Intrinsic::convert_to_fp16:
6112 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6113 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6114 getValue(I.getArgOperand(0)),
6115 DAG.getTargetConstant(0, sdl,
6118 case Intrinsic::convert_from_fp16:
6119 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6120 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6121 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6122 getValue(I.getArgOperand(0)))));
6124 case Intrinsic::pcmarker: {
6125 SDValue Tmp = getValue(I.getArgOperand(0));
6126 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6129 case Intrinsic::readcyclecounter: {
6130 SDValue Op = getRoot();
6131 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6132 DAG.getVTList(MVT::i64, MVT::Other), Op);
6134 DAG.setRoot(Res.getValue(1));
6137 case Intrinsic::bitreverse:
6138 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6139 getValue(I.getArgOperand(0)).getValueType(),
6140 getValue(I.getArgOperand(0))));
6142 case Intrinsic::bswap:
6143 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6144 getValue(I.getArgOperand(0)).getValueType(),
6145 getValue(I.getArgOperand(0))));
6147 case Intrinsic::cttz: {
6148 SDValue Arg = getValue(I.getArgOperand(0));
6149 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6150 EVT Ty = Arg.getValueType();
6151 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6155 case Intrinsic::ctlz: {
6156 SDValue Arg = getValue(I.getArgOperand(0));
6157 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6158 EVT Ty = Arg.getValueType();
6159 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6163 case Intrinsic::ctpop: {
6164 SDValue Arg = getValue(I.getArgOperand(0));
6165 EVT Ty = Arg.getValueType();
6166 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6169 case Intrinsic::fshl:
6170 case Intrinsic::fshr: {
6171 bool IsFSHL = Intrinsic == Intrinsic::fshl;
6172 SDValue X = getValue(I.getArgOperand(0));
6173 SDValue Y = getValue(I.getArgOperand(1));
6174 SDValue Z = getValue(I.getArgOperand(2));
6175 EVT VT = X.getValueType();
6176 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6177 SDValue Zero = DAG.getConstant(0, sdl, VT);
6178 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6180 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6181 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6182 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6186 // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6187 // avoid the select that is necessary in the general case to filter out
6188 // the 0-shift possibility that leads to UB.
6189 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6190 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6191 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6192 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6196 // Some targets only rotate one way. Try the opposite direction.
6197 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6198 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6199 // Negate the shift amount because it is safe to ignore the high bits.
6200 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6201 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6205 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6206 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6207 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6208 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6209 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6210 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6211 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6215 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6216 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6217 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6218 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6219 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6220 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6222 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6223 // and that is undefined. We must compare and select to avoid UB.
6226 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6228 // For fshl, 0-shift returns the 1st arg (X).
6229 // For fshr, 0-shift returns the 2nd arg (Y).
6230 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6231 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6234 case Intrinsic::sadd_sat: {
6235 SDValue Op1 = getValue(I.getArgOperand(0));
6236 SDValue Op2 = getValue(I.getArgOperand(1));
6237 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6240 case Intrinsic::uadd_sat: {
6241 SDValue Op1 = getValue(I.getArgOperand(0));
6242 SDValue Op2 = getValue(I.getArgOperand(1));
6243 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6246 case Intrinsic::ssub_sat: {
6247 SDValue Op1 = getValue(I.getArgOperand(0));
6248 SDValue Op2 = getValue(I.getArgOperand(1));
6249 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6252 case Intrinsic::usub_sat: {
6253 SDValue Op1 = getValue(I.getArgOperand(0));
6254 SDValue Op2 = getValue(I.getArgOperand(1));
6255 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6258 case Intrinsic::smul_fix:
6259 case Intrinsic::umul_fix: {
6260 SDValue Op1 = getValue(I.getArgOperand(0));
6261 SDValue Op2 = getValue(I.getArgOperand(1));
6262 SDValue Op3 = getValue(I.getArgOperand(2));
6263 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6264 Op1.getValueType(), Op1, Op2, Op3));
6267 case Intrinsic::smul_fix_sat: {
6268 SDValue Op1 = getValue(I.getArgOperand(0));
6269 SDValue Op2 = getValue(I.getArgOperand(1));
6270 SDValue Op3 = getValue(I.getArgOperand(2));
6271 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6275 case Intrinsic::stacksave: {
6276 SDValue Op = getRoot();
6278 ISD::STACKSAVE, sdl,
6279 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6281 DAG.setRoot(Res.getValue(1));
6284 case Intrinsic::stackrestore:
6285 Res = getValue(I.getArgOperand(0));
6286 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6288 case Intrinsic::get_dynamic_area_offset: {
6289 SDValue Op = getRoot();
6290 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6291 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6292 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6294 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6295 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6297 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6303 case Intrinsic::stackguard: {
6304 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6305 MachineFunction &MF = DAG.getMachineFunction();
6306 const Module &M = *MF.getFunction().getParent();
6307 SDValue Chain = getRoot();
6308 if (TLI.useLoadStackGuardNode()) {
6309 Res = getLoadStackGuard(DAG, sdl, Chain);
6311 const Value *Global = TLI.getSDagStackGuard(M);
6312 unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6313 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6314 MachinePointerInfo(Global, 0), Align,
6315 MachineMemOperand::MOVolatile);
6317 if (TLI.useStackGuardXorFP())
6318 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6323 case Intrinsic::stackprotector: {
6324 // Emit code into the DAG to store the stack guard onto the stack.
6325 MachineFunction &MF = DAG.getMachineFunction();
6326 MachineFrameInfo &MFI = MF.getFrameInfo();
6327 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6328 SDValue Src, Chain = getRoot();
6330 if (TLI.useLoadStackGuardNode())
6331 Src = getLoadStackGuard(DAG, sdl, Chain);
6333 Src = getValue(I.getArgOperand(0)); // The guard's value.
6335 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6337 int FI = FuncInfo.StaticAllocaMap[Slot];
6338 MFI.setStackProtectorIndex(FI);
6340 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6342 // Store the stack protector onto the stack.
6343 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6344 DAG.getMachineFunction(), FI),
6345 /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6350 case Intrinsic::objectsize: {
6351 // If we don't know by now, we're never going to know.
6352 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6354 assert(CI && "Non-constant type in __builtin_object_size?");
6356 SDValue Arg = getValue(I.getCalledValue());
6357 EVT Ty = Arg.getValueType();
6360 Res = DAG.getConstant(-1ULL, sdl, Ty);
6362 Res = DAG.getConstant(0, sdl, Ty);
6368 case Intrinsic::is_constant:
6369 // If this wasn't constant-folded away by now, then it's not a
6371 setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6374 case Intrinsic::annotation:
6375 case Intrinsic::ptr_annotation:
6376 case Intrinsic::launder_invariant_group:
6377 case Intrinsic::strip_invariant_group:
6378 // Drop the intrinsic, but forward the value
6379 setValue(&I, getValue(I.getOperand(0)));
6381 case Intrinsic::assume:
6382 case Intrinsic::var_annotation:
6383 case Intrinsic::sideeffect:
6384 // Discard annotate attributes, assumptions, and artificial side-effects.
6387 case Intrinsic::codeview_annotation: {
6388 // Emit a label associated with this metadata.
6389 MachineFunction &MF = DAG.getMachineFunction();
6391 MF.getMMI().getContext().createTempSymbol("annotation", true);
6392 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6393 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6394 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6399 case Intrinsic::init_trampoline: {
6400 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6404 Ops[1] = getValue(I.getArgOperand(0));
6405 Ops[2] = getValue(I.getArgOperand(1));
6406 Ops[3] = getValue(I.getArgOperand(2));
6407 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6408 Ops[5] = DAG.getSrcValue(F);
6410 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6415 case Intrinsic::adjust_trampoline:
6416 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6417 TLI.getPointerTy(DAG.getDataLayout()),
6418 getValue(I.getArgOperand(0))));
6420 case Intrinsic::gcroot: {
6421 assert(DAG.getMachineFunction().getFunction().hasGC() &&
6422 "only valid in functions with gc specified, enforced by Verifier");
6423 assert(GFI && "implied by previous");
6424 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6425 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6427 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6428 GFI->addStackRoot(FI->getIndex(), TypeMap);
6431 case Intrinsic::gcread:
6432 case Intrinsic::gcwrite:
6433 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6434 case Intrinsic::flt_rounds:
6435 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6438 case Intrinsic::expect:
6439 // Just replace __builtin_expect(exp, c) with EXP.
6440 setValue(&I, getValue(I.getArgOperand(0)));
6443 case Intrinsic::debugtrap:
6444 case Intrinsic::trap: {
6445 StringRef TrapFuncName =
6447 .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6448 .getValueAsString();
6449 if (TrapFuncName.empty()) {
6450 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6451 ISD::TRAP : ISD::DEBUGTRAP;
6452 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6455 TargetLowering::ArgListTy Args;
6457 TargetLowering::CallLoweringInfo CLI(DAG);
6458 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6459 CallingConv::C, I.getType(),
6460 DAG.getExternalSymbol(TrapFuncName.data(),
6461 TLI.getPointerTy(DAG.getDataLayout())),
6464 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6465 DAG.setRoot(Result.second);
6469 case Intrinsic::uadd_with_overflow:
6470 case Intrinsic::sadd_with_overflow:
6471 case Intrinsic::usub_with_overflow:
6472 case Intrinsic::ssub_with_overflow:
6473 case Intrinsic::umul_with_overflow:
6474 case Intrinsic::smul_with_overflow: {
6476 switch (Intrinsic) {
6477 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6478 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6479 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6480 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6481 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6482 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6483 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6485 SDValue Op1 = getValue(I.getArgOperand(0));
6486 SDValue Op2 = getValue(I.getArgOperand(1));
6488 EVT ResultVT = Op1.getValueType();
6489 EVT OverflowVT = MVT::i1;
6490 if (ResultVT.isVector())
6491 OverflowVT = EVT::getVectorVT(
6492 *Context, OverflowVT, ResultVT.getVectorNumElements());
6494 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6495 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6498 case Intrinsic::prefetch: {
6500 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6501 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6502 Ops[0] = DAG.getRoot();
6503 Ops[1] = getValue(I.getArgOperand(0));
6504 Ops[2] = getValue(I.getArgOperand(1));
6505 Ops[3] = getValue(I.getArgOperand(2));
6506 Ops[4] = getValue(I.getArgOperand(3));
6507 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6508 DAG.getVTList(MVT::Other), Ops,
6509 EVT::getIntegerVT(*Context, 8),
6510 MachinePointerInfo(I.getArgOperand(0)),
6514 // Chain the prefetch in parallell with any pending loads, to stay out of
6515 // the way of later optimizations.
6516 PendingLoads.push_back(Result);
6518 DAG.setRoot(Result);
6521 case Intrinsic::lifetime_start:
6522 case Intrinsic::lifetime_end: {
6523 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6524 // Stack coloring is not enabled in O0, discard region information.
6525 if (TM.getOptLevel() == CodeGenOpt::None)
6528 const int64_t ObjectSize =
6529 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6530 Value *const ObjectPtr = I.getArgOperand(1);
6531 SmallVector<const Value *, 4> Allocas;
6532 GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6534 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6535 E = Allocas.end(); Object != E; ++Object) {
6536 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6538 // Could not find an Alloca.
6539 if (!LifetimeObject)
6542 // First check that the Alloca is static, otherwise it won't have a
6543 // valid frame index.
6544 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6545 if (SI == FuncInfo.StaticAllocaMap.end())
6548 const int FrameIndex = SI->second;
6550 if (GetPointerBaseWithConstantOffset(
6551 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6552 Offset = -1; // Cannot determine offset from alloca to lifetime object.
6553 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6559 case Intrinsic::invariant_start:
6560 // Discard region information.
6561 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6563 case Intrinsic::invariant_end:
6564 // Discard region information.
6566 case Intrinsic::clear_cache:
6567 /// FunctionName may be null.
6568 if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6569 lowerCallToExternalSymbol(I, FunctionName);
6571 case Intrinsic::donothing:
6574 case Intrinsic::experimental_stackmap:
6577 case Intrinsic::experimental_patchpoint_void:
6578 case Intrinsic::experimental_patchpoint_i64:
6579 visitPatchpoint(&I);
6581 case Intrinsic::experimental_gc_statepoint:
6582 LowerStatepoint(ImmutableStatepoint(&I));
6584 case Intrinsic::experimental_gc_result:
6585 visitGCResult(cast<GCResultInst>(I));
6587 case Intrinsic::experimental_gc_relocate:
6588 visitGCRelocate(cast<GCRelocateInst>(I));
6590 case Intrinsic::instrprof_increment:
6591 llvm_unreachable("instrprof failed to lower an increment");
6592 case Intrinsic::instrprof_value_profile:
6593 llvm_unreachable("instrprof failed to lower a value profiling call");
6594 case Intrinsic::localescape: {
6595 MachineFunction &MF = DAG.getMachineFunction();
6596 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6598 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6599 // is the same on all targets.
6600 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6601 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6602 if (isa<ConstantPointerNull>(Arg))
6603 continue; // Skip null pointers. They represent a hole in index space.
6604 AllocaInst *Slot = cast<AllocaInst>(Arg);
6605 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6606 "can only escape static allocas");
6607 int FI = FuncInfo.StaticAllocaMap[Slot];
6608 MCSymbol *FrameAllocSym =
6609 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6610 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6611 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6612 TII->get(TargetOpcode::LOCAL_ESCAPE))
6613 .addSym(FrameAllocSym)
6620 case Intrinsic::localrecover: {
6621 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6622 MachineFunction &MF = DAG.getMachineFunction();
6623 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6625 // Get the symbol that defines the frame offset.
6626 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6627 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6629 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6630 MCSymbol *FrameAllocSym =
6631 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6632 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6634 // Create a MCSymbol for the label to avoid any target lowering
6635 // that would make this PC relative.
6636 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6638 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6640 // Add the offset to the FP.
6641 Value *FP = I.getArgOperand(1);
6642 SDValue FPVal = getValue(FP);
6643 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6649 case Intrinsic::eh_exceptionpointer:
6650 case Intrinsic::eh_exceptioncode: {
6651 // Get the exception pointer vreg, copy from it, and resize it to fit.
6652 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6653 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6654 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6655 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6657 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6658 if (Intrinsic == Intrinsic::eh_exceptioncode)
6659 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6663 case Intrinsic::xray_customevent: {
6664 // Here we want to make sure that the intrinsic behaves as if it has a
6665 // specific calling convention, and only for x86_64.
6666 // FIXME: Support other platforms later.
6667 const auto &Triple = DAG.getTarget().getTargetTriple();
6668 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6671 SDLoc DL = getCurSDLoc();
6672 SmallVector<SDValue, 8> Ops;
6674 // We want to say that we always want the arguments in registers.
6675 SDValue LogEntryVal = getValue(I.getArgOperand(0));
6676 SDValue StrSizeVal = getValue(I.getArgOperand(1));
6677 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6678 SDValue Chain = getRoot();
6679 Ops.push_back(LogEntryVal);
6680 Ops.push_back(StrSizeVal);
6681 Ops.push_back(Chain);
6683 // We need to enforce the calling convention for the callsite, so that
6684 // argument ordering is enforced correctly, and that register allocation can
6685 // see that some registers may be assumed clobbered and have to preserve
6686 // them across calls to the intrinsic.
6687 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6689 SDValue patchableNode = SDValue(MN, 0);
6690 DAG.setRoot(patchableNode);
6691 setValue(&I, patchableNode);
6694 case Intrinsic::xray_typedevent: {
6695 // Here we want to make sure that the intrinsic behaves as if it has a
6696 // specific calling convention, and only for x86_64.
6697 // FIXME: Support other platforms later.
6698 const auto &Triple = DAG.getTarget().getTargetTriple();
6699 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6702 SDLoc DL = getCurSDLoc();
6703 SmallVector<SDValue, 8> Ops;
6705 // We want to say that we always want the arguments in registers.
6706 // It's unclear to me how manipulating the selection DAG here forces callers
6707 // to provide arguments in registers instead of on the stack.
6708 SDValue LogTypeId = getValue(I.getArgOperand(0));
6709 SDValue LogEntryVal = getValue(I.getArgOperand(1));
6710 SDValue StrSizeVal = getValue(I.getArgOperand(2));
6711 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6712 SDValue Chain = getRoot();
6713 Ops.push_back(LogTypeId);
6714 Ops.push_back(LogEntryVal);
6715 Ops.push_back(StrSizeVal);
6716 Ops.push_back(Chain);
6718 // We need to enforce the calling convention for the callsite, so that
6719 // argument ordering is enforced correctly, and that register allocation can
6720 // see that some registers may be assumed clobbered and have to preserve
6721 // them across calls to the intrinsic.
6722 MachineSDNode *MN = DAG.getMachineNode(
6723 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6724 SDValue patchableNode = SDValue(MN, 0);
6725 DAG.setRoot(patchableNode);
6726 setValue(&I, patchableNode);
6729 case Intrinsic::experimental_deoptimize:
6730 LowerDeoptimizeCall(&I);
6733 case Intrinsic::experimental_vector_reduce_v2_fadd:
6734 case Intrinsic::experimental_vector_reduce_v2_fmul:
6735 case Intrinsic::experimental_vector_reduce_add:
6736 case Intrinsic::experimental_vector_reduce_mul:
6737 case Intrinsic::experimental_vector_reduce_and:
6738 case Intrinsic::experimental_vector_reduce_or:
6739 case Intrinsic::experimental_vector_reduce_xor:
6740 case Intrinsic::experimental_vector_reduce_smax:
6741 case Intrinsic::experimental_vector_reduce_smin:
6742 case Intrinsic::experimental_vector_reduce_umax:
6743 case Intrinsic::experimental_vector_reduce_umin:
6744 case Intrinsic::experimental_vector_reduce_fmax:
6745 case Intrinsic::experimental_vector_reduce_fmin:
6746 visitVectorReduce(I, Intrinsic);
6749 case Intrinsic::icall_branch_funnel: {
6750 SmallVector<SDValue, 16> Ops;
6751 Ops.push_back(getValue(I.getArgOperand(0)));
6754 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6755 I.getArgOperand(1), Offset, DAG.getDataLayout()));
6758 "llvm.icall.branch.funnel operand must be a GlobalValue");
6759 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6761 struct BranchFunnelTarget {
6765 SmallVector<BranchFunnelTarget, 8> Targets;
6767 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6768 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6769 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6770 if (ElemBase != Base)
6771 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6772 "to the same GlobalValue");
6774 SDValue Val = getValue(I.getArgOperand(Op + 1));
6775 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6778 "llvm.icall.branch.funnel operand must be a GlobalValue");
6779 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6780 GA->getGlobal(), getCurSDLoc(),
6781 Val.getValueType(), GA->getOffset())});
6784 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6785 return T1.Offset < T2.Offset;
6788 for (auto &T : Targets) {
6789 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6790 Ops.push_back(T.Target);
6793 Ops.push_back(DAG.getRoot()); // Chain
6794 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6795 getCurSDLoc(), MVT::Other, Ops),
6803 case Intrinsic::wasm_landingpad_index:
6804 // Information this intrinsic contained has been transferred to
6805 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6809 case Intrinsic::aarch64_settag:
6810 case Intrinsic::aarch64_settag_zero: {
6811 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6812 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6813 SDValue Val = TSI.EmitTargetCodeForSetTag(
6814 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6815 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6824 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6825 const ConstrainedFPIntrinsic &FPI) {
6826 SDLoc sdl = getCurSDLoc();
6828 switch (FPI.getIntrinsicID()) {
6829 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6830 case Intrinsic::experimental_constrained_fadd:
6831 Opcode = ISD::STRICT_FADD;
6833 case Intrinsic::experimental_constrained_fsub:
6834 Opcode = ISD::STRICT_FSUB;
6836 case Intrinsic::experimental_constrained_fmul:
6837 Opcode = ISD::STRICT_FMUL;
6839 case Intrinsic::experimental_constrained_fdiv:
6840 Opcode = ISD::STRICT_FDIV;
6842 case Intrinsic::experimental_constrained_frem:
6843 Opcode = ISD::STRICT_FREM;
6845 case Intrinsic::experimental_constrained_fma:
6846 Opcode = ISD::STRICT_FMA;
6848 case Intrinsic::experimental_constrained_fptrunc:
6849 Opcode = ISD::STRICT_FP_ROUND;
6851 case Intrinsic::experimental_constrained_fpext:
6852 Opcode = ISD::STRICT_FP_EXTEND;
6854 case Intrinsic::experimental_constrained_sqrt:
6855 Opcode = ISD::STRICT_FSQRT;
6857 case Intrinsic::experimental_constrained_pow:
6858 Opcode = ISD::STRICT_FPOW;
6860 case Intrinsic::experimental_constrained_powi:
6861 Opcode = ISD::STRICT_FPOWI;
6863 case Intrinsic::experimental_constrained_sin:
6864 Opcode = ISD::STRICT_FSIN;
6866 case Intrinsic::experimental_constrained_cos:
6867 Opcode = ISD::STRICT_FCOS;
6869 case Intrinsic::experimental_constrained_exp:
6870 Opcode = ISD::STRICT_FEXP;
6872 case Intrinsic::experimental_constrained_exp2:
6873 Opcode = ISD::STRICT_FEXP2;
6875 case Intrinsic::experimental_constrained_log:
6876 Opcode = ISD::STRICT_FLOG;
6878 case Intrinsic::experimental_constrained_log10:
6879 Opcode = ISD::STRICT_FLOG10;
6881 case Intrinsic::experimental_constrained_log2:
6882 Opcode = ISD::STRICT_FLOG2;
6884 case Intrinsic::experimental_constrained_rint:
6885 Opcode = ISD::STRICT_FRINT;
6887 case Intrinsic::experimental_constrained_nearbyint:
6888 Opcode = ISD::STRICT_FNEARBYINT;
6890 case Intrinsic::experimental_constrained_maxnum:
6891 Opcode = ISD::STRICT_FMAXNUM;
6893 case Intrinsic::experimental_constrained_minnum:
6894 Opcode = ISD::STRICT_FMINNUM;
6896 case Intrinsic::experimental_constrained_ceil:
6897 Opcode = ISD::STRICT_FCEIL;
6899 case Intrinsic::experimental_constrained_floor:
6900 Opcode = ISD::STRICT_FFLOOR;
6902 case Intrinsic::experimental_constrained_round:
6903 Opcode = ISD::STRICT_FROUND;
6905 case Intrinsic::experimental_constrained_trunc:
6906 Opcode = ISD::STRICT_FTRUNC;
6909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6910 SDValue Chain = getRoot();
6911 SmallVector<EVT, 4> ValueVTs;
6912 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6913 ValueVTs.push_back(MVT::Other); // Out chain
6915 SDVTList VTs = DAG.getVTList(ValueVTs);
6917 if (Opcode == ISD::STRICT_FP_ROUND)
6918 Result = DAG.getNode(Opcode, sdl, VTs,
6919 { Chain, getValue(FPI.getArgOperand(0)),
6920 DAG.getTargetConstant(0, sdl,
6921 TLI.getPointerTy(DAG.getDataLayout())) });
6922 else if (FPI.isUnaryOp())
6923 Result = DAG.getNode(Opcode, sdl, VTs,
6924 { Chain, getValue(FPI.getArgOperand(0)) });
6925 else if (FPI.isTernaryOp())
6926 Result = DAG.getNode(Opcode, sdl, VTs,
6927 { Chain, getValue(FPI.getArgOperand(0)),
6928 getValue(FPI.getArgOperand(1)),
6929 getValue(FPI.getArgOperand(2)) });
6931 Result = DAG.getNode(Opcode, sdl, VTs,
6932 { Chain, getValue(FPI.getArgOperand(0)),
6933 getValue(FPI.getArgOperand(1)) });
6935 if (FPI.getExceptionBehavior() !=
6936 ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
6938 Flags.setFPExcept(true);
6939 Result->setFlags(Flags);
6942 assert(Result.getNode()->getNumValues() == 2);
6943 SDValue OutChain = Result.getValue(1);
6944 DAG.setRoot(OutChain);
6945 SDValue FPResult = Result.getValue(0);
6946 setValue(&FPI, FPResult);
6949 std::pair<SDValue, SDValue>
6950 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6951 const BasicBlock *EHPadBB) {
6952 MachineFunction &MF = DAG.getMachineFunction();
6953 MachineModuleInfo &MMI = MF.getMMI();
6954 MCSymbol *BeginLabel = nullptr;
6957 // Insert a label before the invoke call to mark the try range. This can be
6958 // used to detect deletion of the invoke via the MachineModuleInfo.
6959 BeginLabel = MMI.getContext().createTempSymbol();
6961 // For SjLj, keep track of which landing pads go with which invokes
6962 // so as to maintain the ordering of pads in the LSDA.
6963 unsigned CallSiteIndex = MMI.getCurrentCallSite();
6964 if (CallSiteIndex) {
6965 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6966 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6968 // Now that the call site is handled, stop tracking it.
6969 MMI.setCurrentCallSite(0);
6972 // Both PendingLoads and PendingExports must be flushed here;
6973 // this call might not return.
6975 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6977 CLI.setChain(getRoot());
6979 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6980 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6982 assert((CLI.IsTailCall || Result.second.getNode()) &&
6983 "Non-null chain expected with non-tail call!");
6984 assert((Result.second.getNode() || !Result.first.getNode()) &&
6985 "Null value expected with tail call!");
6987 if (!Result.second.getNode()) {
6988 // As a special case, a null chain means that a tail call has been emitted
6989 // and the DAG root is already updated.
6992 // Since there's no actual continuation from this block, nothing can be
6993 // relying on us setting vregs for them.
6994 PendingExports.clear();
6996 DAG.setRoot(Result.second);
7000 // Insert a label at the end of the invoke call to mark the try range. This
7001 // can be used to detect deletion of the invoke via the MachineModuleInfo.
7002 MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7003 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7005 // Inform MachineModuleInfo of range.
7006 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7007 // There is a platform (e.g. wasm) that uses funclet style IR but does not
7008 // actually use outlined funclets and their LSDA info style.
7009 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7011 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7012 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7013 BeginLabel, EndLabel);
7014 } else if (!isScopedEHPersonality(Pers)) {
7015 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7022 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7024 const BasicBlock *EHPadBB) {
7025 auto &DL = DAG.getDataLayout();
7026 FunctionType *FTy = CS.getFunctionType();
7027 Type *RetTy = CS.getType();
7029 TargetLowering::ArgListTy Args;
7030 Args.reserve(CS.arg_size());
7032 const Value *SwiftErrorVal = nullptr;
7033 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7035 // We can't tail call inside a function with a swifterror argument. Lowering
7036 // does not support this yet. It would have to move into the swifterror
7037 // register before the call.
7038 auto *Caller = CS.getInstruction()->getParent()->getParent();
7039 if (TLI.supportSwiftError() &&
7040 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7043 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7045 TargetLowering::ArgListEntry Entry;
7046 const Value *V = *i;
7049 if (V->getType()->isEmptyTy())
7052 SDValue ArgNode = getValue(V);
7053 Entry.Node = ArgNode; Entry.Ty = V->getType();
7055 Entry.setAttributes(&CS, i - CS.arg_begin());
7057 // Use swifterror virtual register as input to the call.
7058 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7060 // We find the virtual register for the actual swifterror argument.
7061 // Instead of using the Value, we use the virtual register instead.
7062 Entry.Node = DAG.getRegister(
7063 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7064 EVT(TLI.getPointerTy(DL)));
7067 Args.push_back(Entry);
7069 // If we have an explicit sret argument that is an Instruction, (i.e., it
7070 // might point to function-local memory), we can't meaningfully tail-call.
7071 if (Entry.IsSRet && isa<Instruction>(V))
7075 // Check if target-independent constraints permit a tail call here.
7076 // Target-dependent constraints are checked within TLI->LowerCallTo.
7077 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7080 // Disable tail calls if there is an swifterror argument. Targets have not
7081 // been updated to support tail calls.
7082 if (TLI.supportSwiftError() && SwiftErrorVal)
7085 TargetLowering::CallLoweringInfo CLI(DAG);
7086 CLI.setDebugLoc(getCurSDLoc())
7087 .setChain(getRoot())
7088 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7089 .setTailCall(isTailCall)
7090 .setConvergent(CS.isConvergent());
7091 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7093 if (Result.first.getNode()) {
7094 const Instruction *Inst = CS.getInstruction();
7095 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7096 setValue(Inst, Result.first);
7099 // The last element of CLI.InVals has the SDValue for swifterror return.
7100 // Here we copy it to a virtual register and update SwiftErrorMap for
7102 if (SwiftErrorVal && TLI.supportSwiftError()) {
7103 // Get the last element of InVals.
7104 SDValue Src = CLI.InVals.back();
7105 unsigned VReg = SwiftError.getOrCreateVRegDefAt(
7106 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7107 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7108 DAG.setRoot(CopyNode);
7112 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7113 SelectionDAGBuilder &Builder) {
7114 // Check to see if this load can be trivially constant folded, e.g. if the
7115 // input is from a string literal.
7116 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7117 // Cast pointer to the type we really want to load.
7119 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7120 if (LoadVT.isVector())
7121 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7123 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7124 PointerType::getUnqual(LoadTy));
7126 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7127 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7128 return Builder.getValue(LoadCst);
7131 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
7132 // still constant memory, the input chain can be the entry node.
7134 bool ConstantMemory = false;
7136 // Do not serialize (non-volatile) loads of constant memory with anything.
7137 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7138 Root = Builder.DAG.getEntryNode();
7139 ConstantMemory = true;
7141 // Do not serialize non-volatile loads against each other.
7142 Root = Builder.DAG.getRoot();
7145 SDValue Ptr = Builder.getValue(PtrVal);
7146 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7147 Ptr, MachinePointerInfo(PtrVal),
7148 /* Alignment = */ 1);
7150 if (!ConstantMemory)
7151 Builder.PendingLoads.push_back(LoadVal.getValue(1));
7155 /// Record the value for an instruction that produces an integer result,
7156 /// converting the type where necessary.
7157 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7160 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7163 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7165 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7166 setValue(&I, Value);
7169 /// See if we can lower a memcmp call into an optimized form. If so, return
7170 /// true and lower it. Otherwise return false, and it will be lowered like a
7172 /// The caller already checked that \p I calls the appropriate LibFunc with a
7173 /// correct prototype.
7174 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7175 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7176 const Value *Size = I.getArgOperand(2);
7177 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7178 if (CSize && CSize->getZExtValue() == 0) {
7179 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7181 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7185 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7186 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7187 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7188 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7189 if (Res.first.getNode()) {
7190 processIntegerCallValue(I, Res.first, true);
7191 PendingLoads.push_back(Res.second);
7195 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
7196 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
7197 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7200 // If the target has a fast compare for the given size, it will return a
7201 // preferred load type for that size. Require that the load VT is legal and
7202 // that the target supports unaligned loads of that type. Otherwise, return
7204 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7205 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7206 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7207 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7208 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7209 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7210 // TODO: Check alignment of src and dest ptrs.
7211 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7212 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7213 if (!TLI.isTypeLegal(LVT) ||
7214 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7215 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7216 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7222 // This turns into unaligned loads. We only do this if the target natively
7223 // supports the MVT we'll be loading or if it is small enough (<= 4) that
7224 // we'll only produce a small number of byte loads.
7226 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7227 switch (NumBitsToCompare) {
7239 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7243 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7246 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7247 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7249 // Bitcast to a wide integer type if the loads are vectors.
7250 if (LoadVT.isVector()) {
7251 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7252 LoadL = DAG.getBitcast(CmpVT, LoadL);
7253 LoadR = DAG.getBitcast(CmpVT, LoadR);
7256 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7257 processIntegerCallValue(I, Cmp, false);
7261 /// See if we can lower a memchr call into an optimized form. If so, return
7262 /// true and lower it. Otherwise return false, and it will be lowered like a
7264 /// The caller already checked that \p I calls the appropriate LibFunc with a
7265 /// correct prototype.
7266 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7267 const Value *Src = I.getArgOperand(0);
7268 const Value *Char = I.getArgOperand(1);
7269 const Value *Length = I.getArgOperand(2);
7271 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7272 std::pair<SDValue, SDValue> Res =
7273 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7274 getValue(Src), getValue(Char), getValue(Length),
7275 MachinePointerInfo(Src));
7276 if (Res.first.getNode()) {
7277 setValue(&I, Res.first);
7278 PendingLoads.push_back(Res.second);
7285 /// See if we can lower a mempcpy call into an optimized form. If so, return
7286 /// true and lower it. Otherwise return false, and it will be lowered like a
7288 /// The caller already checked that \p I calls the appropriate LibFunc with a
7289 /// correct prototype.
7290 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7291 SDValue Dst = getValue(I.getArgOperand(0));
7292 SDValue Src = getValue(I.getArgOperand(1));
7293 SDValue Size = getValue(I.getArgOperand(2));
7295 unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7296 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7297 unsigned Align = std::min(DstAlign, SrcAlign);
7298 if (Align == 0) // Alignment of one or both could not be inferred.
7299 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7302 SDLoc sdl = getCurSDLoc();
7304 // In the mempcpy context we need to pass in a false value for isTailCall
7305 // because the return pointer needs to be adjusted by the size of
7306 // the copied memory.
7307 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7308 false, /*isTailCall=*/false,
7309 MachinePointerInfo(I.getArgOperand(0)),
7310 MachinePointerInfo(I.getArgOperand(1)));
7311 assert(MC.getNode() != nullptr &&
7312 "** memcpy should not be lowered as TailCall in mempcpy context **");
7315 // Check if Size needs to be truncated or extended.
7316 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7318 // Adjust return pointer to point just past the last dst byte.
7319 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7321 setValue(&I, DstPlusSize);
7325 /// See if we can lower a strcpy call into an optimized form. If so, return
7326 /// true and lower it, otherwise return false and it will be lowered like a
7328 /// The caller already checked that \p I calls the appropriate LibFunc with a
7329 /// correct prototype.
7330 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7331 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7333 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7334 std::pair<SDValue, SDValue> Res =
7335 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7336 getValue(Arg0), getValue(Arg1),
7337 MachinePointerInfo(Arg0),
7338 MachinePointerInfo(Arg1), isStpcpy);
7339 if (Res.first.getNode()) {
7340 setValue(&I, Res.first);
7341 DAG.setRoot(Res.second);
7348 /// See if we can lower a strcmp call into an optimized form. If so, return
7349 /// true and lower it, otherwise return false and it will be lowered like a
7351 /// The caller already checked that \p I calls the appropriate LibFunc with a
7352 /// correct prototype.
7353 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7354 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7356 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7357 std::pair<SDValue, SDValue> Res =
7358 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7359 getValue(Arg0), getValue(Arg1),
7360 MachinePointerInfo(Arg0),
7361 MachinePointerInfo(Arg1));
7362 if (Res.first.getNode()) {
7363 processIntegerCallValue(I, Res.first, true);
7364 PendingLoads.push_back(Res.second);
7371 /// See if we can lower a strlen call into an optimized form. If so, return
7372 /// true and lower it, otherwise return false and it will be lowered like a
7374 /// The caller already checked that \p I calls the appropriate LibFunc with a
7375 /// correct prototype.
7376 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7377 const Value *Arg0 = I.getArgOperand(0);
7379 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7380 std::pair<SDValue, SDValue> Res =
7381 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7382 getValue(Arg0), MachinePointerInfo(Arg0));
7383 if (Res.first.getNode()) {
7384 processIntegerCallValue(I, Res.first, false);
7385 PendingLoads.push_back(Res.second);
7392 /// See if we can lower a strnlen call into an optimized form. If so, return
7393 /// true and lower it, otherwise return false and it will be lowered like a
7395 /// The caller already checked that \p I calls the appropriate LibFunc with a
7396 /// correct prototype.
7397 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7398 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7400 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7401 std::pair<SDValue, SDValue> Res =
7402 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7403 getValue(Arg0), getValue(Arg1),
7404 MachinePointerInfo(Arg0));
7405 if (Res.first.getNode()) {
7406 processIntegerCallValue(I, Res.first, false);
7407 PendingLoads.push_back(Res.second);
7414 /// See if we can lower a unary floating-point operation into an SDNode with
7415 /// the specified Opcode. If so, return true and lower it, otherwise return
7416 /// false and it will be lowered like a normal call.
7417 /// The caller already checked that \p I calls the appropriate LibFunc with a
7418 /// correct prototype.
7419 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7421 // We already checked this call's prototype; verify it doesn't modify errno.
7422 if (!I.onlyReadsMemory())
7425 SDValue Tmp = getValue(I.getArgOperand(0));
7426 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7430 /// See if we can lower a binary floating-point operation into an SDNode with
7431 /// the specified Opcode. If so, return true and lower it. Otherwise return
7432 /// false, and it will be lowered like a normal call.
7433 /// The caller already checked that \p I calls the appropriate LibFunc with a
7434 /// correct prototype.
7435 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7437 // We already checked this call's prototype; verify it doesn't modify errno.
7438 if (!I.onlyReadsMemory())
7441 SDValue Tmp0 = getValue(I.getArgOperand(0));
7442 SDValue Tmp1 = getValue(I.getArgOperand(1));
7443 EVT VT = Tmp0.getValueType();
7444 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7448 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7449 // Handle inline assembly differently.
7450 if (isa<InlineAsm>(I.getCalledValue())) {
7455 if (Function *F = I.getCalledFunction()) {
7456 if (F->isDeclaration()) {
7457 // Is this an LLVM intrinsic or a target-specific intrinsic?
7458 unsigned IID = F->getIntrinsicID();
7460 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7461 IID = II->getIntrinsicID(F);
7464 visitIntrinsicCall(I, IID);
7469 // Check for well-known libc/libm calls. If the function is internal, it
7470 // can't be a library call. Don't do the check if marked as nobuiltin for
7471 // some reason or the call site requires strict floating point semantics.
7473 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7474 F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7475 LibInfo->hasOptimizedCodeGen(Func)) {
7478 case LibFunc_copysign:
7479 case LibFunc_copysignf:
7480 case LibFunc_copysignl:
7481 // We already checked this call's prototype; verify it doesn't modify
7483 if (I.onlyReadsMemory()) {
7484 SDValue LHS = getValue(I.getArgOperand(0));
7485 SDValue RHS = getValue(I.getArgOperand(1));
7486 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7487 LHS.getValueType(), LHS, RHS));
7494 if (visitUnaryFloatCall(I, ISD::FABS))
7500 if (visitBinaryFloatCall(I, ISD::FMINNUM))
7506 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7512 if (visitUnaryFloatCall(I, ISD::FSIN))
7518 if (visitUnaryFloatCall(I, ISD::FCOS))
7524 case LibFunc_sqrt_finite:
7525 case LibFunc_sqrtf_finite:
7526 case LibFunc_sqrtl_finite:
7527 if (visitUnaryFloatCall(I, ISD::FSQRT))
7531 case LibFunc_floorf:
7532 case LibFunc_floorl:
7533 if (visitUnaryFloatCall(I, ISD::FFLOOR))
7536 case LibFunc_nearbyint:
7537 case LibFunc_nearbyintf:
7538 case LibFunc_nearbyintl:
7539 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7545 if (visitUnaryFloatCall(I, ISD::FCEIL))
7551 if (visitUnaryFloatCall(I, ISD::FRINT))
7555 case LibFunc_roundf:
7556 case LibFunc_roundl:
7557 if (visitUnaryFloatCall(I, ISD::FROUND))
7561 case LibFunc_truncf:
7562 case LibFunc_truncl:
7563 if (visitUnaryFloatCall(I, ISD::FTRUNC))
7569 if (visitUnaryFloatCall(I, ISD::FLOG2))
7575 if (visitUnaryFloatCall(I, ISD::FEXP2))
7578 case LibFunc_memcmp:
7579 if (visitMemCmpCall(I))
7582 case LibFunc_mempcpy:
7583 if (visitMemPCpyCall(I))
7586 case LibFunc_memchr:
7587 if (visitMemChrCall(I))
7590 case LibFunc_strcpy:
7591 if (visitStrCpyCall(I, false))
7594 case LibFunc_stpcpy:
7595 if (visitStrCpyCall(I, true))
7598 case LibFunc_strcmp:
7599 if (visitStrCmpCall(I))
7602 case LibFunc_strlen:
7603 if (visitStrLenCall(I))
7606 case LibFunc_strnlen:
7607 if (visitStrNLenCall(I))
7614 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7615 // have to do anything here to lower funclet bundles.
7616 assert(!I.hasOperandBundlesOtherThan(
7617 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7618 "Cannot lower calls with arbitrary operand bundles!");
7620 SDValue Callee = getValue(I.getCalledValue());
7622 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7623 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7625 // Check if we can potentially perform a tail call. More detailed checking
7626 // is be done within LowerCallTo, after more information about the call is
7628 LowerCallTo(&I, Callee, I.isTailCall());
7633 /// AsmOperandInfo - This contains information for each constraint that we are
7635 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7637 /// CallOperand - If this is the result output operand or a clobber
7638 /// this is null, otherwise it is the incoming operand to the CallInst.
7639 /// This gets modified as the asm is processed.
7640 SDValue CallOperand;
7642 /// AssignedRegs - If this is a register or register class operand, this
7643 /// contains the set of register corresponding to the operand.
7644 RegsForValue AssignedRegs;
7646 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7647 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7650 /// Whether or not this operand accesses memory
7651 bool hasMemory(const TargetLowering &TLI) const {
7652 // Indirect operand accesses access memory.
7656 for (const auto &Code : Codes)
7657 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7663 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7664 /// corresponds to. If there is no Value* for this operand, it returns
7666 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7667 const DataLayout &DL) const {
7668 if (!CallOperandVal) return MVT::Other;
7670 if (isa<BasicBlock>(CallOperandVal))
7671 return TLI.getPointerTy(DL);
7673 llvm::Type *OpTy = CallOperandVal->getType();
7675 // FIXME: code duplicated from TargetLowering::ParseConstraints().
7676 // If this is an indirect operand, the operand is a pointer to the
7679 PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7681 report_fatal_error("Indirect operand for inline asm not a pointer!");
7682 OpTy = PtrTy->getElementType();
7685 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7686 if (StructType *STy = dyn_cast<StructType>(OpTy))
7687 if (STy->getNumElements() == 1)
7688 OpTy = STy->getElementType(0);
7690 // If OpTy is not a single value, it may be a struct/union that we
7691 // can tile with integers.
7692 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7693 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7702 OpTy = IntegerType::get(Context, BitSize);
7707 return TLI.getValueType(DL, OpTy, true);
7711 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7713 } // end anonymous namespace
7715 /// Make sure that the output operand \p OpInfo and its corresponding input
7716 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7718 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7719 SDISelAsmOperandInfo &MatchingOpInfo,
7720 SelectionDAG &DAG) {
7721 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7724 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7725 const auto &TLI = DAG.getTargetLoweringInfo();
7727 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7728 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7729 OpInfo.ConstraintVT);
7730 std::pair<unsigned, const TargetRegisterClass *> InputRC =
7731 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7732 MatchingOpInfo.ConstraintVT);
7733 if ((OpInfo.ConstraintVT.isInteger() !=
7734 MatchingOpInfo.ConstraintVT.isInteger()) ||
7735 (MatchRC.second != InputRC.second)) {
7736 // FIXME: error out in a more elegant fashion
7737 report_fatal_error("Unsupported asm: input constraint"
7738 " with a matching output constraint of"
7739 " incompatible type!");
7741 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7744 /// Get a direct memory input to behave well as an indirect operand.
7745 /// This may introduce stores, hence the need for a \p Chain.
7746 /// \return The (possibly updated) chain.
7747 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7748 SDISelAsmOperandInfo &OpInfo,
7749 SelectionDAG &DAG) {
7750 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7752 // If we don't have an indirect input, put it in the constpool if we can,
7753 // otherwise spill it to a stack slot.
7754 // TODO: This isn't quite right. We need to handle these according to
7755 // the addressing mode that the constraint wants. Also, this may take
7756 // an additional register for the computation and we don't want that
7759 // If the operand is a float, integer, or vector constant, spill to a
7760 // constant pool entry to get its address.
7761 const Value *OpVal = OpInfo.CallOperandVal;
7762 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7763 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7764 OpInfo.CallOperand = DAG.getConstantPool(
7765 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7769 // Otherwise, create a stack slot and emit a store to it before the asm.
7770 Type *Ty = OpVal->getType();
7771 auto &DL = DAG.getDataLayout();
7772 uint64_t TySize = DL.getTypeAllocSize(Ty);
7773 unsigned Align = DL.getPrefTypeAlignment(Ty);
7774 MachineFunction &MF = DAG.getMachineFunction();
7775 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7776 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7777 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7778 MachinePointerInfo::getFixedStack(MF, SSFI),
7779 TLI.getMemValueType(DL, Ty));
7780 OpInfo.CallOperand = StackSlot;
7785 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7786 /// specified operand. We prefer to assign virtual registers, to allow the
7787 /// register allocator to handle the assignment process. However, if the asm
7788 /// uses features that we can't model on machineinstrs, we have SDISel do the
7789 /// allocation. This produces generally horrible, but correct, code.
7791 /// OpInfo describes the operand
7792 /// RefOpInfo describes the matching operand if any, the operand otherwise
7793 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7794 SDISelAsmOperandInfo &OpInfo,
7795 SDISelAsmOperandInfo &RefOpInfo) {
7796 LLVMContext &Context = *DAG.getContext();
7797 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7799 MachineFunction &MF = DAG.getMachineFunction();
7800 SmallVector<unsigned, 4> Regs;
7801 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7803 // No work to do for memory operations.
7804 if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7807 // If this is a constraint for a single physreg, or a constraint for a
7808 // register class, find it.
7809 unsigned AssignedReg;
7810 const TargetRegisterClass *RC;
7811 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7812 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7813 // RC is unset only on failure. Return immediately.
7817 // Get the actual register value type. This is important, because the user
7818 // may have asked for (e.g.) the AX register in i32 type. We need to
7819 // remember that AX is actually i16 to get the right extension.
7820 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7822 if (OpInfo.ConstraintVT != MVT::Other) {
7823 // If this is an FP operand in an integer register (or visa versa), or more
7824 // generally if the operand value disagrees with the register class we plan
7825 // to stick it in, fix the operand type.
7827 // If this is an input value, the bitcast to the new type is done now.
7828 // Bitcast for output value is done at the end of visitInlineAsm().
7829 if ((OpInfo.Type == InlineAsm::isOutput ||
7830 OpInfo.Type == InlineAsm::isInput) &&
7831 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7832 // Try to convert to the first EVT that the reg class contains. If the
7833 // types are identical size, use a bitcast to convert (e.g. two differing
7834 // vector types). Note: output bitcast is done at the end of
7835 // visitInlineAsm().
7836 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7837 // Exclude indirect inputs while they are unsupported because the code
7838 // to perform the load is missing and thus OpInfo.CallOperand still
7839 // refers to the input address rather than the pointed-to value.
7840 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7841 OpInfo.CallOperand =
7842 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7843 OpInfo.ConstraintVT = RegVT;
7844 // If the operand is an FP value and we want it in integer registers,
7845 // use the corresponding integer type. This turns an f64 value into
7846 // i64, which can be passed with two i32 values on a 32-bit machine.
7847 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7848 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7849 if (OpInfo.Type == InlineAsm::isInput)
7850 OpInfo.CallOperand =
7851 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7852 OpInfo.ConstraintVT = VT;
7857 // No need to allocate a matching input constraint since the constraint it's
7858 // matching to has already been allocated.
7859 if (OpInfo.isMatchingInputConstraint())
7862 EVT ValueVT = OpInfo.ConstraintVT;
7863 if (OpInfo.ConstraintVT == MVT::Other)
7866 // Initialize NumRegs.
7867 unsigned NumRegs = 1;
7868 if (OpInfo.ConstraintVT != MVT::Other)
7869 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7871 // If this is a constraint for a specific physical register, like {r17},
7874 // If this associated to a specific register, initialize iterator to correct
7875 // place. If virtual, make sure we have enough registers
7877 // Initialize iterator if necessary
7878 TargetRegisterClass::iterator I = RC->begin();
7879 MachineRegisterInfo &RegInfo = MF.getRegInfo();
7881 // Do not check for single registers.
7883 for (; *I != AssignedReg; ++I)
7884 assert(I != RC->end() && "AssignedReg should be member of RC");
7887 for (; NumRegs; --NumRegs, ++I) {
7888 assert(I != RC->end() && "Ran out of registers to allocate!");
7889 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7893 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7897 findMatchingInlineAsmOperand(unsigned OperandNo,
7898 const std::vector<SDValue> &AsmNodeOperands) {
7899 // Scan until we find the definition we already emitted of this operand.
7900 unsigned CurOp = InlineAsm::Op_FirstOperand;
7901 for (; OperandNo; --OperandNo) {
7902 // Advance to the next operand.
7904 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7905 assert((InlineAsm::isRegDefKind(OpFlag) ||
7906 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7907 InlineAsm::isMemKind(OpFlag)) &&
7908 "Skipped past definitions?");
7909 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7920 explicit ExtraFlags(ImmutableCallSite CS) {
7921 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7922 if (IA->hasSideEffects())
7923 Flags |= InlineAsm::Extra_HasSideEffects;
7924 if (IA->isAlignStack())
7925 Flags |= InlineAsm::Extra_IsAlignStack;
7926 if (CS.isConvergent())
7927 Flags |= InlineAsm::Extra_IsConvergent;
7928 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7931 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7932 // Ideally, we would only check against memory constraints. However, the
7933 // meaning of an Other constraint can be target-specific and we can't easily
7934 // reason about it. Therefore, be conservative and set MayLoad/MayStore
7935 // for Other constraints as well.
7936 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7937 OpInfo.ConstraintType == TargetLowering::C_Other) {
7938 if (OpInfo.Type == InlineAsm::isInput)
7939 Flags |= InlineAsm::Extra_MayLoad;
7940 else if (OpInfo.Type == InlineAsm::isOutput)
7941 Flags |= InlineAsm::Extra_MayStore;
7942 else if (OpInfo.Type == InlineAsm::isClobber)
7943 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7947 unsigned get() const { return Flags; }
7950 } // end anonymous namespace
7952 /// visitInlineAsm - Handle a call to an InlineAsm object.
7953 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7954 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7956 /// ConstraintOperands - Information about all of the constraints.
7957 SDISelAsmOperandInfoVector ConstraintOperands;
7959 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7960 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7961 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7963 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7964 // AsmDialect, MayLoad, MayStore).
7965 bool HasSideEffect = IA->hasSideEffects();
7966 ExtraFlags ExtraInfo(CS);
7968 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
7969 unsigned ResNo = 0; // ResNo - The result number of the next output.
7970 for (auto &T : TargetConstraints) {
7971 ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7972 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7974 // Compute the value type for each operand.
7975 if (OpInfo.Type == InlineAsm::isInput ||
7976 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7977 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7979 // Process the call argument. BasicBlocks are labels, currently appearing
7981 const Instruction *I = CS.getInstruction();
7982 if (isa<CallBrInst>(I) &&
7983 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7984 cast<CallBrInst>(I)->getNumIndirectDests())) {
7985 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7986 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7987 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
7988 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7989 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7991 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7994 OpInfo.ConstraintVT =
7996 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7998 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7999 // The return value of the call is this value. As such, there is no
8000 // corresponding argument.
8001 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8002 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8003 OpInfo.ConstraintVT = TLI.getSimpleValueType(
8004 DAG.getDataLayout(), STy->getElementType(ResNo));
8006 assert(ResNo == 0 && "Asm only has one result!");
8007 OpInfo.ConstraintVT =
8008 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8012 OpInfo.ConstraintVT = MVT::Other;
8016 HasSideEffect = OpInfo.hasMemory(TLI);
8018 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8019 // FIXME: Could we compute this on OpInfo rather than T?
8021 // Compute the constraint code and ConstraintType to use.
8022 TLI.ComputeConstraintToUse(T, SDValue());
8024 if (T.ConstraintType == TargetLowering::C_Immediate &&
8025 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8026 // We've delayed emitting a diagnostic like the "n" constraint because
8027 // inlining could cause an integer showing up.
8028 return emitInlineAsmError(
8029 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8030 "integer constant expression");
8032 ExtraInfo.update(T);
8036 // We won't need to flush pending loads if this asm doesn't touch
8037 // memory and is nonvolatile.
8038 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8040 bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8042 // If this is a callbr we need to flush pending exports since inlineasm_br
8043 // is a terminator. We need to do this before nodes are glued to
8044 // the inlineasm_br node.
8045 Chain = getControlRoot();
8048 // Second pass over the constraints: compute which constraint option to use.
8049 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8050 // If this is an output operand with a matching input operand, look up the
8051 // matching input. If their types mismatch, e.g. one is an integer, the
8052 // other is floating point, or their sizes are different, flag it as an
8054 if (OpInfo.hasMatchingInput()) {
8055 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8056 patchMatchingInput(OpInfo, Input, DAG);
8059 // Compute the constraint code and ConstraintType to use.
8060 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8062 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8063 OpInfo.Type == InlineAsm::isClobber)
8066 // If this is a memory input, and if the operand is not indirect, do what we
8067 // need to provide an address for the memory input.
8068 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8069 !OpInfo.isIndirect) {
8070 assert((OpInfo.isMultipleAlternative ||
8071 (OpInfo.Type == InlineAsm::isInput)) &&
8072 "Can only indirectify direct input operands!");
8074 // Memory operands really want the address of the value.
8075 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8077 // There is no longer a Value* corresponding to this operand.
8078 OpInfo.CallOperandVal = nullptr;
8080 // It is now an indirect operand.
8081 OpInfo.isIndirect = true;
8086 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8087 std::vector<SDValue> AsmNodeOperands;
8088 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
8089 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8090 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8092 // If we have a !srcloc metadata node associated with it, we want to attach
8093 // this to the ultimately generated inline asm machineinstr. To do this, we
8094 // pass in the third operand as this (potentially null) inline asm MDNode.
8095 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8096 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8098 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8099 // bits as operand 3.
8100 AsmNodeOperands.push_back(DAG.getTargetConstant(
8101 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8103 // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8104 // this, assign virtual and physical registers for inputs and otput.
8105 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8106 // Assign Registers.
8107 SDISelAsmOperandInfo &RefOpInfo =
8108 OpInfo.isMatchingInputConstraint()
8109 ? ConstraintOperands[OpInfo.getMatchedOperand()]
8111 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8113 switch (OpInfo.Type) {
8114 case InlineAsm::isOutput:
8115 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8116 ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8117 OpInfo.ConstraintType == TargetLowering::C_Other) &&
8118 OpInfo.isIndirect)) {
8119 unsigned ConstraintID =
8120 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8121 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8122 "Failed to convert memory constraint code to constraint id.");
8124 // Add information to the INLINEASM node to know about this output.
8125 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8126 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8127 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8129 AsmNodeOperands.push_back(OpInfo.CallOperand);
8131 } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8132 OpInfo.ConstraintType == TargetLowering::C_Other) &&
8133 !OpInfo.isIndirect) ||
8134 OpInfo.ConstraintType == TargetLowering::C_Register ||
8135 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8136 // Otherwise, this outputs to a register (directly for C_Register /
8137 // C_RegisterClass, and a target-defined fashion for
8138 // C_Immediate/C_Other). Find a register that we can use.
8139 if (OpInfo.AssignedRegs.Regs.empty()) {
8141 CS, "couldn't allocate output register for constraint '" +
8142 Twine(OpInfo.ConstraintCode) + "'");
8146 // Add information to the INLINEASM node to know that this register is
8148 OpInfo.AssignedRegs.AddInlineAsmOperands(
8149 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8150 : InlineAsm::Kind_RegDef,
8151 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8155 case InlineAsm::isInput: {
8156 SDValue InOperandVal = OpInfo.CallOperand;
8158 if (OpInfo.isMatchingInputConstraint()) {
8159 // If this is required to match an output register we have already set,
8160 // just use its register.
8161 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8164 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8165 if (InlineAsm::isRegDefKind(OpFlag) ||
8166 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8167 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8168 if (OpInfo.isIndirect) {
8169 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8170 emitInlineAsmError(CS, "inline asm not supported yet:"
8171 " don't know how to handle tied "
8172 "indirect register inputs");
8176 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8177 SmallVector<unsigned, 4> Regs;
8179 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8180 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8181 MachineRegisterInfo &RegInfo =
8182 DAG.getMachineFunction().getRegInfo();
8183 for (unsigned i = 0; i != NumRegs; ++i)
8184 Regs.push_back(RegInfo.createVirtualRegister(RC));
8186 emitInlineAsmError(CS, "inline asm error: This value type register "
8187 "class is not natively supported!");
8191 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8193 SDLoc dl = getCurSDLoc();
8194 // Use the produced MatchedRegs object to
8195 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8196 CS.getInstruction());
8197 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8198 true, OpInfo.getMatchedOperand(), dl,
8199 DAG, AsmNodeOperands);
8203 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8204 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8205 "Unexpected number of operands");
8206 // Add information to the INLINEASM node to know about this input.
8207 // See InlineAsm.h isUseOperandTiedToDef.
8208 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8209 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8210 OpInfo.getMatchedOperand());
8211 AsmNodeOperands.push_back(DAG.getTargetConstant(
8212 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8213 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8217 // Treat indirect 'X' constraint as memory.
8218 if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8219 OpInfo.ConstraintType == TargetLowering::C_Other) &&
8221 OpInfo.ConstraintType = TargetLowering::C_Memory;
8223 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8224 OpInfo.ConstraintType == TargetLowering::C_Other) {
8225 std::vector<SDValue> Ops;
8226 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8229 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8230 if (isa<ConstantSDNode>(InOperandVal)) {
8231 emitInlineAsmError(CS, "value out of range for constraint '" +
8232 Twine(OpInfo.ConstraintCode) + "'");
8236 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8237 Twine(OpInfo.ConstraintCode) + "'");
8241 // Add information to the INLINEASM node to know about this input.
8242 unsigned ResOpType =
8243 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8244 AsmNodeOperands.push_back(DAG.getTargetConstant(
8245 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8246 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8250 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8251 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8252 assert(InOperandVal.getValueType() ==
8253 TLI.getPointerTy(DAG.getDataLayout()) &&
8254 "Memory operands expect pointer values");
8256 unsigned ConstraintID =
8257 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8258 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8259 "Failed to convert memory constraint code to constraint id.");
8261 // Add information to the INLINEASM node to know about this input.
8262 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8263 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8264 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8267 AsmNodeOperands.push_back(InOperandVal);
8271 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8272 OpInfo.ConstraintType == TargetLowering::C_Register ||
8273 OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
8274 "Unknown constraint type!");
8276 // TODO: Support this.
8277 if (OpInfo.isIndirect) {
8279 CS, "Don't know how to handle indirect register inputs yet "
8280 "for constraint '" +
8281 Twine(OpInfo.ConstraintCode) + "'");
8285 // Copy the input into the appropriate registers.
8286 if (OpInfo.AssignedRegs.Regs.empty()) {
8287 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8288 Twine(OpInfo.ConstraintCode) + "'");
8292 SDLoc dl = getCurSDLoc();
8294 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8295 Chain, &Flag, CS.getInstruction());
8297 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8298 dl, DAG, AsmNodeOperands);
8301 case InlineAsm::isClobber:
8302 // Add the clobbered value to the operand list, so that the register
8303 // allocator is aware that the physreg got clobbered.
8304 if (!OpInfo.AssignedRegs.Regs.empty())
8305 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8306 false, 0, getCurSDLoc(), DAG,
8312 // Finish up input operands. Set the input chain and add the flag last.
8313 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8314 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8316 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8317 Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8318 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8319 Flag = Chain.getValue(1);
8321 // Do additional work to generate outputs.
8323 SmallVector<EVT, 1> ResultVTs;
8324 SmallVector<SDValue, 1> ResultValues;
8325 SmallVector<SDValue, 8> OutChains;
8327 llvm::Type *CSResultType = CS.getType();
8328 ArrayRef<Type *> ResultTypes;
8329 if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8330 ResultTypes = StructResult->elements();
8331 else if (!CSResultType->isVoidTy())
8332 ResultTypes = makeArrayRef(CSResultType);
8334 auto CurResultType = ResultTypes.begin();
8335 auto handleRegAssign = [&](SDValue V) {
8336 assert(CurResultType != ResultTypes.end() && "Unexpected value");
8337 assert((*CurResultType)->isSized() && "Unexpected unsized type");
8338 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8340 // If the type of the inline asm call site return value is different but has
8341 // same size as the type of the asm output bitcast it. One example of this
8342 // is for vectors with different width / number of elements. This can
8343 // happen for register classes that can contain multiple different value
8344 // types. The preg or vreg allocated may not have the same VT as was
8347 // This can also happen for a return value that disagrees with the register
8348 // class it is put in, eg. a double in a general-purpose register on a
8350 if (ResultVT != V.getValueType() &&
8351 ResultVT.getSizeInBits() == V.getValueSizeInBits())
8352 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8353 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8354 V.getValueType().isInteger()) {
8355 // If a result value was tied to an input value, the computed result
8356 // may have a wider width than the expected result. Extract the
8357 // relevant portion.
8358 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8360 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8361 ResultVTs.push_back(ResultVT);
8362 ResultValues.push_back(V);
8365 // Deal with output operands.
8366 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8367 if (OpInfo.Type == InlineAsm::isOutput) {
8369 // Skip trivial output operands.
8370 if (OpInfo.AssignedRegs.Regs.empty())
8373 switch (OpInfo.ConstraintType) {
8374 case TargetLowering::C_Register:
8375 case TargetLowering::C_RegisterClass:
8376 Val = OpInfo.AssignedRegs.getCopyFromRegs(
8377 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8379 case TargetLowering::C_Immediate:
8380 case TargetLowering::C_Other:
8381 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8384 case TargetLowering::C_Memory:
8385 break; // Already handled.
8386 case TargetLowering::C_Unknown:
8387 assert(false && "Unexpected unknown constraint");
8390 // Indirect output manifest as stores. Record output chains.
8391 if (OpInfo.isIndirect) {
8392 const Value *Ptr = OpInfo.CallOperandVal;
8393 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8394 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8395 MachinePointerInfo(Ptr));
8396 OutChains.push_back(Store);
8398 // generate CopyFromRegs to associated registers.
8399 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8400 if (Val.getOpcode() == ISD::MERGE_VALUES) {
8401 for (const SDValue &V : Val->op_values())
8404 handleRegAssign(Val);
8410 if (!ResultValues.empty()) {
8411 assert(CurResultType == ResultTypes.end() &&
8412 "Mismatch in number of ResultTypes");
8413 assert(ResultValues.size() == ResultTypes.size() &&
8414 "Mismatch in number of output operands in asm result");
8416 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8417 DAG.getVTList(ResultVTs), ResultValues);
8418 setValue(CS.getInstruction(), V);
8421 // Collect store chains.
8422 if (!OutChains.empty())
8423 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8425 // Only Update Root if inline assembly has a memory effect.
8426 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8430 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8431 const Twine &Message) {
8432 LLVMContext &Ctx = *DAG.getContext();
8433 Ctx.emitError(CS.getInstruction(), Message);
8435 // Make sure we leave the DAG in a valid state
8436 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8437 SmallVector<EVT, 1> ValueVTs;
8438 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8440 if (ValueVTs.empty())
8443 SmallVector<SDValue, 1> Ops;
8444 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8445 Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8447 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8450 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8451 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8452 MVT::Other, getRoot(),
8453 getValue(I.getArgOperand(0)),
8454 DAG.getSrcValue(I.getArgOperand(0))));
8457 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8458 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8459 const DataLayout &DL = DAG.getDataLayout();
8460 SDValue V = DAG.getVAArg(
8461 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8462 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8463 DL.getABITypeAlignment(I.getType()));
8464 DAG.setRoot(V.getValue(1));
8466 if (I.getType()->isPointerTy())
8467 V = DAG.getPtrExtOrTrunc(
8468 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8472 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8473 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8474 MVT::Other, getRoot(),
8475 getValue(I.getArgOperand(0)),
8476 DAG.getSrcValue(I.getArgOperand(0))));
8479 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8480 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8481 MVT::Other, getRoot(),
8482 getValue(I.getArgOperand(0)),
8483 getValue(I.getArgOperand(1)),
8484 DAG.getSrcValue(I.getArgOperand(0)),
8485 DAG.getSrcValue(I.getArgOperand(1))));
8488 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8489 const Instruction &I,
8491 const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8495 ConstantRange CR = getConstantRangeFromMetadata(*Range);
8496 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8499 APInt Lo = CR.getUnsignedMin();
8500 if (!Lo.isMinValue())
8503 APInt Hi = CR.getUnsignedMax();
8504 unsigned Bits = std::max(Hi.getActiveBits(),
8505 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8507 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8509 SDLoc SL = getCurSDLoc();
8511 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8512 DAG.getValueType(SmallVT));
8513 unsigned NumVals = Op.getNode()->getNumValues();
8517 SmallVector<SDValue, 4> Ops;
8519 Ops.push_back(ZExt);
8520 for (unsigned I = 1; I != NumVals; ++I)
8521 Ops.push_back(Op.getValue(I));
8523 return DAG.getMergeValues(Ops, SL);
8526 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8527 /// the call being lowered.
8529 /// This is a helper for lowering intrinsics that follow a target calling
8530 /// convention or require stack pointer adjustment. Only a subset of the
8531 /// intrinsic's operands need to participate in the calling convention.
8532 void SelectionDAGBuilder::populateCallLoweringInfo(
8533 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8534 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8535 bool IsPatchPoint) {
8536 TargetLowering::ArgListTy Args;
8537 Args.reserve(NumArgs);
8539 // Populate the argument list.
8540 // Attributes for args start at offset 1, after the return attribute.
8541 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8542 ArgI != ArgE; ++ArgI) {
8543 const Value *V = Call->getOperand(ArgI);
8545 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8547 TargetLowering::ArgListEntry Entry;
8548 Entry.Node = getValue(V);
8549 Entry.Ty = V->getType();
8550 Entry.setAttributes(Call, ArgI);
8551 Args.push_back(Entry);
8554 CLI.setDebugLoc(getCurSDLoc())
8555 .setChain(getRoot())
8556 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8557 .setDiscardResult(Call->use_empty())
8558 .setIsPatchPoint(IsPatchPoint);
8561 /// Add a stack map intrinsic call's live variable operands to a stackmap
8562 /// or patchpoint target node's operand list.
8564 /// Constants are converted to TargetConstants purely as an optimization to
8565 /// avoid constant materialization and register allocation.
8567 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8568 /// generate addess computation nodes, and so FinalizeISel can convert the
8569 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8570 /// address materialization and register allocation, but may also be required
8571 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8572 /// alloca in the entry block, then the runtime may assume that the alloca's
8573 /// StackMap location can be read immediately after compilation and that the
8574 /// location is valid at any point during execution (this is similar to the
8575 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8576 /// only available in a register, then the runtime would need to trap when
8577 /// execution reaches the StackMap in order to read the alloca's location.
8578 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8579 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8580 SelectionDAGBuilder &Builder) {
8581 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8582 SDValue OpVal = Builder.getValue(CS.getArgument(i));
8583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8585 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8587 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8588 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8589 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8590 Ops.push_back(Builder.DAG.getTargetFrameIndex(
8591 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8593 Ops.push_back(OpVal);
8597 /// Lower llvm.experimental.stackmap directly to its target opcode.
8598 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8599 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8600 // [live variables...])
8602 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8604 SDValue Chain, InFlag, Callee, NullPtr;
8605 SmallVector<SDValue, 32> Ops;
8607 SDLoc DL = getCurSDLoc();
8608 Callee = getValue(CI.getCalledValue());
8609 NullPtr = DAG.getIntPtrConstant(0, DL, true);
8611 // The stackmap intrinsic only records the live variables (the arguemnts
8612 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8613 // intrinsic, this won't be lowered to a function call. This means we don't
8614 // have to worry about calling conventions and target specific lowering code.
8615 // Instead we perform the call lowering right here.
8617 // chain, flag = CALLSEQ_START(chain, 0, 0)
8618 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8619 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8621 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8622 InFlag = Chain.getValue(1);
8624 // Add the <id> and <numBytes> constants.
8625 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8626 Ops.push_back(DAG.getTargetConstant(
8627 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8628 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8629 Ops.push_back(DAG.getTargetConstant(
8630 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8633 // Push live variables for the stack map.
8634 addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8636 // We are not pushing any register mask info here on the operands list,
8637 // because the stackmap doesn't clobber anything.
8639 // Push the chain and the glue flag.
8640 Ops.push_back(Chain);
8641 Ops.push_back(InFlag);
8643 // Create the STACKMAP node.
8644 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8645 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8646 Chain = SDValue(SM, 0);
8647 InFlag = Chain.getValue(1);
8649 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8651 // Stackmaps don't generate values, so nothing goes into the NodeMap.
8653 // Set the root to the target-lowered call chain.
8656 // Inform the Frame Information that we have a stackmap in this function.
8657 FuncInfo.MF->getFrameInfo().setHasStackMap();
8660 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8661 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8662 const BasicBlock *EHPadBB) {
8663 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8668 // [live variables...])
8670 CallingConv::ID CC = CS.getCallingConv();
8671 bool IsAnyRegCC = CC == CallingConv::AnyReg;
8672 bool HasDef = !CS->getType()->isVoidTy();
8673 SDLoc dl = getCurSDLoc();
8674 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8676 // Handle immediate and symbolic callees.
8677 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8678 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8680 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8681 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8682 SDLoc(SymbolicCallee),
8683 SymbolicCallee->getValueType(0));
8685 // Get the real number of arguments participating in the call <numArgs>
8686 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8687 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8689 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8690 // Intrinsics include all meta-operands up to but not including CC.
8691 unsigned NumMetaOpers = PatchPointOpers::CCPos;
8692 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8693 "Not enough arguments provided to the patchpoint intrinsic");
8695 // For AnyRegCC the arguments are lowered later on manually.
8696 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8698 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8700 TargetLowering::CallLoweringInfo CLI(DAG);
8701 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8702 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8703 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8705 SDNode *CallEnd = Result.second.getNode();
8706 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8707 CallEnd = CallEnd->getOperand(0).getNode();
8709 /// Get a call instruction from the call sequence chain.
8710 /// Tail calls are not allowed.
8711 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8712 "Expected a callseq node.");
8713 SDNode *Call = CallEnd->getOperand(0).getNode();
8714 bool HasGlue = Call->getGluedNode();
8716 // Replace the target specific call node with the patchable intrinsic.
8717 SmallVector<SDValue, 8> Ops;
8719 // Add the <id> and <numBytes> constants.
8720 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8721 Ops.push_back(DAG.getTargetConstant(
8722 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8723 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8724 Ops.push_back(DAG.getTargetConstant(
8725 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8729 Ops.push_back(Callee);
8731 // Adjust <numArgs> to account for any arguments that have been passed on the
8733 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8734 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8735 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8736 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8738 // Add the calling convention
8739 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8741 // Add the arguments we omitted previously. The register allocator should
8742 // place these in any free register.
8744 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8745 Ops.push_back(getValue(CS.getArgument(i)));
8747 // Push the arguments from the call instruction up to the register mask.
8748 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8749 Ops.append(Call->op_begin() + 2, e);
8751 // Push live variables for the stack map.
8752 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8754 // Push the register mask info.
8756 Ops.push_back(*(Call->op_end()-2));
8758 Ops.push_back(*(Call->op_end()-1));
8760 // Push the chain (this is originally the first operand of the call, but
8761 // becomes now the last or second to last operand).
8762 Ops.push_back(*(Call->op_begin()));
8764 // Push the glue flag (last operand).
8766 Ops.push_back(*(Call->op_end()-1));
8769 if (IsAnyRegCC && HasDef) {
8770 // Create the return types based on the intrinsic definition
8771 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8772 SmallVector<EVT, 3> ValueVTs;
8773 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8774 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8776 // There is always a chain and a glue type at the end
8777 ValueVTs.push_back(MVT::Other);
8778 ValueVTs.push_back(MVT::Glue);
8779 NodeTys = DAG.getVTList(ValueVTs);
8781 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8783 // Replace the target specific call node with a PATCHPOINT node.
8784 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8787 // Update the NodeMap.
8790 setValue(CS.getInstruction(), SDValue(MN, 0));
8792 setValue(CS.getInstruction(), Result.first);
8795 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8796 // call sequence. Furthermore the location of the chain and glue can change
8797 // when the AnyReg calling convention is used and the intrinsic returns a
8799 if (IsAnyRegCC && HasDef) {
8800 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8801 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8802 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8804 DAG.ReplaceAllUsesWith(Call, MN);
8805 DAG.DeleteNode(Call);
8807 // Inform the Frame Information that we have a patchpoint in this function.
8808 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8811 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8812 unsigned Intrinsic) {
8813 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8814 SDValue Op1 = getValue(I.getArgOperand(0));
8816 if (I.getNumArgOperands() > 1)
8817 Op2 = getValue(I.getArgOperand(1));
8818 SDLoc dl = getCurSDLoc();
8819 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8822 if (isa<FPMathOperator>(I))
8823 FMF = I.getFastMathFlags();
8825 switch (Intrinsic) {
8826 case Intrinsic::experimental_vector_reduce_v2_fadd:
8827 if (FMF.allowReassoc())
8828 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8829 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8831 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8833 case Intrinsic::experimental_vector_reduce_v2_fmul:
8834 if (FMF.allowReassoc())
8835 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8836 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8838 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8840 case Intrinsic::experimental_vector_reduce_add:
8841 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8843 case Intrinsic::experimental_vector_reduce_mul:
8844 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8846 case Intrinsic::experimental_vector_reduce_and:
8847 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8849 case Intrinsic::experimental_vector_reduce_or:
8850 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8852 case Intrinsic::experimental_vector_reduce_xor:
8853 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8855 case Intrinsic::experimental_vector_reduce_smax:
8856 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8858 case Intrinsic::experimental_vector_reduce_smin:
8859 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8861 case Intrinsic::experimental_vector_reduce_umax:
8862 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8864 case Intrinsic::experimental_vector_reduce_umin:
8865 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8867 case Intrinsic::experimental_vector_reduce_fmax:
8868 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8870 case Intrinsic::experimental_vector_reduce_fmin:
8871 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8874 llvm_unreachable("Unhandled vector reduce intrinsic");
8879 /// Returns an AttributeList representing the attributes applied to the return
8880 /// value of the given call.
8881 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8882 SmallVector<Attribute::AttrKind, 2> Attrs;
8884 Attrs.push_back(Attribute::SExt);
8886 Attrs.push_back(Attribute::ZExt);
8888 Attrs.push_back(Attribute::InReg);
8890 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8894 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8895 /// implementation, which just calls LowerCall.
8896 /// FIXME: When all targets are
8897 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8898 std::pair<SDValue, SDValue>
8899 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8900 // Handle the incoming return values from the call.
8902 Type *OrigRetTy = CLI.RetTy;
8903 SmallVector<EVT, 4> RetTys;
8904 SmallVector<uint64_t, 4> Offsets;
8905 auto &DL = CLI.DAG.getDataLayout();
8906 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8908 if (CLI.IsPostTypeLegalization) {
8909 // If we are lowering a libcall after legalization, split the return type.
8910 SmallVector<EVT, 4> OldRetTys;
8911 SmallVector<uint64_t, 4> OldOffsets;
8912 RetTys.swap(OldRetTys);
8913 Offsets.swap(OldOffsets);
8915 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8916 EVT RetVT = OldRetTys[i];
8917 uint64_t Offset = OldOffsets[i];
8918 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8919 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8920 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8921 RetTys.append(NumRegs, RegisterVT);
8922 for (unsigned j = 0; j != NumRegs; ++j)
8923 Offsets.push_back(Offset + j * RegisterVTByteSZ);
8927 SmallVector<ISD::OutputArg, 4> Outs;
8928 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8930 bool CanLowerReturn =
8931 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8932 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8934 SDValue DemoteStackSlot;
8935 int DemoteStackIdx = -100;
8936 if (!CanLowerReturn) {
8937 // FIXME: equivalent assert?
8938 // assert(!CS.hasInAllocaArgument() &&
8939 // "sret demotion is incompatible with inalloca");
8940 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8941 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8942 MachineFunction &MF = CLI.DAG.getMachineFunction();
8943 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8944 Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8945 DL.getAllocaAddrSpace());
8947 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8949 Entry.Node = DemoteStackSlot;
8950 Entry.Ty = StackSlotPtrType;
8951 Entry.IsSExt = false;
8952 Entry.IsZExt = false;
8953 Entry.IsInReg = false;
8954 Entry.IsSRet = true;
8955 Entry.IsNest = false;
8956 Entry.IsByVal = false;
8957 Entry.IsReturned = false;
8958 Entry.IsSwiftSelf = false;
8959 Entry.IsSwiftError = false;
8960 Entry.Alignment = Align;
8961 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8962 CLI.NumFixedArgs += 1;
8963 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8965 // sret demotion isn't compatible with tail-calls, since the sret argument
8966 // points into the callers stack frame.
8967 CLI.IsTailCall = false;
8969 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8970 CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
8971 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8972 ISD::ArgFlagsTy Flags;
8973 if (NeedsRegBlock) {
8974 Flags.setInConsecutiveRegs();
8975 if (I == RetTys.size() - 1)
8976 Flags.setInConsecutiveRegsLast();
8979 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8981 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8983 for (unsigned i = 0; i != NumRegs; ++i) {
8984 ISD::InputArg MyFlags;
8985 MyFlags.Flags = Flags;
8986 MyFlags.VT = RegisterVT;
8988 MyFlags.Used = CLI.IsReturnValueUsed;
8989 if (CLI.RetTy->isPointerTy()) {
8990 MyFlags.Flags.setPointer();
8991 MyFlags.Flags.setPointerAddrSpace(
8992 cast<PointerType>(CLI.RetTy)->getAddressSpace());
8995 MyFlags.Flags.setSExt();
8997 MyFlags.Flags.setZExt();
8999 MyFlags.Flags.setInReg();
9000 CLI.Ins.push_back(MyFlags);
9005 // We push in swifterror return as the last element of CLI.Ins.
9006 ArgListTy &Args = CLI.getArgs();
9007 if (supportSwiftError()) {
9008 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9009 if (Args[i].IsSwiftError) {
9010 ISD::InputArg MyFlags;
9011 MyFlags.VT = getPointerTy(DL);
9012 MyFlags.ArgVT = EVT(getPointerTy(DL));
9013 MyFlags.Flags.setSwiftError();
9014 CLI.Ins.push_back(MyFlags);
9019 // Handle all of the outgoing arguments.
9021 CLI.OutVals.clear();
9022 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9023 SmallVector<EVT, 4> ValueVTs;
9024 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9025 // FIXME: Split arguments if CLI.IsPostTypeLegalization
9026 Type *FinalType = Args[i].Ty;
9027 if (Args[i].IsByVal)
9028 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9029 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9030 FinalType, CLI.CallConv, CLI.IsVarArg);
9031 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9033 EVT VT = ValueVTs[Value];
9034 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9035 SDValue Op = SDValue(Args[i].Node.getNode(),
9036 Args[i].Node.getResNo() + Value);
9037 ISD::ArgFlagsTy Flags;
9039 // Certain targets (such as MIPS), may have a different ABI alignment
9040 // for a type depending on the context. Give the target a chance to
9041 // specify the alignment it wants.
9042 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
9044 if (Args[i].Ty->isPointerTy()) {
9046 Flags.setPointerAddrSpace(
9047 cast<PointerType>(Args[i].Ty)->getAddressSpace());
9053 if (Args[i].IsInReg) {
9054 // If we are using vectorcall calling convention, a structure that is
9055 // passed InReg - is surely an HVA
9056 if (CLI.CallConv == CallingConv::X86_VectorCall &&
9057 isa<StructType>(FinalType)) {
9058 // The first value of a structure is marked
9060 Flags.setHvaStart();
9068 if (Args[i].IsSwiftSelf)
9069 Flags.setSwiftSelf();
9070 if (Args[i].IsSwiftError)
9071 Flags.setSwiftError();
9072 if (Args[i].IsByVal)
9074 if (Args[i].IsInAlloca) {
9075 Flags.setInAlloca();
9076 // Set the byval flag for CCAssignFn callbacks that don't know about
9077 // inalloca. This way we can know how many bytes we should've allocated
9078 // and how many bytes a callee cleanup function will pop. If we port
9079 // inalloca to more targets, we'll have to add custom inalloca handling
9080 // in the various CC lowering callbacks.
9083 if (Args[i].IsByVal || Args[i].IsInAlloca) {
9084 PointerType *Ty = cast<PointerType>(Args[i].Ty);
9085 Type *ElementTy = Ty->getElementType();
9087 unsigned FrameSize = DL.getTypeAllocSize(
9088 Args[i].ByValType ? Args[i].ByValType : ElementTy);
9089 Flags.setByValSize(FrameSize);
9091 // info is not there but there are cases it cannot get right.
9092 unsigned FrameAlign;
9093 if (Args[i].Alignment)
9094 FrameAlign = Args[i].Alignment;
9096 FrameAlign = getByValTypeAlignment(ElementTy, DL);
9097 Flags.setByValAlign(FrameAlign);
9102 Flags.setInConsecutiveRegs();
9103 Flags.setOrigAlign(OriginalAlignment);
9105 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9107 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9109 SmallVector<SDValue, 4> Parts(NumParts);
9110 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9113 ExtendKind = ISD::SIGN_EXTEND;
9114 else if (Args[i].IsZExt)
9115 ExtendKind = ISD::ZERO_EXTEND;
9117 // Conservatively only handle 'returned' on non-vectors that can be lowered,
9119 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9121 assert((CLI.RetTy == Args[i].Ty ||
9122 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9123 CLI.RetTy->getPointerAddressSpace() ==
9124 Args[i].Ty->getPointerAddressSpace())) &&
9125 RetTys.size() == NumValues && "unexpected use of 'returned'");
9126 // Before passing 'returned' to the target lowering code, ensure that
9127 // either the register MVT and the actual EVT are the same size or that
9128 // the return value and argument are extended in the same way; in these
9129 // cases it's safe to pass the argument register value unchanged as the
9130 // return register value (although it's at the target's option whether
9132 // TODO: allow code generation to take advantage of partially preserved
9133 // registers rather than clobbering the entire register when the
9134 // parameter extension method is not compatible with the return
9136 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9137 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9138 CLI.RetZExt == Args[i].IsZExt))
9139 Flags.setReturned();
9142 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9143 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9145 for (unsigned j = 0; j != NumParts; ++j) {
9146 // if it isn't first piece, alignment must be 1
9147 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9148 i < CLI.NumFixedArgs,
9149 i, j*Parts[j].getValueType().getStoreSize());
9150 if (NumParts > 1 && j == 0)
9151 MyFlags.Flags.setSplit();
9153 MyFlags.Flags.setOrigAlign(1);
9154 if (j == NumParts - 1)
9155 MyFlags.Flags.setSplitEnd();
9158 CLI.Outs.push_back(MyFlags);
9159 CLI.OutVals.push_back(Parts[j]);
9162 if (NeedsRegBlock && Value == NumValues - 1)
9163 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9167 SmallVector<SDValue, 4> InVals;
9168 CLI.Chain = LowerCall(CLI, InVals);
9170 // Update CLI.InVals to use outside of this function.
9171 CLI.InVals = InVals;
9173 // Verify that the target's LowerCall behaved as expected.
9174 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9175 "LowerCall didn't return a valid chain!");
9176 assert((!CLI.IsTailCall || InVals.empty()) &&
9177 "LowerCall emitted a return value for a tail call!");
9178 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9179 "LowerCall didn't emit the correct number of values!");
9181 // For a tail call, the return value is merely live-out and there aren't
9182 // any nodes in the DAG representing it. Return a special value to
9183 // indicate that a tail call has been emitted and no more Instructions
9184 // should be processed in the current block.
9185 if (CLI.IsTailCall) {
9186 CLI.DAG.setRoot(CLI.Chain);
9187 return std::make_pair(SDValue(), SDValue());
9191 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9192 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9193 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9194 "LowerCall emitted a value with the wrong type!");
9198 SmallVector<SDValue, 4> ReturnValues;
9199 if (!CanLowerReturn) {
9200 // The instruction result is the result of loading from the
9201 // hidden sret parameter.
9202 SmallVector<EVT, 1> PVTs;
9203 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9205 ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9206 assert(PVTs.size() == 1 && "Pointers should fit in one register");
9207 EVT PtrVT = PVTs[0];
9209 unsigned NumValues = RetTys.size();
9210 ReturnValues.resize(NumValues);
9211 SmallVector<SDValue, 4> Chains(NumValues);
9213 // An aggregate return value cannot wrap around the address space, so
9214 // offsets to its parts don't wrap either.
9216 Flags.setNoUnsignedWrap(true);
9218 for (unsigned i = 0; i < NumValues; ++i) {
9219 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9220 CLI.DAG.getConstant(Offsets[i], CLI.DL,
9222 SDValue L = CLI.DAG.getLoad(
9223 RetTys[i], CLI.DL, CLI.Chain, Add,
9224 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9225 DemoteStackIdx, Offsets[i]),
9226 /* Alignment = */ 1);
9227 ReturnValues[i] = L;
9228 Chains[i] = L.getValue(1);
9231 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9233 // Collect the legal value parts into potentially illegal values
9234 // that correspond to the original function's return values.
9235 Optional<ISD::NodeType> AssertOp;
9237 AssertOp = ISD::AssertSext;
9238 else if (CLI.RetZExt)
9239 AssertOp = ISD::AssertZext;
9240 unsigned CurReg = 0;
9241 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9243 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9245 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9248 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9249 NumRegs, RegisterVT, VT, nullptr,
9250 CLI.CallConv, AssertOp));
9254 // For a function returning void, there is no return value. We can't create
9255 // such a node, so we just return a null return value in that case. In
9256 // that case, nothing will actually look at the value.
9257 if (ReturnValues.empty())
9258 return std::make_pair(SDValue(), CLI.Chain);
9261 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9262 CLI.DAG.getVTList(RetTys), ReturnValues);
9263 return std::make_pair(Res, CLI.Chain);
9266 void TargetLowering::LowerOperationWrapper(SDNode *N,
9267 SmallVectorImpl<SDValue> &Results,
9268 SelectionDAG &DAG) const {
9269 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9270 Results.push_back(Res);
9273 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9274 llvm_unreachable("LowerOperation not implemented for this target!");
9278 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9279 SDValue Op = getNonRegisterValue(V);
9280 assert((Op.getOpcode() != ISD::CopyFromReg ||
9281 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9282 "Copy from a reg to the same reg!");
9283 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
9285 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9286 // If this is an InlineAsm we have to match the registers required, not the
9287 // notional registers required by the type.
9289 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9290 None); // This is not an ABI copy.
9291 SDValue Chain = DAG.getEntryNode();
9293 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9294 FuncInfo.PreferredExtendType.end())
9296 : FuncInfo.PreferredExtendType[V];
9297 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9298 PendingExports.push_back(Chain);
9301 #include "llvm/CodeGen/SelectionDAGISel.h"
9303 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9304 /// entry block, return true. This includes arguments used by switches, since
9305 /// the switch may expand into multiple basic blocks.
9306 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9307 // With FastISel active, we may be splitting blocks, so force creation
9308 // of virtual registers for all non-dead arguments.
9310 return A->use_empty();
9312 const BasicBlock &Entry = A->getParent()->front();
9313 for (const User *U : A->users())
9314 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9315 return false; // Use not in entry block.
9320 using ArgCopyElisionMapTy =
9321 DenseMap<const Argument *,
9322 std::pair<const AllocaInst *, const StoreInst *>>;
9324 /// Scan the entry block of the function in FuncInfo for arguments that look
9325 /// like copies into a local alloca. Record any copied arguments in
9326 /// ArgCopyElisionCandidates.
9328 findArgumentCopyElisionCandidates(const DataLayout &DL,
9329 FunctionLoweringInfo *FuncInfo,
9330 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9331 // Record the state of every static alloca used in the entry block. Argument
9332 // allocas are all used in the entry block, so we need approximately as many
9333 // entries as we have arguments.
9334 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9335 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9336 unsigned NumArgs = FuncInfo->Fn->arg_size();
9337 StaticAllocas.reserve(NumArgs * 2);
9339 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9342 V = V->stripPointerCasts();
9343 const auto *AI = dyn_cast<AllocaInst>(V);
9344 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9346 auto Iter = StaticAllocas.insert({AI, Unknown});
9347 return &Iter.first->second;
9350 // Look for stores of arguments to static allocas. Look through bitcasts and
9351 // GEPs to handle type coercions, as long as the alloca is fully initialized
9352 // by the store. Any non-store use of an alloca escapes it and any subsequent
9353 // unanalyzed store might write it.
9354 // FIXME: Handle structs initialized with multiple stores.
9355 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9356 // Look for stores, and handle non-store uses conservatively.
9357 const auto *SI = dyn_cast<StoreInst>(&I);
9359 // We will look through cast uses, so ignore them completely.
9362 // Ignore debug info intrinsics, they don't escape or store to allocas.
9363 if (isa<DbgInfoIntrinsic>(I))
9365 // This is an unknown instruction. Assume it escapes or writes to all
9366 // static alloca operands.
9367 for (const Use &U : I.operands()) {
9368 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9369 *Info = StaticAllocaInfo::Clobbered;
9374 // If the stored value is a static alloca, mark it as escaped.
9375 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9376 *Info = StaticAllocaInfo::Clobbered;
9378 // Check if the destination is a static alloca.
9379 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9380 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9383 const AllocaInst *AI = cast<AllocaInst>(Dst);
9385 // Skip allocas that have been initialized or clobbered.
9386 if (*Info != StaticAllocaInfo::Unknown)
9389 // Check if the stored value is an argument, and that this store fully
9390 // initializes the alloca. Don't elide copies from the same argument twice.
9391 const Value *Val = SI->getValueOperand()->stripPointerCasts();
9392 const auto *Arg = dyn_cast<Argument>(Val);
9393 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9394 Arg->getType()->isEmptyTy() ||
9395 DL.getTypeStoreSize(Arg->getType()) !=
9396 DL.getTypeAllocSize(AI->getAllocatedType()) ||
9397 ArgCopyElisionCandidates.count(Arg)) {
9398 *Info = StaticAllocaInfo::Clobbered;
9402 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9405 // Mark this alloca and store for argument copy elision.
9406 *Info = StaticAllocaInfo::Elidable;
9407 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9409 // Stop scanning if we've seen all arguments. This will happen early in -O0
9410 // builds, which is useful, because -O0 builds have large entry blocks and
9412 if (ArgCopyElisionCandidates.size() == NumArgs)
9417 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9418 /// ArgVal is a load from a suitable fixed stack object.
9419 static void tryToElideArgumentCopy(
9420 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9421 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9422 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9423 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9424 SDValue ArgVal, bool &ArgHasUses) {
9425 // Check if this is a load from a fixed stack object.
9426 auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9429 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9433 // Check that the fixed stack object is the right size and alignment.
9434 // Look at the alignment that the user wrote on the alloca instead of looking
9435 // at the stack object.
9436 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9437 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9438 const AllocaInst *AI = ArgCopyIter->second.first;
9439 int FixedIndex = FINode->getIndex();
9440 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9441 int OldIndex = AllocaIndex;
9442 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9443 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9445 dbgs() << " argument copy elision failed due to bad fixed stack "
9449 unsigned RequiredAlignment = AI->getAlignment();
9450 if (!RequiredAlignment) {
9451 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9452 AI->getAllocatedType());
9454 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9455 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
9456 "greater than stack argument alignment ("
9457 << RequiredAlignment << " vs "
9458 << MFI.getObjectAlignment(FixedIndex) << ")\n");
9462 // Perform the elision. Delete the old stack object and replace its only use
9463 // in the variable info map. Mark the stack object as mutable.
9465 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9466 << " Replacing frame index " << OldIndex << " with " << FixedIndex
9469 MFI.RemoveStackObject(OldIndex);
9470 MFI.setIsImmutableObjectIndex(FixedIndex, false);
9471 AllocaIndex = FixedIndex;
9472 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9473 Chains.push_back(ArgVal.getValue(1));
9475 // Avoid emitting code for the store implementing the copy.
9476 const StoreInst *SI = ArgCopyIter->second.second;
9477 ElidedArgCopyInstrs.insert(SI);
9479 // Check for uses of the argument again so that we can avoid exporting ArgVal
9480 // if it is't used by anything other than the store.
9481 for (const Value *U : Arg.users()) {
9489 void SelectionDAGISel::LowerArguments(const Function &F) {
9490 SelectionDAG &DAG = SDB->DAG;
9491 SDLoc dl = SDB->getCurSDLoc();
9492 const DataLayout &DL = DAG.getDataLayout();
9493 SmallVector<ISD::InputArg, 16> Ins;
9495 if (!FuncInfo->CanLowerReturn) {
9496 // Put in an sret pointer parameter before all the other parameters.
9497 SmallVector<EVT, 1> ValueVTs;
9498 ComputeValueVTs(*TLI, DAG.getDataLayout(),
9499 F.getReturnType()->getPointerTo(
9500 DAG.getDataLayout().getAllocaAddrSpace()),
9503 // NOTE: Assuming that a pointer will never break down to more than one VT
9505 ISD::ArgFlagsTy Flags;
9507 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9508 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9509 ISD::InputArg::NoArgIndex, 0);
9510 Ins.push_back(RetArg);
9513 // Look for stores of arguments to static allocas. Mark such arguments with a
9514 // flag to ask the target to give us the memory location of that argument if
9516 ArgCopyElisionMapTy ArgCopyElisionCandidates;
9517 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9519 // Set up the incoming argument description vector.
9520 for (const Argument &Arg : F.args()) {
9521 unsigned ArgNo = Arg.getArgNo();
9522 SmallVector<EVT, 4> ValueVTs;
9523 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9524 bool isArgValueUsed = !Arg.use_empty();
9525 unsigned PartBase = 0;
9526 Type *FinalType = Arg.getType();
9527 if (Arg.hasAttribute(Attribute::ByVal))
9528 FinalType = Arg.getParamByValType();
9529 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9530 FinalType, F.getCallingConv(), F.isVarArg());
9531 for (unsigned Value = 0, NumValues = ValueVTs.size();
9532 Value != NumValues; ++Value) {
9533 EVT VT = ValueVTs[Value];
9534 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9535 ISD::ArgFlagsTy Flags;
9537 // Certain targets (such as MIPS), may have a different ABI alignment
9538 // for a type depending on the context. Give the target a chance to
9539 // specify the alignment it wants.
9540 unsigned OriginalAlignment =
9541 TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9543 if (Arg.getType()->isPointerTy()) {
9545 Flags.setPointerAddrSpace(
9546 cast<PointerType>(Arg.getType())->getAddressSpace());
9548 if (Arg.hasAttribute(Attribute::ZExt))
9550 if (Arg.hasAttribute(Attribute::SExt))
9552 if (Arg.hasAttribute(Attribute::InReg)) {
9553 // If we are using vectorcall calling convention, a structure that is
9554 // passed InReg - is surely an HVA
9555 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9556 isa<StructType>(Arg.getType())) {
9557 // The first value of a structure is marked
9559 Flags.setHvaStart();
9565 if (Arg.hasAttribute(Attribute::StructRet))
9567 if (Arg.hasAttribute(Attribute::SwiftSelf))
9568 Flags.setSwiftSelf();
9569 if (Arg.hasAttribute(Attribute::SwiftError))
9570 Flags.setSwiftError();
9571 if (Arg.hasAttribute(Attribute::ByVal))
9573 if (Arg.hasAttribute(Attribute::InAlloca)) {
9574 Flags.setInAlloca();
9575 // Set the byval flag for CCAssignFn callbacks that don't know about
9576 // inalloca. This way we can know how many bytes we should've allocated
9577 // and how many bytes a callee cleanup function will pop. If we port
9578 // inalloca to more targets, we'll have to add custom inalloca handling
9579 // in the various CC lowering callbacks.
9582 if (F.getCallingConv() == CallingConv::X86_INTR) {
9583 // IA Interrupt passes frame (1st parameter) by value in the stack.
9587 if (Flags.isByVal() || Flags.isInAlloca()) {
9588 Type *ElementTy = Arg.getParamByValType();
9590 // For ByVal, size and alignment should be passed from FE. BE will
9591 // guess if this info is not there but there are cases it cannot get
9593 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9594 Flags.setByValSize(FrameSize);
9596 unsigned FrameAlign;
9597 if (Arg.getParamAlignment())
9598 FrameAlign = Arg.getParamAlignment();
9600 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9601 Flags.setByValAlign(FrameAlign);
9603 if (Arg.hasAttribute(Attribute::Nest))
9606 Flags.setInConsecutiveRegs();
9607 Flags.setOrigAlign(OriginalAlignment);
9608 if (ArgCopyElisionCandidates.count(&Arg))
9609 Flags.setCopyElisionCandidate();
9611 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9612 *CurDAG->getContext(), F.getCallingConv(), VT);
9613 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9614 *CurDAG->getContext(), F.getCallingConv(), VT);
9615 for (unsigned i = 0; i != NumRegs; ++i) {
9616 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9617 ArgNo, PartBase+i*RegisterVT.getStoreSize());
9618 if (NumRegs > 1 && i == 0)
9619 MyFlags.Flags.setSplit();
9620 // if it isn't first piece, alignment must be 1
9622 MyFlags.Flags.setOrigAlign(1);
9623 if (i == NumRegs - 1)
9624 MyFlags.Flags.setSplitEnd();
9626 Ins.push_back(MyFlags);
9628 if (NeedsRegBlock && Value == NumValues - 1)
9629 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9630 PartBase += VT.getStoreSize();
9634 // Call the target to set up the argument values.
9635 SmallVector<SDValue, 8> InVals;
9636 SDValue NewRoot = TLI->LowerFormalArguments(
9637 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9639 // Verify that the target's LowerFormalArguments behaved as expected.
9640 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9641 "LowerFormalArguments didn't return a valid chain!");
9642 assert(InVals.size() == Ins.size() &&
9643 "LowerFormalArguments didn't emit the correct number of values!");
9645 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9646 assert(InVals[i].getNode() &&
9647 "LowerFormalArguments emitted a null value!");
9648 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9649 "LowerFormalArguments emitted a value with the wrong type!");
9653 // Update the DAG with the new chain value resulting from argument lowering.
9654 DAG.setRoot(NewRoot);
9656 // Set up the argument values.
9658 if (!FuncInfo->CanLowerReturn) {
9659 // Create a virtual register for the sret pointer, and put in a copy
9660 // from the sret argument into it.
9661 SmallVector<EVT, 1> ValueVTs;
9662 ComputeValueVTs(*TLI, DAG.getDataLayout(),
9663 F.getReturnType()->getPointerTo(
9664 DAG.getDataLayout().getAllocaAddrSpace()),
9666 MVT VT = ValueVTs[0].getSimpleVT();
9667 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9668 Optional<ISD::NodeType> AssertOp = None;
9669 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9670 nullptr, F.getCallingConv(), AssertOp);
9672 MachineFunction& MF = SDB->DAG.getMachineFunction();
9673 MachineRegisterInfo& RegInfo = MF.getRegInfo();
9674 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9675 FuncInfo->DemoteRegister = SRetReg;
9677 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9678 DAG.setRoot(NewRoot);
9680 // i indexes lowered arguments. Bump it past the hidden sret argument.
9684 SmallVector<SDValue, 4> Chains;
9685 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9686 for (const Argument &Arg : F.args()) {
9687 SmallVector<SDValue, 4> ArgValues;
9688 SmallVector<EVT, 4> ValueVTs;
9689 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9690 unsigned NumValues = ValueVTs.size();
9694 bool ArgHasUses = !Arg.use_empty();
9696 // Elide the copying store if the target loaded this argument from a
9697 // suitable fixed stack object.
9698 if (Ins[i].Flags.isCopyElisionCandidate()) {
9699 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9700 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9701 InVals[i], ArgHasUses);
9704 // If this argument is unused then remember its value. It is used to generate
9705 // debugging information.
9706 bool isSwiftErrorArg =
9707 TLI->supportSwiftError() &&
9708 Arg.hasAttribute(Attribute::SwiftError);
9709 if (!ArgHasUses && !isSwiftErrorArg) {
9710 SDB->setUnusedArgValue(&Arg, InVals[i]);
9712 // Also remember any frame index for use in FastISel.
9713 if (FrameIndexSDNode *FI =
9714 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9715 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9718 for (unsigned Val = 0; Val != NumValues; ++Val) {
9719 EVT VT = ValueVTs[Val];
9720 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9721 F.getCallingConv(), VT);
9722 unsigned NumParts = TLI->getNumRegistersForCallingConv(
9723 *CurDAG->getContext(), F.getCallingConv(), VT);
9725 // Even an apparant 'unused' swifterror argument needs to be returned. So
9726 // we do generate a copy for it that can be used on return from the
9728 if (ArgHasUses || isSwiftErrorArg) {
9729 Optional<ISD::NodeType> AssertOp;
9730 if (Arg.hasAttribute(Attribute::SExt))
9731 AssertOp = ISD::AssertSext;
9732 else if (Arg.hasAttribute(Attribute::ZExt))
9733 AssertOp = ISD::AssertZext;
9735 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9736 PartVT, VT, nullptr,
9737 F.getCallingConv(), AssertOp));
9743 // We don't need to do anything else for unused arguments.
9744 if (ArgValues.empty())
9747 // Note down frame index.
9748 if (FrameIndexSDNode *FI =
9749 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9750 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9752 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9753 SDB->getCurSDLoc());
9755 SDB->setValue(&Arg, Res);
9756 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9757 // We want to associate the argument with the frame index, among
9758 // involved operands, that correspond to the lowest address. The
9759 // getCopyFromParts function, called earlier, is swapping the order of
9760 // the operands to BUILD_PAIR depending on endianness. The result of
9761 // that swapping is that the least significant bits of the argument will
9762 // be in the first operand of the BUILD_PAIR node, and the most
9763 // significant bits will be in the second operand.
9764 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9765 if (LoadSDNode *LNode =
9766 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9767 if (FrameIndexSDNode *FI =
9768 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9769 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9772 // Update the SwiftErrorVRegDefMap.
9773 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9774 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9775 if (TargetRegisterInfo::isVirtualRegister(Reg))
9776 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9780 // If this argument is live outside of the entry block, insert a copy from
9781 // wherever we got it to the vreg that other BB's will reference it as.
9782 if (Res.getOpcode() == ISD::CopyFromReg) {
9783 // If we can, though, try to skip creating an unnecessary vreg.
9784 // FIXME: This isn't very clean... it would be nice to make this more
9786 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9787 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9788 FuncInfo->ValueMap[&Arg] = Reg;
9792 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9793 FuncInfo->InitializeRegForValue(&Arg);
9794 SDB->CopyToExportRegsIfNeeded(&Arg);
9798 if (!Chains.empty()) {
9799 Chains.push_back(NewRoot);
9800 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9803 DAG.setRoot(NewRoot);
9805 assert(i == InVals.size() && "Argument register count mismatch!");
9807 // If any argument copy elisions occurred and we have debug info, update the
9808 // stale frame indices used in the dbg.declare variable info table.
9809 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9810 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9811 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9812 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9813 if (I != ArgCopyElisionFrameIndexMap.end())
9814 VI.Slot = I->second;
9818 // Finally, if the target has anything special to do, allow it to do so.
9819 EmitFunctionEntryCode();
9822 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
9823 /// ensure constants are generated when needed. Remember the virtual registers
9824 /// that need to be added to the Machine PHI nodes as input. We cannot just
9825 /// directly add them, because expansion might result in multiple MBB's for one
9826 /// BB. As such, the start of the BB might correspond to a different MBB than
9829 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9830 const Instruction *TI = LLVMBB->getTerminator();
9832 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9834 // Check PHI nodes in successors that expect a value to be available from this
9836 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9837 const BasicBlock *SuccBB = TI->getSuccessor(succ);
9838 if (!isa<PHINode>(SuccBB->begin())) continue;
9839 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9841 // If this terminator has multiple identical successors (common for
9842 // switches), only handle each succ once.
9843 if (!SuccsHandled.insert(SuccMBB).second)
9846 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9848 // At this point we know that there is a 1-1 correspondence between LLVM PHI
9849 // nodes and Machine PHI nodes, but the incoming operands have not been
9851 for (const PHINode &PN : SuccBB->phis()) {
9852 // Ignore dead phi's.
9857 if (PN.getType()->isEmptyTy())
9861 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9863 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9864 unsigned &RegOut = ConstantsOut[C];
9866 RegOut = FuncInfo.CreateRegs(C);
9867 CopyValueToVirtualRegister(C, RegOut);
9871 DenseMap<const Value *, unsigned>::iterator I =
9872 FuncInfo.ValueMap.find(PHIOp);
9873 if (I != FuncInfo.ValueMap.end())
9876 assert(isa<AllocaInst>(PHIOp) &&
9877 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9878 "Didn't codegen value into a register!??");
9879 Reg = FuncInfo.CreateRegs(PHIOp);
9880 CopyValueToVirtualRegister(PHIOp, Reg);
9884 // Remember that this register needs to added to the machine PHI node as
9885 // the input for this MBB.
9886 SmallVector<EVT, 4> ValueVTs;
9887 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9888 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9889 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9890 EVT VT = ValueVTs[vti];
9891 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9892 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9893 FuncInfo.PHINodesToUpdate.push_back(
9894 std::make_pair(&*MBBI++, Reg + i));
9895 Reg += NumRegisters;
9900 ConstantsOut.clear();
9903 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9906 SelectionDAGBuilder::StackProtectorDescriptor::
9907 AddSuccessorMBB(const BasicBlock *BB,
9908 MachineBasicBlock *ParentMBB,
9910 MachineBasicBlock *SuccMBB) {
9911 // If SuccBB has not been created yet, create it.
9913 MachineFunction *MF = ParentMBB->getParent();
9914 MachineFunction::iterator BBI(ParentMBB);
9915 SuccMBB = MF->CreateMachineBasicBlock(BB);
9916 MF->insert(++BBI, SuccMBB);
9918 // Add it as a successor of ParentMBB.
9919 ParentMBB->addSuccessor(
9920 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9924 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9925 MachineFunction::iterator I(MBB);
9926 if (++I == FuncInfo.MF->end())
9931 /// During lowering new call nodes can be created (such as memset, etc.).
9932 /// Those will become new roots of the current DAG, but complications arise
9933 /// when they are tail calls. In such cases, the call lowering will update
9934 /// the root, but the builder still needs to know that a tail call has been
9935 /// lowered in order to avoid generating an additional return.
9936 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9937 // If the node is null, we do have a tail call.
9938 if (MaybeTC.getNode() != nullptr)
9939 DAG.setRoot(MaybeTC);
9944 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9945 MachineBasicBlock *SwitchMBB,
9946 MachineBasicBlock *DefaultMBB) {
9947 MachineFunction *CurMF = FuncInfo.MF;
9948 MachineBasicBlock *NextMBB = nullptr;
9949 MachineFunction::iterator BBI(W.MBB);
9950 if (++BBI != FuncInfo.MF->end())
9953 unsigned Size = W.LastCluster - W.FirstCluster + 1;
9955 BranchProbabilityInfo *BPI = FuncInfo.BPI;
9957 if (Size == 2 && W.MBB == SwitchMBB) {
9958 // If any two of the cases has the same destination, and if one value
9959 // is the same as the other, but has one bit unset that the other has set,
9960 // use bit manipulation to do two compares at once. For example:
9961 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9962 // TODO: This could be extended to merge any 2 cases in switches with 3
9964 // TODO: Handle cases where W.CaseBB != SwitchBB.
9965 CaseCluster &Small = *W.FirstCluster;
9966 CaseCluster &Big = *W.LastCluster;
9968 if (Small.Low == Small.High && Big.Low == Big.High &&
9969 Small.MBB == Big.MBB) {
9970 const APInt &SmallValue = Small.Low->getValue();
9971 const APInt &BigValue = Big.Low->getValue();
9973 // Check that there is only one bit different.
9974 APInt CommonBit = BigValue ^ SmallValue;
9975 if (CommonBit.isPowerOf2()) {
9976 SDValue CondLHS = getValue(Cond);
9977 EVT VT = CondLHS.getValueType();
9978 SDLoc DL = getCurSDLoc();
9980 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9981 DAG.getConstant(CommonBit, DL, VT));
9982 SDValue Cond = DAG.getSetCC(
9983 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9986 // Update successor info.
9987 // Both Small and Big will jump to Small.BB, so we sum up the
9989 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9991 addSuccessorWithProb(
9992 SwitchMBB, DefaultMBB,
9993 // The default destination is the first successor in IR.
9994 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9996 addSuccessorWithProb(SwitchMBB, DefaultMBB);
9998 // Insert the true branch.
10000 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10001 DAG.getBasicBlock(Small.MBB));
10002 // Insert the false branch.
10003 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10004 DAG.getBasicBlock(DefaultMBB));
10006 DAG.setRoot(BrCond);
10012 if (TM.getOptLevel() != CodeGenOpt::None) {
10013 // Here, we order cases by probability so the most likely case will be
10014 // checked first. However, two clusters can have the same probability in
10015 // which case their relative ordering is non-deterministic. So we use Low
10016 // as a tie-breaker as clusters are guaranteed to never overlap.
10017 llvm::sort(W.FirstCluster, W.LastCluster + 1,
10018 [](const CaseCluster &a, const CaseCluster &b) {
10019 return a.Prob != b.Prob ?
10021 a.Low->getValue().slt(b.Low->getValue());
10024 // Rearrange the case blocks so that the last one falls through if possible
10025 // without changing the order of probabilities.
10026 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10028 if (I->Prob > W.LastCluster->Prob)
10030 if (I->Kind == CC_Range && I->MBB == NextMBB) {
10031 std::swap(*I, *W.LastCluster);
10037 // Compute total probability.
10038 BranchProbability DefaultProb = W.DefaultProb;
10039 BranchProbability UnhandledProbs = DefaultProb;
10040 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10041 UnhandledProbs += I->Prob;
10043 MachineBasicBlock *CurMBB = W.MBB;
10044 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10045 bool FallthroughUnreachable = false;
10046 MachineBasicBlock *Fallthrough;
10047 if (I == W.LastCluster) {
10048 // For the last cluster, fall through to the default destination.
10049 Fallthrough = DefaultMBB;
10050 FallthroughUnreachable = isa<UnreachableInst>(
10051 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10053 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10054 CurMF->insert(BBI, Fallthrough);
10055 // Put Cond in a virtual register to make it available from the new blocks.
10056 ExportFromCurrentBlock(Cond);
10058 UnhandledProbs -= I->Prob;
10061 case CC_JumpTable: {
10062 // FIXME: Optimize away range check based on pivot comparisons.
10063 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10064 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10066 // The jump block hasn't been inserted yet; insert it here.
10067 MachineBasicBlock *JumpMBB = JT->MBB;
10068 CurMF->insert(BBI, JumpMBB);
10070 auto JumpProb = I->Prob;
10071 auto FallthroughProb = UnhandledProbs;
10073 // If the default statement is a target of the jump table, we evenly
10074 // distribute the default probability to successors of CurMBB. Also
10075 // update the probability on the edge from JumpMBB to Fallthrough.
10076 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10077 SE = JumpMBB->succ_end();
10079 if (*SI == DefaultMBB) {
10080 JumpProb += DefaultProb / 2;
10081 FallthroughProb -= DefaultProb / 2;
10082 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10083 JumpMBB->normalizeSuccProbs();
10088 if (FallthroughUnreachable) {
10089 // Skip the range check if the fallthrough block is unreachable.
10090 JTH->OmitRangeCheck = true;
10093 if (!JTH->OmitRangeCheck)
10094 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10095 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10096 CurMBB->normalizeSuccProbs();
10098 // The jump table header will be inserted in our current block, do the
10099 // range check, and fall through to our fallthrough block.
10100 JTH->HeaderBB = CurMBB;
10101 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10103 // If we're in the right place, emit the jump table header right now.
10104 if (CurMBB == SwitchMBB) {
10105 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10106 JTH->Emitted = true;
10110 case CC_BitTests: {
10111 // FIXME: If Fallthrough is unreachable, skip the range check.
10113 // FIXME: Optimize away range check based on pivot comparisons.
10114 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10116 // The bit test blocks haven't been inserted yet; insert them here.
10117 for (BitTestCase &BTC : BTB->Cases)
10118 CurMF->insert(BBI, BTC.ThisBB);
10120 // Fill in fields of the BitTestBlock.
10121 BTB->Parent = CurMBB;
10122 BTB->Default = Fallthrough;
10124 BTB->DefaultProb = UnhandledProbs;
10125 // If the cases in bit test don't form a contiguous range, we evenly
10126 // distribute the probability on the edge to Fallthrough to two
10127 // successors of CurMBB.
10128 if (!BTB->ContiguousRange) {
10129 BTB->Prob += DefaultProb / 2;
10130 BTB->DefaultProb -= DefaultProb / 2;
10133 // If we're in the right place, emit the bit test header right now.
10134 if (CurMBB == SwitchMBB) {
10135 visitBitTestHeader(*BTB, SwitchMBB);
10136 BTB->Emitted = true;
10141 const Value *RHS, *LHS, *MHS;
10143 if (I->Low == I->High) {
10144 // Check Cond == I->Low.
10150 // Check I->Low <= Cond <= I->High.
10157 // If Fallthrough is unreachable, fold away the comparison.
10158 if (FallthroughUnreachable)
10161 // The false probability is the sum of all unhandled cases.
10162 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10163 getCurSDLoc(), I->Prob, UnhandledProbs);
10165 if (CurMBB == SwitchMBB)
10166 visitSwitchCase(CB, SwitchMBB);
10168 SL->SwitchCases.push_back(CB);
10173 CurMBB = Fallthrough;
10177 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10178 CaseClusterIt First,
10179 CaseClusterIt Last) {
10180 return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10181 if (X.Prob != CC.Prob)
10182 return X.Prob > CC.Prob;
10184 // Ties are broken by comparing the case value.
10185 return X.Low->getValue().slt(CC.Low->getValue());
10189 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10190 const SwitchWorkListItem &W,
10192 MachineBasicBlock *SwitchMBB) {
10193 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10194 "Clusters not sorted?");
10196 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10198 // Balance the tree based on branch probabilities to create a near-optimal (in
10199 // terms of search time given key frequency) binary search tree. See e.g. Kurt
10200 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10201 CaseClusterIt LastLeft = W.FirstCluster;
10202 CaseClusterIt FirstRight = W.LastCluster;
10203 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10204 auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10206 // Move LastLeft and FirstRight towards each other from opposite directions to
10207 // find a partitioning of the clusters which balances the probability on both
10208 // sides. If LeftProb and RightProb are equal, alternate which side is
10209 // taken to ensure 0-probability nodes are distributed evenly.
10211 while (LastLeft + 1 < FirstRight) {
10212 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10213 LeftProb += (++LastLeft)->Prob;
10215 RightProb += (--FirstRight)->Prob;
10220 // Our binary search tree differs from a typical BST in that ours can have up
10221 // to three values in each leaf. The pivot selection above doesn't take that
10222 // into account, which means the tree might require more nodes and be less
10223 // efficient. We compensate for this here.
10225 unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10226 unsigned NumRight = W.LastCluster - FirstRight + 1;
10228 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10229 // If one side has less than 3 clusters, and the other has more than 3,
10230 // consider taking a cluster from the other side.
10232 if (NumLeft < NumRight) {
10233 // Consider moving the first cluster on the right to the left side.
10234 CaseCluster &CC = *FirstRight;
10235 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10236 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10237 if (LeftSideRank <= RightSideRank) {
10238 // Moving the cluster to the left does not demote it.
10244 assert(NumRight < NumLeft);
10245 // Consider moving the last element on the left to the right side.
10246 CaseCluster &CC = *LastLeft;
10247 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10248 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10249 if (RightSideRank <= LeftSideRank) {
10250 // Moving the cluster to the right does not demot it.
10260 assert(LastLeft + 1 == FirstRight);
10261 assert(LastLeft >= W.FirstCluster);
10262 assert(FirstRight <= W.LastCluster);
10264 // Use the first element on the right as pivot since we will make less-than
10265 // comparisons against it.
10266 CaseClusterIt PivotCluster = FirstRight;
10267 assert(PivotCluster > W.FirstCluster);
10268 assert(PivotCluster <= W.LastCluster);
10270 CaseClusterIt FirstLeft = W.FirstCluster;
10271 CaseClusterIt LastRight = W.LastCluster;
10273 const ConstantInt *Pivot = PivotCluster->Low;
10275 // New blocks will be inserted immediately after the current one.
10276 MachineFunction::iterator BBI(W.MBB);
10279 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10280 // we can branch to its destination directly if it's squeezed exactly in
10281 // between the known lower bound and Pivot - 1.
10282 MachineBasicBlock *LeftMBB;
10283 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10284 FirstLeft->Low == W.GE &&
10285 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10286 LeftMBB = FirstLeft->MBB;
10288 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10289 FuncInfo.MF->insert(BBI, LeftMBB);
10290 WorkList.push_back(
10291 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10292 // Put Cond in a virtual register to make it available from the new blocks.
10293 ExportFromCurrentBlock(Cond);
10296 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10297 // single cluster, RHS.Low == Pivot, and we can branch to its destination
10298 // directly if RHS.High equals the current upper bound.
10299 MachineBasicBlock *RightMBB;
10300 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10301 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10302 RightMBB = FirstRight->MBB;
10304 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10305 FuncInfo.MF->insert(BBI, RightMBB);
10306 WorkList.push_back(
10307 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10308 // Put Cond in a virtual register to make it available from the new blocks.
10309 ExportFromCurrentBlock(Cond);
10312 // Create the CaseBlock record that will be used to lower the branch.
10313 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10314 getCurSDLoc(), LeftProb, RightProb);
10316 if (W.MBB == SwitchMBB)
10317 visitSwitchCase(CB, SwitchMBB);
10319 SL->SwitchCases.push_back(CB);
10322 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10323 // from the swith statement.
10324 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10325 BranchProbability PeeledCaseProb) {
10326 if (PeeledCaseProb == BranchProbability::getOne())
10327 return BranchProbability::getZero();
10328 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10330 uint32_t Numerator = CaseProb.getNumerator();
10331 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10332 return BranchProbability(Numerator, std::max(Numerator, Denominator));
10335 // Try to peel the top probability case if it exceeds the threshold.
10336 // Return current MachineBasicBlock for the switch statement if the peeling
10338 // If the peeling is performed, return the newly created MachineBasicBlock
10339 // for the peeled switch statement. Also update Clusters to remove the peeled
10340 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10341 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10342 const SwitchInst &SI, CaseClusterVector &Clusters,
10343 BranchProbability &PeeledCaseProb) {
10344 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10345 // Don't perform if there is only one cluster or optimizing for size.
10346 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10347 TM.getOptLevel() == CodeGenOpt::None ||
10348 SwitchMBB->getParent()->getFunction().hasMinSize())
10351 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10352 unsigned PeeledCaseIndex = 0;
10353 bool SwitchPeeled = false;
10354 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10355 CaseCluster &CC = Clusters[Index];
10356 if (CC.Prob < TopCaseProb)
10358 TopCaseProb = CC.Prob;
10359 PeeledCaseIndex = Index;
10360 SwitchPeeled = true;
10365 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10366 << TopCaseProb << "\n");
10368 // Record the MBB for the peeled switch statement.
10369 MachineFunction::iterator BBI(SwitchMBB);
10371 MachineBasicBlock *PeeledSwitchMBB =
10372 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10373 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10375 ExportFromCurrentBlock(SI.getCondition());
10376 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10377 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10378 nullptr, nullptr, TopCaseProb.getCompl()};
10379 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10381 Clusters.erase(PeeledCaseIt);
10382 for (CaseCluster &CC : Clusters) {
10384 dbgs() << "Scale the probablity for one cluster, before scaling: "
10385 << CC.Prob << "\n");
10386 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10387 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10389 PeeledCaseProb = TopCaseProb;
10390 return PeeledSwitchMBB;
10393 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10394 // Extract cases from the switch.
10395 BranchProbabilityInfo *BPI = FuncInfo.BPI;
10396 CaseClusterVector Clusters;
10397 Clusters.reserve(SI.getNumCases());
10398 for (auto I : SI.cases()) {
10399 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10400 const ConstantInt *CaseVal = I.getCaseValue();
10401 BranchProbability Prob =
10402 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10403 : BranchProbability(1, SI.getNumCases() + 1);
10404 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10407 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10409 // Cluster adjacent cases with the same destination. We do this at all
10410 // optimization levels because it's cheap to do and will make codegen faster
10411 // if there are many clusters.
10412 sortAndRangeify(Clusters);
10414 // The branch probablity of the peeled case.
10415 BranchProbability PeeledCaseProb = BranchProbability::getZero();
10416 MachineBasicBlock *PeeledSwitchMBB =
10417 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10419 // If there is only the default destination, jump there directly.
10420 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10421 if (Clusters.empty()) {
10422 assert(PeeledSwitchMBB == SwitchMBB);
10423 SwitchMBB->addSuccessor(DefaultMBB);
10424 if (DefaultMBB != NextBlock(SwitchMBB)) {
10425 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10426 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10431 SL->findJumpTables(Clusters, &SI, DefaultMBB);
10432 SL->findBitTestClusters(Clusters, &SI);
10435 dbgs() << "Case clusters: ";
10436 for (const CaseCluster &C : Clusters) {
10437 if (C.Kind == CC_JumpTable)
10439 if (C.Kind == CC_BitTests)
10442 C.Low->getValue().print(dbgs(), true);
10443 if (C.Low != C.High) {
10445 C.High->getValue().print(dbgs(), true);
10452 assert(!Clusters.empty());
10453 SwitchWorkList WorkList;
10454 CaseClusterIt First = Clusters.begin();
10455 CaseClusterIt Last = Clusters.end() - 1;
10456 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10457 // Scale the branchprobability for DefaultMBB if the peel occurs and
10458 // DefaultMBB is not replaced.
10459 if (PeeledCaseProb != BranchProbability::getZero() &&
10460 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10461 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10462 WorkList.push_back(
10463 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10465 while (!WorkList.empty()) {
10466 SwitchWorkListItem W = WorkList.back();
10467 WorkList.pop_back();
10468 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10470 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10471 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10472 // For optimized builds, lower large range as a balanced binary tree.
10473 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10477 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);