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/TargetFrameLowering.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/CodeGen/WinEHFuncInfo.h"
65 #include "llvm/IR/Argument.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/BasicBlock.h"
68 #include "llvm/IR/CFG.h"
69 #include "llvm/IR/CallSite.h"
70 #include "llvm/IR/CallingConv.h"
71 #include "llvm/IR/Constant.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DebugInfoMetadata.h"
76 #include "llvm/IR/DebugLoc.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/InlineAsm.h"
81 #include "llvm/IR/InstrTypes.h"
82 #include "llvm/IR/Instruction.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/IntrinsicInst.h"
85 #include "llvm/IR/Intrinsics.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Metadata.h"
88 #include "llvm/IR/Module.h"
89 #include "llvm/IR/Operator.h"
90 #include "llvm/IR/PatternMatch.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include "llvm/Transforms/Utils/Local.h"
124 using namespace llvm
;
125 using namespace PatternMatch
;
127 #define DEBUG_TYPE "isel"
129 /// LimitFloatPrecision - Generate low-precision inline sequences for
130 /// some float libcalls (6, 8 or 12 bits).
131 static unsigned LimitFloatPrecision
;
133 static cl::opt
<unsigned, true>
134 LimitFPPrecision("limit-float-precision",
135 cl::desc("Generate low-precision inline sequences "
136 "for some float libcalls"),
137 cl::location(LimitFloatPrecision
), cl::Hidden
,
140 static cl::opt
<unsigned> SwitchPeelThreshold(
141 "switch-peel-threshold", cl::Hidden
, cl::init(66),
142 cl::desc("Set the case probability threshold for peeling the case from a "
143 "switch statement. A value greater than 100 will void this "
146 // Limit the width of DAG chains. This is important in general to prevent
147 // DAG-based analysis from blowing up. For example, alias analysis and
148 // load clustering may not complete in reasonable time. It is difficult to
149 // recognize and avoid this situation within each individual analysis, and
150 // future analyses are likely to have the same behavior. Limiting DAG width is
151 // the safe approach and will be especially important with global DAGs.
153 // MaxParallelChains default is arbitrarily high to avoid affecting
154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
155 // sequence over this should have been converted to llvm.memcpy by the
156 // frontend. It is easy to induce this behavior with .ll code such as:
157 // %buffer = alloca [4096 x i8]
158 // %data = load [4096 x i8]* %argPtr
159 // store [4096 x i8] %data, [4096 x i8]* %buffer
160 static const unsigned MaxParallelChains
= 64;
162 // Return the calling convention if the Value passed requires ABI mangling as it
163 // is a parameter to a function or a return value from a function which is not
165 static Optional
<CallingConv::ID
> getABIRegCopyCC(const Value
*V
) {
166 if (auto *R
= dyn_cast
<ReturnInst
>(V
))
167 return R
->getParent()->getParent()->getCallingConv();
169 if (auto *CI
= dyn_cast
<CallInst
>(V
)) {
170 const bool IsInlineAsm
= CI
->isInlineAsm();
171 const bool IsIndirectFunctionCall
=
172 !IsInlineAsm
&& !CI
->getCalledFunction();
174 // It is possible that the call instruction is an inline asm statement or an
175 // indirect function call in which case the return value of
176 // getCalledFunction() would be nullptr.
177 const bool IsInstrinsicCall
=
178 !IsInlineAsm
&& !IsIndirectFunctionCall
&&
179 CI
->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic
;
181 if (!IsInlineAsm
&& !IsInstrinsicCall
)
182 return CI
->getCallingConv();
188 static SDValue
getCopyFromPartsVector(SelectionDAG
&DAG
, const SDLoc
&DL
,
189 const SDValue
*Parts
, unsigned NumParts
,
190 MVT PartVT
, EVT ValueVT
, const Value
*V
,
191 Optional
<CallingConv::ID
> CC
);
193 /// getCopyFromParts - Create a value that contains the specified legal parts
194 /// combined into the value they represent. If the parts combine to a type
195 /// larger than ValueVT then AssertOp can be used to specify whether the extra
196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
197 /// (ISD::AssertSext).
198 static SDValue
getCopyFromParts(SelectionDAG
&DAG
, const SDLoc
&DL
,
199 const SDValue
*Parts
, unsigned NumParts
,
200 MVT PartVT
, EVT ValueVT
, const Value
*V
,
201 Optional
<CallingConv::ID
> CC
= None
,
202 Optional
<ISD::NodeType
> AssertOp
= None
) {
203 if (ValueVT
.isVector())
204 return getCopyFromPartsVector(DAG
, DL
, Parts
, NumParts
, PartVT
, ValueVT
, V
,
207 assert(NumParts
> 0 && "No parts to assemble!");
208 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
209 SDValue Val
= Parts
[0];
212 // Assemble the value from multiple parts.
213 if (ValueVT
.isInteger()) {
214 unsigned PartBits
= PartVT
.getSizeInBits();
215 unsigned ValueBits
= ValueVT
.getSizeInBits();
217 // Assemble the power of 2 part.
218 unsigned RoundParts
= NumParts
& (NumParts
- 1) ?
219 1 << Log2_32(NumParts
) : NumParts
;
220 unsigned RoundBits
= PartBits
* RoundParts
;
221 EVT RoundVT
= RoundBits
== ValueBits
?
222 ValueVT
: EVT::getIntegerVT(*DAG
.getContext(), RoundBits
);
225 EVT HalfVT
= EVT::getIntegerVT(*DAG
.getContext(), RoundBits
/2);
227 if (RoundParts
> 2) {
228 Lo
= getCopyFromParts(DAG
, DL
, Parts
, RoundParts
/ 2,
230 Hi
= getCopyFromParts(DAG
, DL
, Parts
+ RoundParts
/ 2,
231 RoundParts
/ 2, PartVT
, HalfVT
, V
);
233 Lo
= DAG
.getNode(ISD::BITCAST
, DL
, HalfVT
, Parts
[0]);
234 Hi
= DAG
.getNode(ISD::BITCAST
, DL
, HalfVT
, Parts
[1]);
237 if (DAG
.getDataLayout().isBigEndian())
240 Val
= DAG
.getNode(ISD::BUILD_PAIR
, DL
, RoundVT
, Lo
, Hi
);
242 if (RoundParts
< NumParts
) {
243 // Assemble the trailing non-power-of-2 part.
244 unsigned OddParts
= NumParts
- RoundParts
;
245 EVT OddVT
= EVT::getIntegerVT(*DAG
.getContext(), OddParts
* PartBits
);
246 Hi
= getCopyFromParts(DAG
, DL
, Parts
+ RoundParts
, OddParts
, PartVT
,
249 // Combine the round and odd parts.
251 if (DAG
.getDataLayout().isBigEndian())
253 EVT TotalVT
= EVT::getIntegerVT(*DAG
.getContext(), NumParts
* PartBits
);
254 Hi
= DAG
.getNode(ISD::ANY_EXTEND
, DL
, TotalVT
, Hi
);
256 DAG
.getNode(ISD::SHL
, DL
, TotalVT
, Hi
,
257 DAG
.getConstant(Lo
.getValueSizeInBits(), DL
,
258 TLI
.getPointerTy(DAG
.getDataLayout())));
259 Lo
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, TotalVT
, Lo
);
260 Val
= DAG
.getNode(ISD::OR
, DL
, TotalVT
, Lo
, Hi
);
262 } else if (PartVT
.isFloatingPoint()) {
263 // FP split into multiple FP parts (for ppcf128)
264 assert(ValueVT
== EVT(MVT::ppcf128
) && PartVT
== MVT::f64
&&
267 Lo
= DAG
.getNode(ISD::BITCAST
, DL
, EVT(MVT::f64
), Parts
[0]);
268 Hi
= DAG
.getNode(ISD::BITCAST
, DL
, EVT(MVT::f64
), Parts
[1]);
269 if (TLI
.hasBigEndianPartOrdering(ValueVT
, DAG
.getDataLayout()))
271 Val
= DAG
.getNode(ISD::BUILD_PAIR
, DL
, ValueVT
, Lo
, Hi
);
273 // FP split into integer parts (soft fp)
274 assert(ValueVT
.isFloatingPoint() && PartVT
.isInteger() &&
275 !PartVT
.isVector() && "Unexpected split");
276 EVT IntVT
= EVT::getIntegerVT(*DAG
.getContext(), ValueVT
.getSizeInBits());
277 Val
= getCopyFromParts(DAG
, DL
, Parts
, NumParts
, PartVT
, IntVT
, V
, CC
);
281 // There is now one part, held in Val. Correct it to match ValueVT.
282 // PartEVT is the type of the register class that holds the value.
283 // ValueVT is the type of the inline asm operation.
284 EVT PartEVT
= Val
.getValueType();
286 if (PartEVT
== ValueVT
)
289 if (PartEVT
.isInteger() && ValueVT
.isFloatingPoint() &&
290 ValueVT
.bitsLT(PartEVT
)) {
291 // For an FP value in an integer part, we need to truncate to the right
293 PartEVT
= EVT::getIntegerVT(*DAG
.getContext(), ValueVT
.getSizeInBits());
294 Val
= DAG
.getNode(ISD::TRUNCATE
, DL
, PartEVT
, Val
);
297 // Handle types that have the same size.
298 if (PartEVT
.getSizeInBits() == ValueVT
.getSizeInBits())
299 return DAG
.getNode(ISD::BITCAST
, DL
, ValueVT
, Val
);
301 // Handle types with different sizes.
302 if (PartEVT
.isInteger() && ValueVT
.isInteger()) {
303 if (ValueVT
.bitsLT(PartEVT
)) {
304 // For a truncate, see if we have any information to
305 // indicate whether the truncated bits will always be
306 // zero or sign-extension.
307 if (AssertOp
.hasValue())
308 Val
= DAG
.getNode(*AssertOp
, DL
, PartEVT
, Val
,
309 DAG
.getValueType(ValueVT
));
310 return DAG
.getNode(ISD::TRUNCATE
, DL
, ValueVT
, Val
);
312 return DAG
.getNode(ISD::ANY_EXTEND
, DL
, ValueVT
, Val
);
315 if (PartEVT
.isFloatingPoint() && ValueVT
.isFloatingPoint()) {
316 // FP_ROUND's are always exact here.
317 if (ValueVT
.bitsLT(Val
.getValueType()))
319 ISD::FP_ROUND
, DL
, ValueVT
, Val
,
320 DAG
.getTargetConstant(1, DL
, TLI
.getPointerTy(DAG
.getDataLayout())));
322 return DAG
.getNode(ISD::FP_EXTEND
, DL
, ValueVT
, Val
);
325 llvm_unreachable("Unknown mismatch!");
328 static void diagnosePossiblyInvalidConstraint(LLVMContext
&Ctx
, const Value
*V
,
329 const Twine
&ErrMsg
) {
330 const Instruction
*I
= dyn_cast_or_null
<Instruction
>(V
);
332 return Ctx
.emitError(ErrMsg
);
334 const char *AsmError
= ", possible invalid constraint for vector type";
335 if (const CallInst
*CI
= dyn_cast
<CallInst
>(I
))
336 if (isa
<InlineAsm
>(CI
->getCalledValue()))
337 return Ctx
.emitError(I
, ErrMsg
+ AsmError
);
339 return Ctx
.emitError(I
, ErrMsg
);
342 /// getCopyFromPartsVector - Create a value that contains the specified legal
343 /// parts combined into the value they represent. If the parts combine to a
344 /// type larger than ValueVT then AssertOp can be used to specify whether the
345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
346 /// ValueVT (ISD::AssertSext).
347 static SDValue
getCopyFromPartsVector(SelectionDAG
&DAG
, const SDLoc
&DL
,
348 const SDValue
*Parts
, unsigned NumParts
,
349 MVT PartVT
, EVT ValueVT
, const Value
*V
,
350 Optional
<CallingConv::ID
> CallConv
) {
351 assert(ValueVT
.isVector() && "Not a vector value");
352 assert(NumParts
> 0 && "No parts to assemble!");
353 const bool IsABIRegCopy
= CallConv
.hasValue();
355 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
356 SDValue Val
= Parts
[0];
358 // Handle a multi-element vector.
362 unsigned NumIntermediates
;
366 NumRegs
= TLI
.getVectorTypeBreakdownForCallingConv(
367 *DAG
.getContext(), CallConv
.getValue(), ValueVT
, IntermediateVT
,
368 NumIntermediates
, RegisterVT
);
371 TLI
.getVectorTypeBreakdown(*DAG
.getContext(), ValueVT
, IntermediateVT
,
372 NumIntermediates
, RegisterVT
);
375 assert(NumRegs
== NumParts
&& "Part count doesn't match vector breakdown!");
376 NumParts
= NumRegs
; // Silence a compiler warning.
377 assert(RegisterVT
== PartVT
&& "Part type doesn't match vector breakdown!");
378 assert(RegisterVT
.getSizeInBits() ==
379 Parts
[0].getSimpleValueType().getSizeInBits() &&
380 "Part type sizes don't match!");
382 // Assemble the parts into intermediate operands.
383 SmallVector
<SDValue
, 8> Ops(NumIntermediates
);
384 if (NumIntermediates
== NumParts
) {
385 // If the register was not expanded, truncate or copy the value,
387 for (unsigned i
= 0; i
!= NumParts
; ++i
)
388 Ops
[i
] = getCopyFromParts(DAG
, DL
, &Parts
[i
], 1,
389 PartVT
, IntermediateVT
, V
);
390 } else if (NumParts
> 0) {
391 // If the intermediate type was expanded, build the intermediate
392 // operands from the parts.
393 assert(NumParts
% NumIntermediates
== 0 &&
394 "Must expand into a divisible number of parts!");
395 unsigned Factor
= NumParts
/ NumIntermediates
;
396 for (unsigned i
= 0; i
!= NumIntermediates
; ++i
)
397 Ops
[i
] = getCopyFromParts(DAG
, DL
, &Parts
[i
* Factor
], Factor
,
398 PartVT
, IntermediateVT
, V
);
401 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
402 // intermediate operands.
404 EVT::getVectorVT(*DAG
.getContext(), IntermediateVT
.getScalarType(),
405 (IntermediateVT
.isVector()
406 ? IntermediateVT
.getVectorNumElements() * NumParts
407 : NumIntermediates
));
408 Val
= DAG
.getNode(IntermediateVT
.isVector() ? ISD::CONCAT_VECTORS
410 DL
, BuiltVectorTy
, Ops
);
413 // There is now one part, held in Val. Correct it to match ValueVT.
414 EVT PartEVT
= Val
.getValueType();
416 if (PartEVT
== ValueVT
)
419 if (PartEVT
.isVector()) {
420 // If the element type of the source/dest vectors are the same, but the
421 // parts vector has more elements than the value vector, then we have a
422 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
424 if (PartEVT
.getVectorElementType() == ValueVT
.getVectorElementType()) {
425 assert(PartEVT
.getVectorNumElements() > ValueVT
.getVectorNumElements() &&
426 "Cannot narrow, it would be a lossy transformation");
428 ISD::EXTRACT_SUBVECTOR
, DL
, ValueVT
, Val
,
429 DAG
.getConstant(0, DL
, TLI
.getVectorIdxTy(DAG
.getDataLayout())));
432 // Vector/Vector bitcast.
433 if (ValueVT
.getSizeInBits() == PartEVT
.getSizeInBits())
434 return DAG
.getNode(ISD::BITCAST
, DL
, ValueVT
, Val
);
436 assert(PartEVT
.getVectorNumElements() == ValueVT
.getVectorNumElements() &&
437 "Cannot handle this kind of promotion");
438 // Promoted vector extract
439 return DAG
.getAnyExtOrTrunc(Val
, DL
, ValueVT
);
443 // Trivial bitcast if the types are the same size and the destination
444 // vector type is legal.
445 if (PartEVT
.getSizeInBits() == ValueVT
.getSizeInBits() &&
446 TLI
.isTypeLegal(ValueVT
))
447 return DAG
.getNode(ISD::BITCAST
, DL
, ValueVT
, Val
);
449 if (ValueVT
.getVectorNumElements() != 1) {
450 // Certain ABIs require that vectors are passed as integers. For vectors
451 // are the same size, this is an obvious bitcast.
452 if (ValueVT
.getSizeInBits() == PartEVT
.getSizeInBits()) {
453 return DAG
.getNode(ISD::BITCAST
, DL
, ValueVT
, Val
);
454 } else if (ValueVT
.getSizeInBits() < PartEVT
.getSizeInBits()) {
455 // Bitcast Val back the original type and extract the corresponding
457 unsigned Elts
= PartEVT
.getSizeInBits() / ValueVT
.getScalarSizeInBits();
458 EVT WiderVecType
= EVT::getVectorVT(*DAG
.getContext(),
459 ValueVT
.getVectorElementType(), Elts
);
460 Val
= DAG
.getBitcast(WiderVecType
, Val
);
462 ISD::EXTRACT_SUBVECTOR
, DL
, ValueVT
, Val
,
463 DAG
.getConstant(0, DL
, TLI
.getVectorIdxTy(DAG
.getDataLayout())));
466 diagnosePossiblyInvalidConstraint(
467 *DAG
.getContext(), V
, "non-trivial scalar-to-vector conversion");
468 return DAG
.getUNDEF(ValueVT
);
471 // Handle cases such as i8 -> <1 x i1>
472 EVT ValueSVT
= ValueVT
.getVectorElementType();
473 if (ValueVT
.getVectorNumElements() == 1 && ValueSVT
!= PartEVT
)
474 Val
= ValueVT
.isFloatingPoint() ? DAG
.getFPExtendOrRound(Val
, DL
, ValueSVT
)
475 : DAG
.getAnyExtOrTrunc(Val
, DL
, ValueSVT
);
477 return DAG
.getBuildVector(ValueVT
, DL
, Val
);
480 static void getCopyToPartsVector(SelectionDAG
&DAG
, const SDLoc
&dl
,
481 SDValue Val
, SDValue
*Parts
, unsigned NumParts
,
482 MVT PartVT
, const Value
*V
,
483 Optional
<CallingConv::ID
> CallConv
);
485 /// getCopyToParts - Create a series of nodes that contain the specified value
486 /// split into legal parts. If the parts contain more bits than Val, then, for
487 /// integers, ExtendKind can be used to specify how to generate the extra bits.
488 static void getCopyToParts(SelectionDAG
&DAG
, const SDLoc
&DL
, SDValue Val
,
489 SDValue
*Parts
, unsigned NumParts
, MVT PartVT
,
491 Optional
<CallingConv::ID
> CallConv
= None
,
492 ISD::NodeType ExtendKind
= ISD::ANY_EXTEND
) {
493 EVT ValueVT
= Val
.getValueType();
495 // Handle the vector case separately.
496 if (ValueVT
.isVector())
497 return getCopyToPartsVector(DAG
, DL
, Val
, Parts
, NumParts
, PartVT
, V
,
500 unsigned PartBits
= PartVT
.getSizeInBits();
501 unsigned OrigNumParts
= NumParts
;
502 assert(DAG
.getTargetLoweringInfo().isTypeLegal(PartVT
) &&
503 "Copying to an illegal type!");
508 assert(!ValueVT
.isVector() && "Vector case handled elsewhere");
509 EVT PartEVT
= PartVT
;
510 if (PartEVT
== ValueVT
) {
511 assert(NumParts
== 1 && "No-op copy with multiple parts!");
516 if (NumParts
* PartBits
> ValueVT
.getSizeInBits()) {
517 // If the parts cover more bits than the value has, promote the value.
518 if (PartVT
.isFloatingPoint() && ValueVT
.isFloatingPoint()) {
519 assert(NumParts
== 1 && "Do not know what to promote to!");
520 Val
= DAG
.getNode(ISD::FP_EXTEND
, DL
, PartVT
, Val
);
522 if (ValueVT
.isFloatingPoint()) {
523 // FP values need to be bitcast, then extended if they are being put
524 // into a larger container.
525 ValueVT
= EVT::getIntegerVT(*DAG
.getContext(), ValueVT
.getSizeInBits());
526 Val
= DAG
.getNode(ISD::BITCAST
, DL
, ValueVT
, Val
);
528 assert((PartVT
.isInteger() || PartVT
== MVT::x86mmx
) &&
529 ValueVT
.isInteger() &&
530 "Unknown mismatch!");
531 ValueVT
= EVT::getIntegerVT(*DAG
.getContext(), NumParts
* PartBits
);
532 Val
= DAG
.getNode(ExtendKind
, DL
, ValueVT
, Val
);
533 if (PartVT
== MVT::x86mmx
)
534 Val
= DAG
.getNode(ISD::BITCAST
, DL
, PartVT
, Val
);
536 } else if (PartBits
== ValueVT
.getSizeInBits()) {
537 // Different types of the same size.
538 assert(NumParts
== 1 && PartEVT
!= ValueVT
);
539 Val
= DAG
.getNode(ISD::BITCAST
, DL
, PartVT
, Val
);
540 } else if (NumParts
* PartBits
< ValueVT
.getSizeInBits()) {
541 // If the parts cover less bits than value has, truncate the value.
542 assert((PartVT
.isInteger() || PartVT
== MVT::x86mmx
) &&
543 ValueVT
.isInteger() &&
544 "Unknown mismatch!");
545 ValueVT
= EVT::getIntegerVT(*DAG
.getContext(), NumParts
* PartBits
);
546 Val
= DAG
.getNode(ISD::TRUNCATE
, DL
, ValueVT
, Val
);
547 if (PartVT
== MVT::x86mmx
)
548 Val
= DAG
.getNode(ISD::BITCAST
, DL
, PartVT
, Val
);
551 // The value may have changed - recompute ValueVT.
552 ValueVT
= Val
.getValueType();
553 assert(NumParts
* PartBits
== ValueVT
.getSizeInBits() &&
554 "Failed to tile the value with PartVT!");
557 if (PartEVT
!= ValueVT
) {
558 diagnosePossiblyInvalidConstraint(*DAG
.getContext(), V
,
559 "scalar-to-vector conversion failed");
560 Val
= DAG
.getNode(ISD::BITCAST
, DL
, PartVT
, Val
);
567 // Expand the value into multiple parts.
568 if (NumParts
& (NumParts
- 1)) {
569 // The number of parts is not a power of 2. Split off and copy the tail.
570 assert(PartVT
.isInteger() && ValueVT
.isInteger() &&
571 "Do not know what to expand to!");
572 unsigned RoundParts
= 1 << Log2_32(NumParts
);
573 unsigned RoundBits
= RoundParts
* PartBits
;
574 unsigned OddParts
= NumParts
- RoundParts
;
575 SDValue OddVal
= DAG
.getNode(ISD::SRL
, DL
, ValueVT
, Val
,
576 DAG
.getIntPtrConstant(RoundBits
, DL
));
577 getCopyToParts(DAG
, DL
, OddVal
, Parts
+ RoundParts
, OddParts
, PartVT
, V
,
580 if (DAG
.getDataLayout().isBigEndian())
581 // The odd parts were reversed by getCopyToParts - unreverse them.
582 std::reverse(Parts
+ RoundParts
, Parts
+ NumParts
);
584 NumParts
= RoundParts
;
585 ValueVT
= EVT::getIntegerVT(*DAG
.getContext(), NumParts
* PartBits
);
586 Val
= DAG
.getNode(ISD::TRUNCATE
, DL
, ValueVT
, Val
);
589 // The number of parts is a power of 2. Repeatedly bisect the value using
591 Parts
[0] = DAG
.getNode(ISD::BITCAST
, DL
,
592 EVT::getIntegerVT(*DAG
.getContext(),
593 ValueVT
.getSizeInBits()),
596 for (unsigned StepSize
= NumParts
; StepSize
> 1; StepSize
/= 2) {
597 for (unsigned i
= 0; i
< NumParts
; i
+= StepSize
) {
598 unsigned ThisBits
= StepSize
* PartBits
/ 2;
599 EVT ThisVT
= EVT::getIntegerVT(*DAG
.getContext(), ThisBits
);
600 SDValue
&Part0
= Parts
[i
];
601 SDValue
&Part1
= Parts
[i
+StepSize
/2];
603 Part1
= DAG
.getNode(ISD::EXTRACT_ELEMENT
, DL
,
604 ThisVT
, Part0
, DAG
.getIntPtrConstant(1, DL
));
605 Part0
= DAG
.getNode(ISD::EXTRACT_ELEMENT
, DL
,
606 ThisVT
, Part0
, DAG
.getIntPtrConstant(0, DL
));
608 if (ThisBits
== PartBits
&& ThisVT
!= PartVT
) {
609 Part0
= DAG
.getNode(ISD::BITCAST
, DL
, PartVT
, Part0
);
610 Part1
= DAG
.getNode(ISD::BITCAST
, DL
, PartVT
, Part1
);
615 if (DAG
.getDataLayout().isBigEndian())
616 std::reverse(Parts
, Parts
+ OrigNumParts
);
619 static SDValue
widenVectorToPartType(SelectionDAG
&DAG
,
620 SDValue Val
, const SDLoc
&DL
, EVT PartVT
) {
621 if (!PartVT
.isVector())
624 EVT ValueVT
= Val
.getValueType();
625 unsigned PartNumElts
= PartVT
.getVectorNumElements();
626 unsigned ValueNumElts
= ValueVT
.getVectorNumElements();
627 if (PartNumElts
> ValueNumElts
&&
628 PartVT
.getVectorElementType() == ValueVT
.getVectorElementType()) {
629 EVT ElementVT
= PartVT
.getVectorElementType();
630 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
632 SmallVector
<SDValue
, 16> Ops
;
633 DAG
.ExtractVectorElements(Val
, Ops
);
634 SDValue EltUndef
= DAG
.getUNDEF(ElementVT
);
635 for (unsigned i
= ValueNumElts
, e
= PartNumElts
; i
!= e
; ++i
)
636 Ops
.push_back(EltUndef
);
638 // FIXME: Use CONCAT for 2x -> 4x.
639 return DAG
.getBuildVector(PartVT
, DL
, Ops
);
645 /// getCopyToPartsVector - Create a series of nodes that contain the specified
646 /// value split into legal parts.
647 static void getCopyToPartsVector(SelectionDAG
&DAG
, const SDLoc
&DL
,
648 SDValue Val
, SDValue
*Parts
, unsigned NumParts
,
649 MVT PartVT
, const Value
*V
,
650 Optional
<CallingConv::ID
> CallConv
) {
651 EVT ValueVT
= Val
.getValueType();
652 assert(ValueVT
.isVector() && "Not a vector");
653 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
654 const bool IsABIRegCopy
= CallConv
.hasValue();
657 EVT PartEVT
= PartVT
;
658 if (PartEVT
== ValueVT
) {
660 } else if (PartVT
.getSizeInBits() == ValueVT
.getSizeInBits()) {
661 // Bitconvert vector->vector case.
662 Val
= DAG
.getNode(ISD::BITCAST
, DL
, PartVT
, Val
);
663 } else if (SDValue Widened
= widenVectorToPartType(DAG
, Val
, DL
, PartVT
)) {
665 } else if (PartVT
.isVector() &&
666 PartEVT
.getVectorElementType().bitsGE(
667 ValueVT
.getVectorElementType()) &&
668 PartEVT
.getVectorNumElements() == ValueVT
.getVectorNumElements()) {
670 // Promoted vector extract
671 Val
= DAG
.getAnyExtOrTrunc(Val
, DL
, PartVT
);
673 if (ValueVT
.getVectorNumElements() == 1) {
675 ISD::EXTRACT_VECTOR_ELT
, DL
, PartVT
, Val
,
676 DAG
.getConstant(0, DL
, TLI
.getVectorIdxTy(DAG
.getDataLayout())));
678 assert(PartVT
.getSizeInBits() > ValueVT
.getSizeInBits() &&
679 "lossy conversion of vector to scalar type");
680 EVT IntermediateType
=
681 EVT::getIntegerVT(*DAG
.getContext(), ValueVT
.getSizeInBits());
682 Val
= DAG
.getBitcast(IntermediateType
, Val
);
683 Val
= DAG
.getAnyExtOrTrunc(Val
, DL
, PartVT
);
687 assert(Val
.getValueType() == PartVT
&& "Unexpected vector part value type");
692 // Handle a multi-element vector.
695 unsigned NumIntermediates
;
698 NumRegs
= TLI
.getVectorTypeBreakdownForCallingConv(
699 *DAG
.getContext(), CallConv
.getValue(), ValueVT
, IntermediateVT
,
700 NumIntermediates
, RegisterVT
);
703 TLI
.getVectorTypeBreakdown(*DAG
.getContext(), ValueVT
, IntermediateVT
,
704 NumIntermediates
, RegisterVT
);
707 assert(NumRegs
== NumParts
&& "Part count doesn't match vector breakdown!");
708 NumParts
= NumRegs
; // Silence a compiler warning.
709 assert(RegisterVT
== PartVT
&& "Part type doesn't match vector breakdown!");
711 unsigned IntermediateNumElts
= IntermediateVT
.isVector() ?
712 IntermediateVT
.getVectorNumElements() : 1;
714 // Convert the vector to the appropiate type if necessary.
715 unsigned DestVectorNoElts
= NumIntermediates
* IntermediateNumElts
;
717 EVT BuiltVectorTy
= EVT::getVectorVT(
718 *DAG
.getContext(), IntermediateVT
.getScalarType(), DestVectorNoElts
);
719 MVT IdxVT
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
720 if (ValueVT
!= BuiltVectorTy
) {
721 if (SDValue Widened
= widenVectorToPartType(DAG
, Val
, DL
, BuiltVectorTy
))
724 Val
= DAG
.getNode(ISD::BITCAST
, DL
, BuiltVectorTy
, Val
);
727 // Split the vector into intermediate operands.
728 SmallVector
<SDValue
, 8> Ops(NumIntermediates
);
729 for (unsigned i
= 0; i
!= NumIntermediates
; ++i
) {
730 if (IntermediateVT
.isVector()) {
731 Ops
[i
] = DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, IntermediateVT
, Val
,
732 DAG
.getConstant(i
* IntermediateNumElts
, DL
, IdxVT
));
734 Ops
[i
] = DAG
.getNode(
735 ISD::EXTRACT_VECTOR_ELT
, DL
, IntermediateVT
, Val
,
736 DAG
.getConstant(i
, DL
, IdxVT
));
740 // Split the intermediate operands into legal parts.
741 if (NumParts
== NumIntermediates
) {
742 // If the register was not expanded, promote or copy the value,
744 for (unsigned i
= 0; i
!= NumParts
; ++i
)
745 getCopyToParts(DAG
, DL
, Ops
[i
], &Parts
[i
], 1, PartVT
, V
, CallConv
);
746 } else if (NumParts
> 0) {
747 // If the intermediate type was expanded, split each the value into
749 assert(NumIntermediates
!= 0 && "division by zero");
750 assert(NumParts
% NumIntermediates
== 0 &&
751 "Must expand into a divisible number of parts!");
752 unsigned Factor
= NumParts
/ NumIntermediates
;
753 for (unsigned i
= 0; i
!= NumIntermediates
; ++i
)
754 getCopyToParts(DAG
, DL
, Ops
[i
], &Parts
[i
* Factor
], Factor
, PartVT
, V
,
759 RegsForValue::RegsForValue(const SmallVector
<unsigned, 4> ®s
, MVT regvt
,
760 EVT valuevt
, Optional
<CallingConv::ID
> CC
)
761 : ValueVTs(1, valuevt
), RegVTs(1, regvt
), Regs(regs
),
762 RegCount(1, regs
.size()), CallConv(CC
) {}
764 RegsForValue::RegsForValue(LLVMContext
&Context
, const TargetLowering
&TLI
,
765 const DataLayout
&DL
, unsigned Reg
, Type
*Ty
,
766 Optional
<CallingConv::ID
> CC
) {
767 ComputeValueVTs(TLI
, DL
, Ty
, ValueVTs
);
771 for (EVT ValueVT
: ValueVTs
) {
774 ? TLI
.getNumRegistersForCallingConv(Context
, CC
.getValue(), ValueVT
)
775 : TLI
.getNumRegisters(Context
, ValueVT
);
778 ? TLI
.getRegisterTypeForCallingConv(Context
, CC
.getValue(), ValueVT
)
779 : TLI
.getRegisterType(Context
, ValueVT
);
780 for (unsigned i
= 0; i
!= NumRegs
; ++i
)
781 Regs
.push_back(Reg
+ i
);
782 RegVTs
.push_back(RegisterVT
);
783 RegCount
.push_back(NumRegs
);
788 SDValue
RegsForValue::getCopyFromRegs(SelectionDAG
&DAG
,
789 FunctionLoweringInfo
&FuncInfo
,
790 const SDLoc
&dl
, SDValue
&Chain
,
791 SDValue
*Flag
, const Value
*V
) const {
792 // A Value with type {} or [0 x %t] needs no registers.
793 if (ValueVTs
.empty())
796 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
798 // Assemble the legal parts into the final values.
799 SmallVector
<SDValue
, 4> Values(ValueVTs
.size());
800 SmallVector
<SDValue
, 8> Parts
;
801 for (unsigned Value
= 0, Part
= 0, e
= ValueVTs
.size(); Value
!= e
; ++Value
) {
802 // Copy the legal parts from the registers.
803 EVT ValueVT
= ValueVTs
[Value
];
804 unsigned NumRegs
= RegCount
[Value
];
805 MVT RegisterVT
= isABIMangled() ? TLI
.getRegisterTypeForCallingConv(
807 CallConv
.getValue(), RegVTs
[Value
])
810 Parts
.resize(NumRegs
);
811 for (unsigned i
= 0; i
!= NumRegs
; ++i
) {
814 P
= DAG
.getCopyFromReg(Chain
, dl
, Regs
[Part
+i
], RegisterVT
);
816 P
= DAG
.getCopyFromReg(Chain
, dl
, Regs
[Part
+i
], RegisterVT
, *Flag
);
817 *Flag
= P
.getValue(2);
820 Chain
= P
.getValue(1);
823 // If the source register was virtual and if we know something about it,
824 // add an assert node.
825 if (!TargetRegisterInfo::isVirtualRegister(Regs
[Part
+i
]) ||
826 !RegisterVT
.isInteger())
829 const FunctionLoweringInfo::LiveOutInfo
*LOI
=
830 FuncInfo
.GetLiveOutRegInfo(Regs
[Part
+i
]);
834 unsigned RegSize
= RegisterVT
.getScalarSizeInBits();
835 unsigned NumSignBits
= LOI
->NumSignBits
;
836 unsigned NumZeroBits
= LOI
->Known
.countMinLeadingZeros();
838 if (NumZeroBits
== RegSize
) {
839 // The current value is a zero.
840 // Explicitly express that as it would be easier for
841 // optimizations to kick in.
842 Parts
[i
] = DAG
.getConstant(0, dl
, RegisterVT
);
846 // FIXME: We capture more information than the dag can represent. For
847 // now, just use the tightest assertzext/assertsext possible.
849 EVT
FromVT(MVT::Other
);
851 FromVT
= EVT::getIntegerVT(*DAG
.getContext(), RegSize
- NumZeroBits
);
853 } else if (NumSignBits
> 1) {
855 EVT::getIntegerVT(*DAG
.getContext(), RegSize
- NumSignBits
+ 1);
860 // Add an assertion node.
861 assert(FromVT
!= MVT::Other
);
862 Parts
[i
] = DAG
.getNode(isSExt
? ISD::AssertSext
: ISD::AssertZext
, dl
,
863 RegisterVT
, P
, DAG
.getValueType(FromVT
));
866 Values
[Value
] = getCopyFromParts(DAG
, dl
, Parts
.begin(), NumRegs
,
867 RegisterVT
, ValueVT
, V
, CallConv
);
872 return DAG
.getNode(ISD::MERGE_VALUES
, dl
, DAG
.getVTList(ValueVTs
), Values
);
875 void RegsForValue::getCopyToRegs(SDValue Val
, SelectionDAG
&DAG
,
876 const SDLoc
&dl
, SDValue
&Chain
, SDValue
*Flag
,
878 ISD::NodeType PreferredExtendType
) const {
879 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
880 ISD::NodeType ExtendKind
= PreferredExtendType
;
882 // Get the list of the values's legal parts.
883 unsigned NumRegs
= Regs
.size();
884 SmallVector
<SDValue
, 8> Parts(NumRegs
);
885 for (unsigned Value
= 0, Part
= 0, e
= ValueVTs
.size(); Value
!= e
; ++Value
) {
886 unsigned NumParts
= RegCount
[Value
];
888 MVT RegisterVT
= isABIMangled() ? TLI
.getRegisterTypeForCallingConv(
890 CallConv
.getValue(), RegVTs
[Value
])
893 if (ExtendKind
== ISD::ANY_EXTEND
&& TLI
.isZExtFree(Val
, RegisterVT
))
894 ExtendKind
= ISD::ZERO_EXTEND
;
896 getCopyToParts(DAG
, dl
, Val
.getValue(Val
.getResNo() + Value
), &Parts
[Part
],
897 NumParts
, RegisterVT
, V
, CallConv
, ExtendKind
);
901 // Copy the parts into the registers.
902 SmallVector
<SDValue
, 8> Chains(NumRegs
);
903 for (unsigned i
= 0; i
!= NumRegs
; ++i
) {
906 Part
= DAG
.getCopyToReg(Chain
, dl
, Regs
[i
], Parts
[i
]);
908 Part
= DAG
.getCopyToReg(Chain
, dl
, Regs
[i
], Parts
[i
], *Flag
);
909 *Flag
= Part
.getValue(1);
912 Chains
[i
] = Part
.getValue(0);
915 if (NumRegs
== 1 || Flag
)
916 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
917 // flagged to it. That is the CopyToReg nodes and the user are considered
918 // a single scheduling unit. If we create a TokenFactor and return it as
919 // chain, then the TokenFactor is both a predecessor (operand) of the
920 // user as well as a successor (the TF operands are flagged to the user).
921 // c1, f1 = CopyToReg
922 // c2, f2 = CopyToReg
923 // c3 = TokenFactor c1, c2
926 Chain
= Chains
[NumRegs
-1];
928 Chain
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Chains
);
931 void RegsForValue::AddInlineAsmOperands(unsigned Code
, bool HasMatching
,
932 unsigned MatchingIdx
, const SDLoc
&dl
,
934 std::vector
<SDValue
> &Ops
) const {
935 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
937 unsigned Flag
= InlineAsm::getFlagWord(Code
, Regs
.size());
939 Flag
= InlineAsm::getFlagWordForMatchingOp(Flag
, MatchingIdx
);
940 else if (!Regs
.empty() &&
941 TargetRegisterInfo::isVirtualRegister(Regs
.front())) {
942 // Put the register class of the virtual registers in the flag word. That
943 // way, later passes can recompute register class constraints for inline
944 // assembly as well as normal instructions.
945 // Don't do this for tied operands that can use the regclass information
947 const MachineRegisterInfo
&MRI
= DAG
.getMachineFunction().getRegInfo();
948 const TargetRegisterClass
*RC
= MRI
.getRegClass(Regs
.front());
949 Flag
= InlineAsm::getFlagWordForRegClass(Flag
, RC
->getID());
952 SDValue Res
= DAG
.getTargetConstant(Flag
, dl
, MVT::i32
);
955 if (Code
== InlineAsm::Kind_Clobber
) {
956 // Clobbers should always have a 1:1 mapping with registers, and may
957 // reference registers that have illegal (e.g. vector) types. Hence, we
958 // shouldn't try to apply any sort of splitting logic to them.
959 assert(Regs
.size() == RegVTs
.size() && Regs
.size() == ValueVTs
.size() &&
960 "No 1:1 mapping from clobbers to regs?");
961 unsigned SP
= TLI
.getStackPointerRegisterToSaveRestore();
963 for (unsigned I
= 0, E
= ValueVTs
.size(); I
!= E
; ++I
) {
964 Ops
.push_back(DAG
.getRegister(Regs
[I
], RegVTs
[I
]));
967 DAG
.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
968 "If we clobbered the stack pointer, MFI should know about it.");
973 for (unsigned Value
= 0, Reg
= 0, e
= ValueVTs
.size(); Value
!= e
; ++Value
) {
974 unsigned NumRegs
= TLI
.getNumRegisters(*DAG
.getContext(), ValueVTs
[Value
]);
975 MVT RegisterVT
= RegVTs
[Value
];
976 for (unsigned i
= 0; i
!= NumRegs
; ++i
) {
977 assert(Reg
< Regs
.size() && "Mismatch in # registers expected");
978 unsigned TheReg
= Regs
[Reg
++];
979 Ops
.push_back(DAG
.getRegister(TheReg
, RegisterVT
));
984 SmallVector
<std::pair
<unsigned, unsigned>, 4>
985 RegsForValue::getRegsAndSizes() const {
986 SmallVector
<std::pair
<unsigned, unsigned>, 4> OutVec
;
988 for (auto CountAndVT
: zip_first(RegCount
, RegVTs
)) {
989 unsigned RegCount
= std::get
<0>(CountAndVT
);
990 MVT RegisterVT
= std::get
<1>(CountAndVT
);
991 unsigned RegisterSize
= RegisterVT
.getSizeInBits();
992 for (unsigned E
= I
+ RegCount
; I
!= E
; ++I
)
993 OutVec
.push_back(std::make_pair(Regs
[I
], RegisterSize
));
998 void SelectionDAGBuilder::init(GCFunctionInfo
*gfi
, AliasAnalysis
*aa
,
999 const TargetLibraryInfo
*li
) {
1003 DL
= &DAG
.getDataLayout();
1004 Context
= DAG
.getContext();
1005 LPadToCallSiteMap
.clear();
1008 void SelectionDAGBuilder::clear() {
1010 UnusedArgNodeMap
.clear();
1011 PendingLoads
.clear();
1012 PendingExports
.clear();
1014 HasTailCall
= false;
1015 SDNodeOrder
= LowestSDNodeOrder
;
1016 StatepointLowering
.clear();
1019 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1020 DanglingDebugInfoMap
.clear();
1023 SDValue
SelectionDAGBuilder::getRoot() {
1024 if (PendingLoads
.empty())
1025 return DAG
.getRoot();
1027 if (PendingLoads
.size() == 1) {
1028 SDValue Root
= PendingLoads
[0];
1030 PendingLoads
.clear();
1034 // Otherwise, we have to make a token factor node.
1035 SDValue Root
= DAG
.getTokenFactor(getCurSDLoc(), PendingLoads
);
1036 PendingLoads
.clear();
1041 SDValue
SelectionDAGBuilder::getControlRoot() {
1042 SDValue Root
= DAG
.getRoot();
1044 if (PendingExports
.empty())
1047 // Turn all of the CopyToReg chains into one factored node.
1048 if (Root
.getOpcode() != ISD::EntryToken
) {
1049 unsigned i
= 0, e
= PendingExports
.size();
1050 for (; i
!= e
; ++i
) {
1051 assert(PendingExports
[i
].getNode()->getNumOperands() > 1);
1052 if (PendingExports
[i
].getNode()->getOperand(0) == Root
)
1053 break; // Don't add the root if we already indirectly depend on it.
1057 PendingExports
.push_back(Root
);
1060 Root
= DAG
.getNode(ISD::TokenFactor
, getCurSDLoc(), MVT::Other
,
1062 PendingExports
.clear();
1067 void SelectionDAGBuilder::visit(const Instruction
&I
) {
1068 // Set up outgoing PHI node register values before emitting the terminator.
1069 if (I
.isTerminator()) {
1070 HandlePHINodesInSuccessorBlocks(I
.getParent());
1073 // Increase the SDNodeOrder if dealing with a non-debug instruction.
1074 if (!isa
<DbgInfoIntrinsic
>(I
))
1079 visit(I
.getOpcode(), I
);
1081 if (auto *FPMO
= dyn_cast
<FPMathOperator
>(&I
)) {
1082 // Propagate the fast-math-flags of this IR instruction to the DAG node that
1083 // maps to this instruction.
1084 // TODO: We could handle all flags (nsw, etc) here.
1085 // TODO: If an IR instruction maps to >1 node, only the final node will have
1087 if (SDNode
*Node
= getNodeForIRValue(&I
)) {
1088 SDNodeFlags IncomingFlags
;
1089 IncomingFlags
.copyFMF(*FPMO
);
1090 if (!Node
->getFlags().isDefined())
1091 Node
->setFlags(IncomingFlags
);
1093 Node
->intersectFlagsWith(IncomingFlags
);
1097 if (!I
.isTerminator() && !HasTailCall
&&
1098 !isStatepoint(&I
)) // statepoints handle their exports internally
1099 CopyToExportRegsIfNeeded(&I
);
1104 void SelectionDAGBuilder::visitPHI(const PHINode
&) {
1105 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1108 void SelectionDAGBuilder::visit(unsigned Opcode
, const User
&I
) {
1109 // Note: this doesn't use InstVisitor, because it has to work with
1110 // ConstantExpr's in addition to instructions.
1112 default: llvm_unreachable("Unknown instruction type encountered!");
1113 // Build the switch statement using the Instruction.def file.
1114 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1115 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1116 #include "llvm/IR/Instruction.def"
1120 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable
*Variable
,
1121 const DIExpression
*Expr
) {
1122 auto isMatchingDbgValue
= [&](DanglingDebugInfo
&DDI
) {
1123 const DbgValueInst
*DI
= DDI
.getDI();
1124 DIVariable
*DanglingVariable
= DI
->getVariable();
1125 DIExpression
*DanglingExpr
= DI
->getExpression();
1126 if (DanglingVariable
== Variable
&& Expr
->fragmentsOverlap(DanglingExpr
)) {
1127 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI
<< "\n");
1133 for (auto &DDIMI
: DanglingDebugInfoMap
) {
1134 DanglingDebugInfoVector
&DDIV
= DDIMI
.second
;
1136 // If debug info is to be dropped, run it through final checks to see
1137 // whether it can be salvaged.
1138 for (auto &DDI
: DDIV
)
1139 if (isMatchingDbgValue(DDI
))
1140 salvageUnresolvedDbgValue(DDI
);
1142 DDIV
.erase(remove_if(DDIV
, isMatchingDbgValue
), DDIV
.end());
1146 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1147 // generate the debug data structures now that we've seen its definition.
1148 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value
*V
,
1150 auto DanglingDbgInfoIt
= DanglingDebugInfoMap
.find(V
);
1151 if (DanglingDbgInfoIt
== DanglingDebugInfoMap
.end())
1154 DanglingDebugInfoVector
&DDIV
= DanglingDbgInfoIt
->second
;
1155 for (auto &DDI
: DDIV
) {
1156 const DbgValueInst
*DI
= DDI
.getDI();
1157 assert(DI
&& "Ill-formed DanglingDebugInfo");
1158 DebugLoc dl
= DDI
.getdl();
1159 unsigned ValSDNodeOrder
= Val
.getNode()->getIROrder();
1160 unsigned DbgSDNodeOrder
= DDI
.getSDNodeOrder();
1161 DILocalVariable
*Variable
= DI
->getVariable();
1162 DIExpression
*Expr
= DI
->getExpression();
1163 assert(Variable
->isValidLocationForIntrinsic(dl
) &&
1164 "Expected inlined-at fields to agree");
1166 if (Val
.getNode()) {
1167 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1168 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1169 // we couldn't resolve it directly when examining the DbgValue intrinsic
1170 // in the first place we should not be more successful here). Unless we
1171 // have some test case that prove this to be correct we should avoid
1172 // calling EmitFuncArgumentDbgValue here.
1173 if (!EmitFuncArgumentDbgValue(V
, Variable
, Expr
, dl
, false, Val
)) {
1174 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1175 << DbgSDNodeOrder
<< "] for:\n " << *DI
<< "\n");
1176 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val
.dump());
1177 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1178 // inserted after the definition of Val when emitting the instructions
1179 // after ISel. An alternative could be to teach
1180 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1181 LLVM_DEBUG(if (ValSDNodeOrder
> DbgSDNodeOrder
) dbgs()
1182 << "changing SDNodeOrder from " << DbgSDNodeOrder
<< " to "
1183 << ValSDNodeOrder
<< "\n");
1184 SDV
= getDbgValue(Val
, Variable
, Expr
, dl
,
1185 std::max(DbgSDNodeOrder
, ValSDNodeOrder
));
1186 DAG
.AddDbgValue(SDV
, Val
.getNode(), false);
1188 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1189 << "in EmitFuncArgumentDbgValue\n");
1191 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI
<< "\n");
1193 UndefValue::get(DDI
.getDI()->getVariableLocation()->getType());
1195 DAG
.getConstantDbgValue(Variable
, Expr
, Undef
, dl
, DbgSDNodeOrder
);
1196 DAG
.AddDbgValue(SDV
, nullptr, false);
1202 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo
&DDI
) {
1203 Value
*V
= DDI
.getDI()->getValue();
1204 DILocalVariable
*Var
= DDI
.getDI()->getVariable();
1205 DIExpression
*Expr
= DDI
.getDI()->getExpression();
1206 DebugLoc DL
= DDI
.getdl();
1207 DebugLoc InstDL
= DDI
.getDI()->getDebugLoc();
1208 unsigned SDOrder
= DDI
.getSDNodeOrder();
1210 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1211 // that DW_OP_stack_value is desired.
1212 assert(isa
<DbgValueInst
>(DDI
.getDI()));
1213 bool StackValue
= true;
1215 // Can this Value can be encoded without any further work?
1216 if (handleDebugValue(V
, Var
, Expr
, DL
, InstDL
, SDOrder
))
1219 // Attempt to salvage back through as many instructions as possible. Bail if
1220 // a non-instruction is seen, such as a constant expression or global
1221 // variable. FIXME: Further work could recover those too.
1222 while (isa
<Instruction
>(V
)) {
1223 Instruction
&VAsInst
= *cast
<Instruction
>(V
);
1224 DIExpression
*NewExpr
= salvageDebugInfoImpl(VAsInst
, Expr
, StackValue
);
1226 // If we cannot salvage any further, and haven't yet found a suitable debug
1227 // expression, bail out.
1231 // New value and expr now represent this debuginfo.
1232 V
= VAsInst
.getOperand(0);
1235 // Some kind of simplification occurred: check whether the operand of the
1236 // salvaged debug expression can be encoded in this DAG.
1237 if (handleDebugValue(V
, Var
, Expr
, DL
, InstDL
, SDOrder
)) {
1238 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
1239 << DDI
.getDI() << "\nBy stripping back to:\n " << V
);
1244 // This was the final opportunity to salvage this debug information, and it
1245 // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1246 // any earlier variable location.
1247 auto Undef
= UndefValue::get(DDI
.getDI()->getVariableLocation()->getType());
1248 auto SDV
= DAG
.getConstantDbgValue(Var
, Expr
, Undef
, DL
, SDNodeOrder
);
1249 DAG
.AddDbgValue(SDV
, nullptr, false);
1251 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI
.getDI()
1253 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI
.getDI()->getOperand(0)
1257 bool SelectionDAGBuilder::handleDebugValue(const Value
*V
, DILocalVariable
*Var
,
1258 DIExpression
*Expr
, DebugLoc dl
,
1259 DebugLoc InstDL
, unsigned Order
) {
1260 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
1262 if (isa
<ConstantInt
>(V
) || isa
<ConstantFP
>(V
) || isa
<UndefValue
>(V
) ||
1263 isa
<ConstantPointerNull
>(V
)) {
1264 SDV
= DAG
.getConstantDbgValue(Var
, Expr
, V
, dl
, SDNodeOrder
);
1265 DAG
.AddDbgValue(SDV
, nullptr, false);
1269 // If the Value is a frame index, we can create a FrameIndex debug value
1270 // without relying on the DAG at all.
1271 if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(V
)) {
1272 auto SI
= FuncInfo
.StaticAllocaMap
.find(AI
);
1273 if (SI
!= FuncInfo
.StaticAllocaMap
.end()) {
1275 DAG
.getFrameIndexDbgValue(Var
, Expr
, SI
->second
,
1276 /*IsIndirect*/ false, dl
, SDNodeOrder
);
1277 // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1278 // is still available even if the SDNode gets optimized out.
1279 DAG
.AddDbgValue(SDV
, nullptr, false);
1284 // Do not use getValue() in here; we don't want to generate code at
1285 // this point if it hasn't been done yet.
1286 SDValue N
= NodeMap
[V
];
1287 if (!N
.getNode() && isa
<Argument
>(V
)) // Check unused arguments map.
1288 N
= UnusedArgNodeMap
[V
];
1290 if (EmitFuncArgumentDbgValue(V
, Var
, Expr
, dl
, false, N
))
1292 SDV
= getDbgValue(N
, Var
, Expr
, dl
, SDNodeOrder
);
1293 DAG
.AddDbgValue(SDV
, N
.getNode(), false);
1297 // Special rules apply for the first dbg.values of parameter variables in a
1298 // function. Identify them by the fact they reference Argument Values, that
1299 // they're parameters, and they are parameters of the current function. We
1300 // need to let them dangle until they get an SDNode.
1301 bool IsParamOfFunc
= isa
<Argument
>(V
) && Var
->isParameter() &&
1302 !InstDL
.getInlinedAt();
1303 if (!IsParamOfFunc
) {
1304 // The value is not used in this block yet (or it would have an SDNode).
1305 // We still want the value to appear for the user if possible -- if it has
1306 // an associated VReg, we can refer to that instead.
1307 auto VMI
= FuncInfo
.ValueMap
.find(V
);
1308 if (VMI
!= FuncInfo
.ValueMap
.end()) {
1309 unsigned Reg
= VMI
->second
;
1310 // If this is a PHI node, it may be split up into several MI PHI nodes
1311 // (in FunctionLoweringInfo::set).
1312 RegsForValue
RFV(V
->getContext(), TLI
, DAG
.getDataLayout(), Reg
,
1313 V
->getType(), None
);
1314 if (RFV
.occupiesMultipleRegs()) {
1315 unsigned Offset
= 0;
1316 unsigned BitsToDescribe
= 0;
1317 if (auto VarSize
= Var
->getSizeInBits())
1318 BitsToDescribe
= *VarSize
;
1319 if (auto Fragment
= Expr
->getFragmentInfo())
1320 BitsToDescribe
= Fragment
->SizeInBits
;
1321 for (auto RegAndSize
: RFV
.getRegsAndSizes()) {
1322 unsigned RegisterSize
= RegAndSize
.second
;
1323 // Bail out if all bits are described already.
1324 if (Offset
>= BitsToDescribe
)
1326 unsigned FragmentSize
= (Offset
+ RegisterSize
> BitsToDescribe
)
1327 ? BitsToDescribe
- Offset
1329 auto FragmentExpr
= DIExpression::createFragmentExpression(
1330 Expr
, Offset
, FragmentSize
);
1333 SDV
= DAG
.getVRegDbgValue(Var
, *FragmentExpr
, RegAndSize
.first
,
1334 false, dl
, SDNodeOrder
);
1335 DAG
.AddDbgValue(SDV
, nullptr, false);
1336 Offset
+= RegisterSize
;
1339 SDV
= DAG
.getVRegDbgValue(Var
, Expr
, Reg
, false, dl
, SDNodeOrder
);
1340 DAG
.AddDbgValue(SDV
, nullptr, false);
1349 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1350 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1351 for (auto &Pair
: DanglingDebugInfoMap
)
1352 for (auto &DDI
: Pair
.getSecond())
1353 salvageUnresolvedDbgValue(DDI
);
1354 clearDanglingDebugInfo();
1357 /// getCopyFromRegs - If there was virtual register allocated for the value V
1358 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1359 SDValue
SelectionDAGBuilder::getCopyFromRegs(const Value
*V
, Type
*Ty
) {
1360 DenseMap
<const Value
*, unsigned>::iterator It
= FuncInfo
.ValueMap
.find(V
);
1363 if (It
!= FuncInfo
.ValueMap
.end()) {
1364 unsigned InReg
= It
->second
;
1366 RegsForValue
RFV(*DAG
.getContext(), DAG
.getTargetLoweringInfo(),
1367 DAG
.getDataLayout(), InReg
, Ty
,
1368 None
); // This is not an ABI copy.
1369 SDValue Chain
= DAG
.getEntryNode();
1370 Result
= RFV
.getCopyFromRegs(DAG
, FuncInfo
, getCurSDLoc(), Chain
, nullptr,
1372 resolveDanglingDebugInfo(V
, Result
);
1378 /// getValue - Return an SDValue for the given Value.
1379 SDValue
SelectionDAGBuilder::getValue(const Value
*V
) {
1380 // If we already have an SDValue for this value, use it. It's important
1381 // to do this first, so that we don't create a CopyFromReg if we already
1382 // have a regular SDValue.
1383 SDValue
&N
= NodeMap
[V
];
1384 if (N
.getNode()) return N
;
1386 // If there's a virtual register allocated and initialized for this
1388 if (SDValue copyFromReg
= getCopyFromRegs(V
, V
->getType()))
1391 // Otherwise create a new SDValue and remember it.
1392 SDValue Val
= getValueImpl(V
);
1394 resolveDanglingDebugInfo(V
, Val
);
1398 // Return true if SDValue exists for the given Value
1399 bool SelectionDAGBuilder::findValue(const Value
*V
) const {
1400 return (NodeMap
.find(V
) != NodeMap
.end()) ||
1401 (FuncInfo
.ValueMap
.find(V
) != FuncInfo
.ValueMap
.end());
1404 /// getNonRegisterValue - Return an SDValue for the given Value, but
1405 /// don't look in FuncInfo.ValueMap for a virtual register.
1406 SDValue
SelectionDAGBuilder::getNonRegisterValue(const Value
*V
) {
1407 // If we already have an SDValue for this value, use it.
1408 SDValue
&N
= NodeMap
[V
];
1410 if (isa
<ConstantSDNode
>(N
) || isa
<ConstantFPSDNode
>(N
)) {
1411 // Remove the debug location from the node as the node is about to be used
1412 // in a location which may differ from the original debug location. This
1413 // is relevant to Constant and ConstantFP nodes because they can appear
1414 // as constant expressions inside PHI nodes.
1415 N
->setDebugLoc(DebugLoc());
1420 // Otherwise create a new SDValue and remember it.
1421 SDValue Val
= getValueImpl(V
);
1423 resolveDanglingDebugInfo(V
, Val
);
1427 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1428 /// Create an SDValue for the given value.
1429 SDValue
SelectionDAGBuilder::getValueImpl(const Value
*V
) {
1430 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
1432 if (const Constant
*C
= dyn_cast
<Constant
>(V
)) {
1433 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), V
->getType(), true);
1435 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(C
))
1436 return DAG
.getConstant(*CI
, getCurSDLoc(), VT
);
1438 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(C
))
1439 return DAG
.getGlobalAddress(GV
, getCurSDLoc(), VT
);
1441 if (isa
<ConstantPointerNull
>(C
)) {
1442 unsigned AS
= V
->getType()->getPointerAddressSpace();
1443 return DAG
.getConstant(0, getCurSDLoc(),
1444 TLI
.getPointerTy(DAG
.getDataLayout(), AS
));
1447 if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(C
))
1448 return DAG
.getConstantFP(*CFP
, getCurSDLoc(), VT
);
1450 if (isa
<UndefValue
>(C
) && !V
->getType()->isAggregateType())
1451 return DAG
.getUNDEF(VT
);
1453 if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
)) {
1454 visit(CE
->getOpcode(), *CE
);
1455 SDValue N1
= NodeMap
[V
];
1456 assert(N1
.getNode() && "visit didn't populate the NodeMap!");
1460 if (isa
<ConstantStruct
>(C
) || isa
<ConstantArray
>(C
)) {
1461 SmallVector
<SDValue
, 4> Constants
;
1462 for (User::const_op_iterator OI
= C
->op_begin(), OE
= C
->op_end();
1464 SDNode
*Val
= getValue(*OI
).getNode();
1465 // If the operand is an empty aggregate, there are no values.
1467 // Add each leaf value from the operand to the Constants list
1468 // to form a flattened list of all the values.
1469 for (unsigned i
= 0, e
= Val
->getNumValues(); i
!= e
; ++i
)
1470 Constants
.push_back(SDValue(Val
, i
));
1473 return DAG
.getMergeValues(Constants
, getCurSDLoc());
1476 if (const ConstantDataSequential
*CDS
=
1477 dyn_cast
<ConstantDataSequential
>(C
)) {
1478 SmallVector
<SDValue
, 4> Ops
;
1479 for (unsigned i
= 0, e
= CDS
->getNumElements(); i
!= e
; ++i
) {
1480 SDNode
*Val
= getValue(CDS
->getElementAsConstant(i
)).getNode();
1481 // Add each leaf value from the operand to the Constants list
1482 // to form a flattened list of all the values.
1483 for (unsigned i
= 0, e
= Val
->getNumValues(); i
!= e
; ++i
)
1484 Ops
.push_back(SDValue(Val
, i
));
1487 if (isa
<ArrayType
>(CDS
->getType()))
1488 return DAG
.getMergeValues(Ops
, getCurSDLoc());
1489 return NodeMap
[V
] = DAG
.getBuildVector(VT
, getCurSDLoc(), Ops
);
1492 if (C
->getType()->isStructTy() || C
->getType()->isArrayTy()) {
1493 assert((isa
<ConstantAggregateZero
>(C
) || isa
<UndefValue
>(C
)) &&
1494 "Unknown struct or array constant!");
1496 SmallVector
<EVT
, 4> ValueVTs
;
1497 ComputeValueVTs(TLI
, DAG
.getDataLayout(), C
->getType(), ValueVTs
);
1498 unsigned NumElts
= ValueVTs
.size();
1500 return SDValue(); // empty struct
1501 SmallVector
<SDValue
, 4> Constants(NumElts
);
1502 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
1503 EVT EltVT
= ValueVTs
[i
];
1504 if (isa
<UndefValue
>(C
))
1505 Constants
[i
] = DAG
.getUNDEF(EltVT
);
1506 else if (EltVT
.isFloatingPoint())
1507 Constants
[i
] = DAG
.getConstantFP(0, getCurSDLoc(), EltVT
);
1509 Constants
[i
] = DAG
.getConstant(0, getCurSDLoc(), EltVT
);
1512 return DAG
.getMergeValues(Constants
, getCurSDLoc());
1515 if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(C
))
1516 return DAG
.getBlockAddress(BA
, VT
);
1518 VectorType
*VecTy
= cast
<VectorType
>(V
->getType());
1519 unsigned NumElements
= VecTy
->getNumElements();
1521 // Now that we know the number and type of the elements, get that number of
1522 // elements into the Ops array based on what kind of constant it is.
1523 SmallVector
<SDValue
, 16> Ops
;
1524 if (const ConstantVector
*CV
= dyn_cast
<ConstantVector
>(C
)) {
1525 for (unsigned i
= 0; i
!= NumElements
; ++i
)
1526 Ops
.push_back(getValue(CV
->getOperand(i
)));
1528 assert(isa
<ConstantAggregateZero
>(C
) && "Unknown vector constant!");
1530 TLI
.getValueType(DAG
.getDataLayout(), VecTy
->getElementType());
1533 if (EltVT
.isFloatingPoint())
1534 Op
= DAG
.getConstantFP(0, getCurSDLoc(), EltVT
);
1536 Op
= DAG
.getConstant(0, getCurSDLoc(), EltVT
);
1537 Ops
.assign(NumElements
, Op
);
1540 // Create a BUILD_VECTOR node.
1541 return NodeMap
[V
] = DAG
.getBuildVector(VT
, getCurSDLoc(), Ops
);
1544 // If this is a static alloca, generate it as the frameindex instead of
1546 if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(V
)) {
1547 DenseMap
<const AllocaInst
*, int>::iterator SI
=
1548 FuncInfo
.StaticAllocaMap
.find(AI
);
1549 if (SI
!= FuncInfo
.StaticAllocaMap
.end())
1550 return DAG
.getFrameIndex(SI
->second
,
1551 TLI
.getFrameIndexTy(DAG
.getDataLayout()));
1554 // If this is an instruction which fast-isel has deferred, select it now.
1555 if (const Instruction
*Inst
= dyn_cast
<Instruction
>(V
)) {
1556 unsigned InReg
= FuncInfo
.InitializeRegForValue(Inst
);
1558 RegsForValue
RFV(*DAG
.getContext(), TLI
, DAG
.getDataLayout(), InReg
,
1559 Inst
->getType(), getABIRegCopyCC(V
));
1560 SDValue Chain
= DAG
.getEntryNode();
1561 return RFV
.getCopyFromRegs(DAG
, FuncInfo
, getCurSDLoc(), Chain
, nullptr, V
);
1564 llvm_unreachable("Can't get register for value!");
1567 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst
&I
) {
1568 auto Pers
= classifyEHPersonality(FuncInfo
.Fn
->getPersonalityFn());
1569 bool IsMSVCCXX
= Pers
== EHPersonality::MSVC_CXX
;
1570 bool IsCoreCLR
= Pers
== EHPersonality::CoreCLR
;
1571 bool IsSEH
= isAsynchronousEHPersonality(Pers
);
1572 bool IsWasmCXX
= Pers
== EHPersonality::Wasm_CXX
;
1573 MachineBasicBlock
*CatchPadMBB
= FuncInfo
.MBB
;
1575 CatchPadMBB
->setIsEHScopeEntry();
1576 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1577 if (IsMSVCCXX
|| IsCoreCLR
)
1578 CatchPadMBB
->setIsEHFuncletEntry();
1579 // Wasm does not need catchpads anymore
1581 DAG
.setRoot(DAG
.getNode(ISD::CATCHPAD
, getCurSDLoc(), MVT::Other
,
1585 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst
&I
) {
1586 // Update machine-CFG edge.
1587 MachineBasicBlock
*TargetMBB
= FuncInfo
.MBBMap
[I
.getSuccessor()];
1588 FuncInfo
.MBB
->addSuccessor(TargetMBB
);
1590 auto Pers
= classifyEHPersonality(FuncInfo
.Fn
->getPersonalityFn());
1591 bool IsSEH
= isAsynchronousEHPersonality(Pers
);
1593 // If this is not a fall-through branch or optimizations are switched off,
1595 if (TargetMBB
!= NextBlock(FuncInfo
.MBB
) ||
1596 TM
.getOptLevel() == CodeGenOpt::None
)
1597 DAG
.setRoot(DAG
.getNode(ISD::BR
, getCurSDLoc(), MVT::Other
,
1598 getControlRoot(), DAG
.getBasicBlock(TargetMBB
)));
1602 // Figure out the funclet membership for the catchret's successor.
1603 // This will be used by the FuncletLayout pass to determine how to order the
1605 // A 'catchret' returns to the outer scope's color.
1606 Value
*ParentPad
= I
.getCatchSwitchParentPad();
1607 const BasicBlock
*SuccessorColor
;
1608 if (isa
<ConstantTokenNone
>(ParentPad
))
1609 SuccessorColor
= &FuncInfo
.Fn
->getEntryBlock();
1611 SuccessorColor
= cast
<Instruction
>(ParentPad
)->getParent();
1612 assert(SuccessorColor
&& "No parent funclet for catchret!");
1613 MachineBasicBlock
*SuccessorColorMBB
= FuncInfo
.MBBMap
[SuccessorColor
];
1614 assert(SuccessorColorMBB
&& "No MBB for SuccessorColor!");
1616 // Create the terminator node.
1617 SDValue Ret
= DAG
.getNode(ISD::CATCHRET
, getCurSDLoc(), MVT::Other
,
1618 getControlRoot(), DAG
.getBasicBlock(TargetMBB
),
1619 DAG
.getBasicBlock(SuccessorColorMBB
));
1623 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst
&CPI
) {
1624 // Don't emit any special code for the cleanuppad instruction. It just marks
1625 // the start of an EH scope/funclet.
1626 FuncInfo
.MBB
->setIsEHScopeEntry();
1627 auto Pers
= classifyEHPersonality(FuncInfo
.Fn
->getPersonalityFn());
1628 if (Pers
!= EHPersonality::Wasm_CXX
) {
1629 FuncInfo
.MBB
->setIsEHFuncletEntry();
1630 FuncInfo
.MBB
->setIsCleanupFuncletEntry();
1634 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1635 // the control flow always stops at the single catch pad, as it does for a
1636 // cleanup pad. In case the exception caught is not of the types the catch pad
1637 // catches, it will be rethrown by a rethrow.
1638 static void findWasmUnwindDestinations(
1639 FunctionLoweringInfo
&FuncInfo
, const BasicBlock
*EHPadBB
,
1640 BranchProbability Prob
,
1641 SmallVectorImpl
<std::pair
<MachineBasicBlock
*, BranchProbability
>>
1644 const Instruction
*Pad
= EHPadBB
->getFirstNonPHI();
1645 if (isa
<CleanupPadInst
>(Pad
)) {
1646 // Stop on cleanup pads.
1647 UnwindDests
.emplace_back(FuncInfo
.MBBMap
[EHPadBB
], Prob
);
1648 UnwindDests
.back().first
->setIsEHScopeEntry();
1650 } else if (auto *CatchSwitch
= dyn_cast
<CatchSwitchInst
>(Pad
)) {
1651 // Add the catchpad handlers to the possible destinations. We don't
1652 // continue to the unwind destination of the catchswitch for wasm.
1653 for (const BasicBlock
*CatchPadBB
: CatchSwitch
->handlers()) {
1654 UnwindDests
.emplace_back(FuncInfo
.MBBMap
[CatchPadBB
], Prob
);
1655 UnwindDests
.back().first
->setIsEHScopeEntry();
1664 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1665 /// many places it could ultimately go. In the IR, we have a single unwind
1666 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1667 /// This function skips over imaginary basic blocks that hold catchswitch
1668 /// instructions, and finds all the "real" machine
1669 /// basic block destinations. As those destinations may not be successors of
1670 /// EHPadBB, here we also calculate the edge probability to those destinations.
1671 /// The passed-in Prob is the edge probability to EHPadBB.
1672 static void findUnwindDestinations(
1673 FunctionLoweringInfo
&FuncInfo
, const BasicBlock
*EHPadBB
,
1674 BranchProbability Prob
,
1675 SmallVectorImpl
<std::pair
<MachineBasicBlock
*, BranchProbability
>>
1677 EHPersonality Personality
=
1678 classifyEHPersonality(FuncInfo
.Fn
->getPersonalityFn());
1679 bool IsMSVCCXX
= Personality
== EHPersonality::MSVC_CXX
;
1680 bool IsCoreCLR
= Personality
== EHPersonality::CoreCLR
;
1681 bool IsWasmCXX
= Personality
== EHPersonality::Wasm_CXX
;
1682 bool IsSEH
= isAsynchronousEHPersonality(Personality
);
1685 findWasmUnwindDestinations(FuncInfo
, EHPadBB
, Prob
, UnwindDests
);
1690 const Instruction
*Pad
= EHPadBB
->getFirstNonPHI();
1691 BasicBlock
*NewEHPadBB
= nullptr;
1692 if (isa
<LandingPadInst
>(Pad
)) {
1693 // Stop on landingpads. They are not funclets.
1694 UnwindDests
.emplace_back(FuncInfo
.MBBMap
[EHPadBB
], Prob
);
1696 } else if (isa
<CleanupPadInst
>(Pad
)) {
1697 // Stop on cleanup pads. Cleanups are always funclet entries for all known
1699 UnwindDests
.emplace_back(FuncInfo
.MBBMap
[EHPadBB
], Prob
);
1700 UnwindDests
.back().first
->setIsEHScopeEntry();
1701 UnwindDests
.back().first
->setIsEHFuncletEntry();
1703 } else if (auto *CatchSwitch
= dyn_cast
<CatchSwitchInst
>(Pad
)) {
1704 // Add the catchpad handlers to the possible destinations.
1705 for (const BasicBlock
*CatchPadBB
: CatchSwitch
->handlers()) {
1706 UnwindDests
.emplace_back(FuncInfo
.MBBMap
[CatchPadBB
], Prob
);
1707 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1708 if (IsMSVCCXX
|| IsCoreCLR
)
1709 UnwindDests
.back().first
->setIsEHFuncletEntry();
1711 UnwindDests
.back().first
->setIsEHScopeEntry();
1713 NewEHPadBB
= CatchSwitch
->getUnwindDest();
1718 BranchProbabilityInfo
*BPI
= FuncInfo
.BPI
;
1719 if (BPI
&& NewEHPadBB
)
1720 Prob
*= BPI
->getEdgeProbability(EHPadBB
, NewEHPadBB
);
1721 EHPadBB
= NewEHPadBB
;
1725 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst
&I
) {
1726 // Update successor info.
1727 SmallVector
<std::pair
<MachineBasicBlock
*, BranchProbability
>, 1> UnwindDests
;
1728 auto UnwindDest
= I
.getUnwindDest();
1729 BranchProbabilityInfo
*BPI
= FuncInfo
.BPI
;
1730 BranchProbability UnwindDestProb
=
1732 ? BPI
->getEdgeProbability(FuncInfo
.MBB
->getBasicBlock(), UnwindDest
)
1733 : BranchProbability::getZero();
1734 findUnwindDestinations(FuncInfo
, UnwindDest
, UnwindDestProb
, UnwindDests
);
1735 for (auto &UnwindDest
: UnwindDests
) {
1736 UnwindDest
.first
->setIsEHPad();
1737 addSuccessorWithProb(FuncInfo
.MBB
, UnwindDest
.first
, UnwindDest
.second
);
1739 FuncInfo
.MBB
->normalizeSuccProbs();
1741 // Create the terminator node.
1743 DAG
.getNode(ISD::CLEANUPRET
, getCurSDLoc(), MVT::Other
, getControlRoot());
1747 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst
&CSI
) {
1748 report_fatal_error("visitCatchSwitch not yet implemented!");
1751 void SelectionDAGBuilder::visitRet(const ReturnInst
&I
) {
1752 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
1753 auto &DL
= DAG
.getDataLayout();
1754 SDValue Chain
= getControlRoot();
1755 SmallVector
<ISD::OutputArg
, 8> Outs
;
1756 SmallVector
<SDValue
, 8> OutVals
;
1758 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1761 // %val = call <ty> @llvm.experimental.deoptimize()
1765 if (I
.getParent()->getTerminatingDeoptimizeCall()) {
1766 LowerDeoptimizingReturn();
1770 if (!FuncInfo
.CanLowerReturn
) {
1771 unsigned DemoteReg
= FuncInfo
.DemoteRegister
;
1772 const Function
*F
= I
.getParent()->getParent();
1774 // Emit a store of the return value through the virtual register.
1775 // Leave Outs empty so that LowerReturn won't try to load return
1776 // registers the usual way.
1777 SmallVector
<EVT
, 1> PtrValueVTs
;
1778 ComputeValueVTs(TLI
, DL
,
1779 F
->getReturnType()->getPointerTo(
1780 DAG
.getDataLayout().getAllocaAddrSpace()),
1783 SDValue RetPtr
= DAG
.getCopyFromReg(DAG
.getEntryNode(), getCurSDLoc(),
1784 DemoteReg
, PtrValueVTs
[0]);
1785 SDValue RetOp
= getValue(I
.getOperand(0));
1787 SmallVector
<EVT
, 4> ValueVTs
;
1788 SmallVector
<uint64_t, 4> Offsets
;
1789 ComputeValueVTs(TLI
, DL
, I
.getOperand(0)->getType(), ValueVTs
, &Offsets
);
1790 unsigned NumValues
= ValueVTs
.size();
1792 SmallVector
<SDValue
, 4> Chains(NumValues
);
1793 for (unsigned i
= 0; i
!= NumValues
; ++i
) {
1794 // An aggregate return value cannot wrap around the address space, so
1795 // offsets to its parts don't wrap either.
1796 SDValue Ptr
= DAG
.getObjectPtrOffset(getCurSDLoc(), RetPtr
, Offsets
[i
]);
1797 Chains
[i
] = DAG
.getStore(
1798 Chain
, getCurSDLoc(), SDValue(RetOp
.getNode(), RetOp
.getResNo() + i
),
1799 // FIXME: better loc info would be nice.
1800 Ptr
, MachinePointerInfo::getUnknownStack(DAG
.getMachineFunction()));
1803 Chain
= DAG
.getNode(ISD::TokenFactor
, getCurSDLoc(),
1804 MVT::Other
, Chains
);
1805 } else if (I
.getNumOperands() != 0) {
1806 SmallVector
<EVT
, 4> ValueVTs
;
1807 ComputeValueVTs(TLI
, DL
, I
.getOperand(0)->getType(), ValueVTs
);
1808 unsigned NumValues
= ValueVTs
.size();
1810 SDValue RetOp
= getValue(I
.getOperand(0));
1812 const Function
*F
= I
.getParent()->getParent();
1814 ISD::NodeType ExtendKind
= ISD::ANY_EXTEND
;
1815 if (F
->getAttributes().hasAttribute(AttributeList::ReturnIndex
,
1817 ExtendKind
= ISD::SIGN_EXTEND
;
1818 else if (F
->getAttributes().hasAttribute(AttributeList::ReturnIndex
,
1820 ExtendKind
= ISD::ZERO_EXTEND
;
1822 LLVMContext
&Context
= F
->getContext();
1823 bool RetInReg
= F
->getAttributes().hasAttribute(
1824 AttributeList::ReturnIndex
, Attribute::InReg
);
1826 for (unsigned j
= 0; j
!= NumValues
; ++j
) {
1827 EVT VT
= ValueVTs
[j
];
1829 if (ExtendKind
!= ISD::ANY_EXTEND
&& VT
.isInteger())
1830 VT
= TLI
.getTypeForExtReturn(Context
, VT
, ExtendKind
);
1832 CallingConv::ID CC
= F
->getCallingConv();
1834 unsigned NumParts
= TLI
.getNumRegistersForCallingConv(Context
, CC
, VT
);
1835 MVT PartVT
= TLI
.getRegisterTypeForCallingConv(Context
, CC
, VT
);
1836 SmallVector
<SDValue
, 4> Parts(NumParts
);
1837 getCopyToParts(DAG
, getCurSDLoc(),
1838 SDValue(RetOp
.getNode(), RetOp
.getResNo() + j
),
1839 &Parts
[0], NumParts
, PartVT
, &I
, CC
, ExtendKind
);
1841 // 'inreg' on function refers to return value
1842 ISD::ArgFlagsTy Flags
= ISD::ArgFlagsTy();
1846 // Propagate extension type if any
1847 if (ExtendKind
== ISD::SIGN_EXTEND
)
1849 else if (ExtendKind
== ISD::ZERO_EXTEND
)
1852 for (unsigned i
= 0; i
< NumParts
; ++i
) {
1853 Outs
.push_back(ISD::OutputArg(Flags
, Parts
[i
].getValueType(),
1854 VT
, /*isfixed=*/true, 0, 0));
1855 OutVals
.push_back(Parts
[i
]);
1861 // Push in swifterror virtual register as the last element of Outs. This makes
1862 // sure swifterror virtual register will be returned in the swifterror
1863 // physical register.
1864 const Function
*F
= I
.getParent()->getParent();
1865 if (TLI
.supportSwiftError() &&
1866 F
->getAttributes().hasAttrSomewhere(Attribute::SwiftError
)) {
1867 assert(FuncInfo
.SwiftErrorArg
&& "Need a swift error argument");
1868 ISD::ArgFlagsTy Flags
= ISD::ArgFlagsTy();
1869 Flags
.setSwiftError();
1870 Outs
.push_back(ISD::OutputArg(Flags
, EVT(TLI
.getPointerTy(DL
)) /*vt*/,
1871 EVT(TLI
.getPointerTy(DL
)) /*argvt*/,
1872 true /*isfixed*/, 1 /*origidx*/,
1874 // Create SDNode for the swifterror virtual register.
1876 DAG
.getRegister(FuncInfo
.getOrCreateSwiftErrorVRegUseAt(
1877 &I
, FuncInfo
.MBB
, FuncInfo
.SwiftErrorArg
).first
,
1878 EVT(TLI
.getPointerTy(DL
))));
1881 bool isVarArg
= DAG
.getMachineFunction().getFunction().isVarArg();
1882 CallingConv::ID CallConv
=
1883 DAG
.getMachineFunction().getFunction().getCallingConv();
1884 Chain
= DAG
.getTargetLoweringInfo().LowerReturn(
1885 Chain
, CallConv
, isVarArg
, Outs
, OutVals
, getCurSDLoc(), DAG
);
1887 // Verify that the target's LowerReturn behaved as expected.
1888 assert(Chain
.getNode() && Chain
.getValueType() == MVT::Other
&&
1889 "LowerReturn didn't return a valid chain!");
1891 // Update the DAG with the new chain value resulting from return lowering.
1895 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1896 /// created for it, emit nodes to copy the value into the virtual
1898 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value
*V
) {
1900 if (V
->getType()->isEmptyTy())
1903 DenseMap
<const Value
*, unsigned>::iterator VMI
= FuncInfo
.ValueMap
.find(V
);
1904 if (VMI
!= FuncInfo
.ValueMap
.end()) {
1905 assert(!V
->use_empty() && "Unused value assigned virtual registers!");
1906 CopyValueToVirtualRegister(V
, VMI
->second
);
1910 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1911 /// the current basic block, add it to ValueMap now so that we'll get a
1913 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value
*V
) {
1914 // No need to export constants.
1915 if (!isa
<Instruction
>(V
) && !isa
<Argument
>(V
)) return;
1917 // Already exported?
1918 if (FuncInfo
.isExportedInst(V
)) return;
1920 unsigned Reg
= FuncInfo
.InitializeRegForValue(V
);
1921 CopyValueToVirtualRegister(V
, Reg
);
1924 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value
*V
,
1925 const BasicBlock
*FromBB
) {
1926 // The operands of the setcc have to be in this block. We don't know
1927 // how to export them from some other block.
1928 if (const Instruction
*VI
= dyn_cast
<Instruction
>(V
)) {
1929 // Can export from current BB.
1930 if (VI
->getParent() == FromBB
)
1933 // Is already exported, noop.
1934 return FuncInfo
.isExportedInst(V
);
1937 // If this is an argument, we can export it if the BB is the entry block or
1938 // if it is already exported.
1939 if (isa
<Argument
>(V
)) {
1940 if (FromBB
== &FromBB
->getParent()->getEntryBlock())
1943 // Otherwise, can only export this if it is already exported.
1944 return FuncInfo
.isExportedInst(V
);
1947 // Otherwise, constants can always be exported.
1951 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1953 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock
*Src
,
1954 const MachineBasicBlock
*Dst
) const {
1955 BranchProbabilityInfo
*BPI
= FuncInfo
.BPI
;
1956 const BasicBlock
*SrcBB
= Src
->getBasicBlock();
1957 const BasicBlock
*DstBB
= Dst
->getBasicBlock();
1959 // If BPI is not available, set the default probability as 1 / N, where N is
1960 // the number of successors.
1961 auto SuccSize
= std::max
<uint32_t>(succ_size(SrcBB
), 1);
1962 return BranchProbability(1, SuccSize
);
1964 return BPI
->getEdgeProbability(SrcBB
, DstBB
);
1967 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock
*Src
,
1968 MachineBasicBlock
*Dst
,
1969 BranchProbability Prob
) {
1971 Src
->addSuccessorWithoutProb(Dst
);
1973 if (Prob
.isUnknown())
1974 Prob
= getEdgeProbability(Src
, Dst
);
1975 Src
->addSuccessor(Dst
, Prob
);
1979 static bool InBlock(const Value
*V
, const BasicBlock
*BB
) {
1980 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
))
1981 return I
->getParent() == BB
;
1985 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1986 /// This function emits a branch and is used at the leaves of an OR or an
1987 /// AND operator tree.
1989 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value
*Cond
,
1990 MachineBasicBlock
*TBB
,
1991 MachineBasicBlock
*FBB
,
1992 MachineBasicBlock
*CurBB
,
1993 MachineBasicBlock
*SwitchBB
,
1994 BranchProbability TProb
,
1995 BranchProbability FProb
,
1997 const BasicBlock
*BB
= CurBB
->getBasicBlock();
1999 // If the leaf of the tree is a comparison, merge the condition into
2001 if (const CmpInst
*BOp
= dyn_cast
<CmpInst
>(Cond
)) {
2002 // The operands of the cmp have to be in this block. We don't know
2003 // how to export them from some other block. If this is the first block
2004 // of the sequence, no exporting is needed.
2005 if (CurBB
== SwitchBB
||
2006 (isExportableFromCurrentBlock(BOp
->getOperand(0), BB
) &&
2007 isExportableFromCurrentBlock(BOp
->getOperand(1), BB
))) {
2008 ISD::CondCode Condition
;
2009 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(Cond
)) {
2010 ICmpInst::Predicate Pred
=
2011 InvertCond
? IC
->getInversePredicate() : IC
->getPredicate();
2012 Condition
= getICmpCondCode(Pred
);
2014 const FCmpInst
*FC
= cast
<FCmpInst
>(Cond
);
2015 FCmpInst::Predicate Pred
=
2016 InvertCond
? FC
->getInversePredicate() : FC
->getPredicate();
2017 Condition
= getFCmpCondCode(Pred
);
2018 if (TM
.Options
.NoNaNsFPMath
)
2019 Condition
= getFCmpCodeWithoutNaN(Condition
);
2022 CaseBlock
CB(Condition
, BOp
->getOperand(0), BOp
->getOperand(1), nullptr,
2023 TBB
, FBB
, CurBB
, getCurSDLoc(), TProb
, FProb
);
2024 SwitchCases
.push_back(CB
);
2029 // Create a CaseBlock record representing this branch.
2030 ISD::CondCode Opc
= InvertCond
? ISD::SETNE
: ISD::SETEQ
;
2031 CaseBlock
CB(Opc
, Cond
, ConstantInt::getTrue(*DAG
.getContext()),
2032 nullptr, TBB
, FBB
, CurBB
, getCurSDLoc(), TProb
, FProb
);
2033 SwitchCases
.push_back(CB
);
2036 void SelectionDAGBuilder::FindMergedConditions(const Value
*Cond
,
2037 MachineBasicBlock
*TBB
,
2038 MachineBasicBlock
*FBB
,
2039 MachineBasicBlock
*CurBB
,
2040 MachineBasicBlock
*SwitchBB
,
2041 Instruction::BinaryOps Opc
,
2042 BranchProbability TProb
,
2043 BranchProbability FProb
,
2045 // Skip over not part of the tree and remember to invert op and operands at
2048 if (match(Cond
, m_OneUse(m_Not(m_Value(NotCond
)))) &&
2049 InBlock(NotCond
, CurBB
->getBasicBlock())) {
2050 FindMergedConditions(NotCond
, TBB
, FBB
, CurBB
, SwitchBB
, Opc
, TProb
, FProb
,
2055 const Instruction
*BOp
= dyn_cast
<Instruction
>(Cond
);
2056 // Compute the effective opcode for Cond, taking into account whether it needs
2057 // to be inverted, e.g.
2058 // and (not (or A, B)), C
2060 // and (and (not A, not B), C)
2063 BOpc
= BOp
->getOpcode();
2065 if (BOpc
== Instruction::And
)
2066 BOpc
= Instruction::Or
;
2067 else if (BOpc
== Instruction::Or
)
2068 BOpc
= Instruction::And
;
2072 // If this node is not part of the or/and tree, emit it as a branch.
2073 if (!BOp
|| !(isa
<BinaryOperator
>(BOp
) || isa
<CmpInst
>(BOp
)) ||
2074 BOpc
!= unsigned(Opc
) || !BOp
->hasOneUse() ||
2075 BOp
->getParent() != CurBB
->getBasicBlock() ||
2076 !InBlock(BOp
->getOperand(0), CurBB
->getBasicBlock()) ||
2077 !InBlock(BOp
->getOperand(1), CurBB
->getBasicBlock())) {
2078 EmitBranchForMergedCondition(Cond
, TBB
, FBB
, CurBB
, SwitchBB
,
2079 TProb
, FProb
, InvertCond
);
2083 // Create TmpBB after CurBB.
2084 MachineFunction::iterator
BBI(CurBB
);
2085 MachineFunction
&MF
= DAG
.getMachineFunction();
2086 MachineBasicBlock
*TmpBB
= MF
.CreateMachineBasicBlock(CurBB
->getBasicBlock());
2087 CurBB
->getParent()->insert(++BBI
, TmpBB
);
2089 if (Opc
== Instruction::Or
) {
2090 // Codegen X | Y as:
2099 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2100 // The requirement is that
2101 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2102 // = TrueProb for original BB.
2103 // Assuming the original probabilities are A and B, one choice is to set
2104 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2105 // A/(1+B) and 2B/(1+B). This choice assumes that
2106 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2107 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2108 // TmpBB, but the math is more complicated.
2110 auto NewTrueProb
= TProb
/ 2;
2111 auto NewFalseProb
= TProb
/ 2 + FProb
;
2112 // Emit the LHS condition.
2113 FindMergedConditions(BOp
->getOperand(0), TBB
, TmpBB
, CurBB
, SwitchBB
, Opc
,
2114 NewTrueProb
, NewFalseProb
, InvertCond
);
2116 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2117 SmallVector
<BranchProbability
, 2> Probs
{TProb
/ 2, FProb
};
2118 BranchProbability::normalizeProbabilities(Probs
.begin(), Probs
.end());
2119 // Emit the RHS condition into TmpBB.
2120 FindMergedConditions(BOp
->getOperand(1), TBB
, FBB
, TmpBB
, SwitchBB
, Opc
,
2121 Probs
[0], Probs
[1], InvertCond
);
2123 assert(Opc
== Instruction::And
&& "Unknown merge op!");
2124 // Codegen X & Y as:
2132 // This requires creation of TmpBB after CurBB.
2134 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2135 // The requirement is that
2136 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2137 // = FalseProb for original BB.
2138 // Assuming the original probabilities are A and B, one choice is to set
2139 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2140 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2141 // TrueProb for BB1 * FalseProb for TmpBB.
2143 auto NewTrueProb
= TProb
+ FProb
/ 2;
2144 auto NewFalseProb
= FProb
/ 2;
2145 // Emit the LHS condition.
2146 FindMergedConditions(BOp
->getOperand(0), TmpBB
, FBB
, CurBB
, SwitchBB
, Opc
,
2147 NewTrueProb
, NewFalseProb
, InvertCond
);
2149 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2150 SmallVector
<BranchProbability
, 2> Probs
{TProb
, FProb
/ 2};
2151 BranchProbability::normalizeProbabilities(Probs
.begin(), Probs
.end());
2152 // Emit the RHS condition into TmpBB.
2153 FindMergedConditions(BOp
->getOperand(1), TBB
, FBB
, TmpBB
, SwitchBB
, Opc
,
2154 Probs
[0], Probs
[1], InvertCond
);
2158 /// If the set of cases should be emitted as a series of branches, return true.
2159 /// If we should emit this as a bunch of and/or'd together conditions, return
2162 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector
<CaseBlock
> &Cases
) {
2163 if (Cases
.size() != 2) return true;
2165 // If this is two comparisons of the same values or'd or and'd together, they
2166 // will get folded into a single comparison, so don't emit two blocks.
2167 if ((Cases
[0].CmpLHS
== Cases
[1].CmpLHS
&&
2168 Cases
[0].CmpRHS
== Cases
[1].CmpRHS
) ||
2169 (Cases
[0].CmpRHS
== Cases
[1].CmpLHS
&&
2170 Cases
[0].CmpLHS
== Cases
[1].CmpRHS
)) {
2174 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2175 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2176 if (Cases
[0].CmpRHS
== Cases
[1].CmpRHS
&&
2177 Cases
[0].CC
== Cases
[1].CC
&&
2178 isa
<Constant
>(Cases
[0].CmpRHS
) &&
2179 cast
<Constant
>(Cases
[0].CmpRHS
)->isNullValue()) {
2180 if (Cases
[0].CC
== ISD::SETEQ
&& Cases
[0].TrueBB
== Cases
[1].ThisBB
)
2182 if (Cases
[0].CC
== ISD::SETNE
&& Cases
[0].FalseBB
== Cases
[1].ThisBB
)
2189 void SelectionDAGBuilder::visitBr(const BranchInst
&I
) {
2190 MachineBasicBlock
*BrMBB
= FuncInfo
.MBB
;
2192 // Update machine-CFG edges.
2193 MachineBasicBlock
*Succ0MBB
= FuncInfo
.MBBMap
[I
.getSuccessor(0)];
2195 if (I
.isUnconditional()) {
2196 // Update machine-CFG edges.
2197 BrMBB
->addSuccessor(Succ0MBB
);
2199 // If this is not a fall-through branch or optimizations are switched off,
2201 if (Succ0MBB
!= NextBlock(BrMBB
) || TM
.getOptLevel() == CodeGenOpt::None
)
2202 DAG
.setRoot(DAG
.getNode(ISD::BR
, getCurSDLoc(),
2203 MVT::Other
, getControlRoot(),
2204 DAG
.getBasicBlock(Succ0MBB
)));
2209 // If this condition is one of the special cases we handle, do special stuff
2211 const Value
*CondVal
= I
.getCondition();
2212 MachineBasicBlock
*Succ1MBB
= FuncInfo
.MBBMap
[I
.getSuccessor(1)];
2214 // If this is a series of conditions that are or'd or and'd together, emit
2215 // this as a sequence of branches instead of setcc's with and/or operations.
2216 // As long as jumps are not expensive, this should improve performance.
2217 // For example, instead of something like:
2229 if (const BinaryOperator
*BOp
= dyn_cast
<BinaryOperator
>(CondVal
)) {
2230 Instruction::BinaryOps Opcode
= BOp
->getOpcode();
2231 if (!DAG
.getTargetLoweringInfo().isJumpExpensive() && BOp
->hasOneUse() &&
2232 !I
.getMetadata(LLVMContext::MD_unpredictable
) &&
2233 (Opcode
== Instruction::And
|| Opcode
== Instruction::Or
)) {
2234 FindMergedConditions(BOp
, Succ0MBB
, Succ1MBB
, BrMBB
, BrMBB
,
2236 getEdgeProbability(BrMBB
, Succ0MBB
),
2237 getEdgeProbability(BrMBB
, Succ1MBB
),
2238 /*InvertCond=*/false);
2239 // If the compares in later blocks need to use values not currently
2240 // exported from this block, export them now. This block should always
2241 // be the first entry.
2242 assert(SwitchCases
[0].ThisBB
== BrMBB
&& "Unexpected lowering!");
2244 // Allow some cases to be rejected.
2245 if (ShouldEmitAsBranches(SwitchCases
)) {
2246 for (unsigned i
= 1, e
= SwitchCases
.size(); i
!= e
; ++i
) {
2247 ExportFromCurrentBlock(SwitchCases
[i
].CmpLHS
);
2248 ExportFromCurrentBlock(SwitchCases
[i
].CmpRHS
);
2251 // Emit the branch for this block.
2252 visitSwitchCase(SwitchCases
[0], BrMBB
);
2253 SwitchCases
.erase(SwitchCases
.begin());
2257 // Okay, we decided not to do this, remove any inserted MBB's and clear
2259 for (unsigned i
= 1, e
= SwitchCases
.size(); i
!= e
; ++i
)
2260 FuncInfo
.MF
->erase(SwitchCases
[i
].ThisBB
);
2262 SwitchCases
.clear();
2266 // Create a CaseBlock record representing this branch.
2267 CaseBlock
CB(ISD::SETEQ
, CondVal
, ConstantInt::getTrue(*DAG
.getContext()),
2268 nullptr, Succ0MBB
, Succ1MBB
, BrMBB
, getCurSDLoc());
2270 // Use visitSwitchCase to actually insert the fast branch sequence for this
2272 visitSwitchCase(CB
, BrMBB
);
2275 /// visitSwitchCase - Emits the necessary code to represent a single node in
2276 /// the binary search tree resulting from lowering a switch instruction.
2277 void SelectionDAGBuilder::visitSwitchCase(CaseBlock
&CB
,
2278 MachineBasicBlock
*SwitchBB
) {
2280 SDValue CondLHS
= getValue(CB
.CmpLHS
);
2283 // Build the setcc now.
2285 // Fold "(X == true)" to X and "(X == false)" to !X to
2286 // handle common cases produced by branch lowering.
2287 if (CB
.CmpRHS
== ConstantInt::getTrue(*DAG
.getContext()) &&
2288 CB
.CC
== ISD::SETEQ
)
2290 else if (CB
.CmpRHS
== ConstantInt::getFalse(*DAG
.getContext()) &&
2291 CB
.CC
== ISD::SETEQ
) {
2292 SDValue True
= DAG
.getConstant(1, dl
, CondLHS
.getValueType());
2293 Cond
= DAG
.getNode(ISD::XOR
, dl
, CondLHS
.getValueType(), CondLHS
, True
);
2295 Cond
= DAG
.getSetCC(dl
, MVT::i1
, CondLHS
, getValue(CB
.CmpRHS
), CB
.CC
);
2297 assert(CB
.CC
== ISD::SETLE
&& "Can handle only LE ranges now");
2299 const APInt
& Low
= cast
<ConstantInt
>(CB
.CmpLHS
)->getValue();
2300 const APInt
& High
= cast
<ConstantInt
>(CB
.CmpRHS
)->getValue();
2302 SDValue CmpOp
= getValue(CB
.CmpMHS
);
2303 EVT VT
= CmpOp
.getValueType();
2305 if (cast
<ConstantInt
>(CB
.CmpLHS
)->isMinValue(true)) {
2306 Cond
= DAG
.getSetCC(dl
, MVT::i1
, CmpOp
, DAG
.getConstant(High
, dl
, VT
),
2309 SDValue SUB
= DAG
.getNode(ISD::SUB
, dl
,
2310 VT
, CmpOp
, DAG
.getConstant(Low
, dl
, VT
));
2311 Cond
= DAG
.getSetCC(dl
, MVT::i1
, SUB
,
2312 DAG
.getConstant(High
-Low
, dl
, VT
), ISD::SETULE
);
2316 // Update successor info
2317 addSuccessorWithProb(SwitchBB
, CB
.TrueBB
, CB
.TrueProb
);
2318 // TrueBB and FalseBB are always different unless the incoming IR is
2319 // degenerate. This only happens when running llc on weird IR.
2320 if (CB
.TrueBB
!= CB
.FalseBB
)
2321 addSuccessorWithProb(SwitchBB
, CB
.FalseBB
, CB
.FalseProb
);
2322 SwitchBB
->normalizeSuccProbs();
2324 // If the lhs block is the next block, invert the condition so that we can
2325 // fall through to the lhs instead of the rhs block.
2326 if (CB
.TrueBB
== NextBlock(SwitchBB
)) {
2327 std::swap(CB
.TrueBB
, CB
.FalseBB
);
2328 SDValue True
= DAG
.getConstant(1, dl
, Cond
.getValueType());
2329 Cond
= DAG
.getNode(ISD::XOR
, dl
, Cond
.getValueType(), Cond
, True
);
2332 SDValue BrCond
= DAG
.getNode(ISD::BRCOND
, dl
,
2333 MVT::Other
, getControlRoot(), Cond
,
2334 DAG
.getBasicBlock(CB
.TrueBB
));
2336 // Insert the false branch. Do this even if it's a fall through branch,
2337 // this makes it easier to do DAG optimizations which require inverting
2338 // the branch condition.
2339 BrCond
= DAG
.getNode(ISD::BR
, dl
, MVT::Other
, BrCond
,
2340 DAG
.getBasicBlock(CB
.FalseBB
));
2342 DAG
.setRoot(BrCond
);
2345 /// visitJumpTable - Emit JumpTable node in the current MBB
2346 void SelectionDAGBuilder::visitJumpTable(JumpTable
&JT
) {
2347 // Emit the code for the jump table
2348 assert(JT
.Reg
!= -1U && "Should lower JT Header first!");
2349 EVT PTy
= DAG
.getTargetLoweringInfo().getPointerTy(DAG
.getDataLayout());
2350 SDValue Index
= DAG
.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2352 SDValue Table
= DAG
.getJumpTable(JT
.JTI
, PTy
);
2353 SDValue BrJumpTable
= DAG
.getNode(ISD::BR_JT
, getCurSDLoc(),
2354 MVT::Other
, Index
.getValue(1),
2356 DAG
.setRoot(BrJumpTable
);
2359 /// visitJumpTableHeader - This function emits necessary code to produce index
2360 /// in the JumpTable from switch case.
2361 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable
&JT
,
2362 JumpTableHeader
&JTH
,
2363 MachineBasicBlock
*SwitchBB
) {
2364 SDLoc dl
= getCurSDLoc();
2366 // Subtract the lowest switch case value from the value being switched on and
2367 // conditional branch to default mbb if the result is greater than the
2368 // difference between smallest and largest cases.
2369 SDValue SwitchOp
= getValue(JTH
.SValue
);
2370 EVT VT
= SwitchOp
.getValueType();
2371 SDValue Sub
= DAG
.getNode(ISD::SUB
, dl
, VT
, SwitchOp
,
2372 DAG
.getConstant(JTH
.First
, dl
, VT
));
2374 // The SDNode we just created, which holds the value being switched on minus
2375 // the smallest case value, needs to be copied to a virtual register so it
2376 // can be used as an index into the jump table in a subsequent basic block.
2377 // This value may be smaller or larger than the target's pointer type, and
2378 // therefore require extension or truncating.
2379 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2380 SwitchOp
= DAG
.getZExtOrTrunc(Sub
, dl
, TLI
.getPointerTy(DAG
.getDataLayout()));
2382 unsigned JumpTableReg
=
2383 FuncInfo
.CreateReg(TLI
.getPointerTy(DAG
.getDataLayout()));
2384 SDValue CopyTo
= DAG
.getCopyToReg(getControlRoot(), dl
,
2385 JumpTableReg
, SwitchOp
);
2386 JT
.Reg
= JumpTableReg
;
2388 // Emit the range check for the jump table, and branch to the default block
2389 // for the switch statement if the value being switched on exceeds the largest
2390 // case in the switch.
2391 SDValue CMP
= DAG
.getSetCC(
2392 dl
, TLI
.getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(),
2393 Sub
.getValueType()),
2394 Sub
, DAG
.getConstant(JTH
.Last
- JTH
.First
, dl
, VT
), ISD::SETUGT
);
2396 SDValue BrCond
= DAG
.getNode(ISD::BRCOND
, dl
,
2397 MVT::Other
, CopyTo
, CMP
,
2398 DAG
.getBasicBlock(JT
.Default
));
2400 // Avoid emitting unnecessary branches to the next block.
2401 if (JT
.MBB
!= NextBlock(SwitchBB
))
2402 BrCond
= DAG
.getNode(ISD::BR
, dl
, MVT::Other
, BrCond
,
2403 DAG
.getBasicBlock(JT
.MBB
));
2405 DAG
.setRoot(BrCond
);
2408 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2409 /// variable if there exists one.
2410 static SDValue
getLoadStackGuard(SelectionDAG
&DAG
, const SDLoc
&DL
,
2412 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2413 EVT PtrTy
= TLI
.getPointerTy(DAG
.getDataLayout());
2414 MachineFunction
&MF
= DAG
.getMachineFunction();
2415 Value
*Global
= TLI
.getSDagStackGuard(*MF
.getFunction().getParent());
2416 MachineSDNode
*Node
=
2417 DAG
.getMachineNode(TargetOpcode::LOAD_STACK_GUARD
, DL
, PtrTy
, Chain
);
2419 MachinePointerInfo
MPInfo(Global
);
2420 auto Flags
= MachineMemOperand::MOLoad
| MachineMemOperand::MOInvariant
|
2421 MachineMemOperand::MODereferenceable
;
2422 MachineMemOperand
*MemRef
= MF
.getMachineMemOperand(
2423 MPInfo
, Flags
, PtrTy
.getSizeInBits() / 8, DAG
.getEVTAlignment(PtrTy
));
2424 DAG
.setNodeMemRefs(Node
, {MemRef
});
2426 return SDValue(Node
, 0);
2429 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2430 /// tail spliced into a stack protector check success bb.
2432 /// For a high level explanation of how this fits into the stack protector
2433 /// generation see the comment on the declaration of class
2434 /// StackProtectorDescriptor.
2435 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor
&SPD
,
2436 MachineBasicBlock
*ParentBB
) {
2438 // First create the loads to the guard/stack slot for the comparison.
2439 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2440 EVT PtrTy
= TLI
.getPointerTy(DAG
.getDataLayout());
2442 MachineFrameInfo
&MFI
= ParentBB
->getParent()->getFrameInfo();
2443 int FI
= MFI
.getStackProtectorIndex();
2446 SDLoc dl
= getCurSDLoc();
2447 SDValue StackSlotPtr
= DAG
.getFrameIndex(FI
, PtrTy
);
2448 const Module
&M
= *ParentBB
->getParent()->getFunction().getParent();
2449 unsigned Align
= DL
->getPrefTypeAlignment(Type::getInt8PtrTy(M
.getContext()));
2451 // Generate code to load the content of the guard slot.
2452 SDValue GuardVal
= DAG
.getLoad(
2453 PtrTy
, dl
, DAG
.getEntryNode(), StackSlotPtr
,
2454 MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(), FI
), Align
,
2455 MachineMemOperand::MOVolatile
);
2457 if (TLI
.useStackGuardXorFP())
2458 GuardVal
= TLI
.emitStackGuardXorFP(DAG
, GuardVal
, dl
);
2460 // Retrieve guard check function, nullptr if instrumentation is inlined.
2461 if (const Function
*GuardCheckFn
= TLI
.getSSPStackGuardCheck(M
)) {
2462 // The target provides a guard check function to validate the guard value.
2463 // Generate a call to that function with the content of the guard slot as
2465 FunctionType
*FnTy
= GuardCheckFn
->getFunctionType();
2466 assert(FnTy
->getNumParams() == 1 && "Invalid function signature");
2468 TargetLowering::ArgListTy Args
;
2469 TargetLowering::ArgListEntry Entry
;
2470 Entry
.Node
= GuardVal
;
2471 Entry
.Ty
= FnTy
->getParamType(0);
2472 if (GuardCheckFn
->hasAttribute(1, Attribute::AttrKind::InReg
))
2473 Entry
.IsInReg
= true;
2474 Args
.push_back(Entry
);
2476 TargetLowering::CallLoweringInfo
CLI(DAG
);
2477 CLI
.setDebugLoc(getCurSDLoc())
2478 .setChain(DAG
.getEntryNode())
2479 .setCallee(GuardCheckFn
->getCallingConv(), FnTy
->getReturnType(),
2480 getValue(GuardCheckFn
), std::move(Args
));
2482 std::pair
<SDValue
, SDValue
> Result
= TLI
.LowerCallTo(CLI
);
2483 DAG
.setRoot(Result
.second
);
2487 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2488 // Otherwise, emit a volatile load to retrieve the stack guard value.
2489 SDValue Chain
= DAG
.getEntryNode();
2490 if (TLI
.useLoadStackGuardNode()) {
2491 Guard
= getLoadStackGuard(DAG
, dl
, Chain
);
2493 const Value
*IRGuard
= TLI
.getSDagStackGuard(M
);
2494 SDValue GuardPtr
= getValue(IRGuard
);
2497 DAG
.getLoad(PtrTy
, dl
, Chain
, GuardPtr
, MachinePointerInfo(IRGuard
, 0),
2498 Align
, MachineMemOperand::MOVolatile
);
2501 // Perform the comparison via a subtract/getsetcc.
2502 EVT VT
= Guard
.getValueType();
2503 SDValue Sub
= DAG
.getNode(ISD::SUB
, dl
, VT
, Guard
, GuardVal
);
2505 SDValue Cmp
= DAG
.getSetCC(dl
, TLI
.getSetCCResultType(DAG
.getDataLayout(),
2507 Sub
.getValueType()),
2508 Sub
, DAG
.getConstant(0, dl
, VT
), ISD::SETNE
);
2510 // If the sub is not 0, then we know the guard/stackslot do not equal, so
2511 // branch to failure MBB.
2512 SDValue BrCond
= DAG
.getNode(ISD::BRCOND
, dl
,
2513 MVT::Other
, GuardVal
.getOperand(0),
2514 Cmp
, DAG
.getBasicBlock(SPD
.getFailureMBB()));
2515 // Otherwise branch to success MBB.
2516 SDValue Br
= DAG
.getNode(ISD::BR
, dl
,
2518 DAG
.getBasicBlock(SPD
.getSuccessMBB()));
2523 /// Codegen the failure basic block for a stack protector check.
2525 /// A failure stack protector machine basic block consists simply of a call to
2526 /// __stack_chk_fail().
2528 /// For a high level explanation of how this fits into the stack protector
2529 /// generation see the comment on the declaration of class
2530 /// StackProtectorDescriptor.
2532 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor
&SPD
) {
2533 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2535 TLI
.makeLibCall(DAG
, RTLIB::STACKPROTECTOR_CHECK_FAIL
, MVT::isVoid
,
2536 None
, false, getCurSDLoc(), false, false).second
;
2540 /// visitBitTestHeader - This function emits necessary code to produce value
2541 /// suitable for "bit tests"
2542 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock
&B
,
2543 MachineBasicBlock
*SwitchBB
) {
2544 SDLoc dl
= getCurSDLoc();
2546 // Subtract the minimum value
2547 SDValue SwitchOp
= getValue(B
.SValue
);
2548 EVT VT
= SwitchOp
.getValueType();
2549 SDValue Sub
= DAG
.getNode(ISD::SUB
, dl
, VT
, SwitchOp
,
2550 DAG
.getConstant(B
.First
, dl
, VT
));
2553 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2554 SDValue RangeCmp
= DAG
.getSetCC(
2555 dl
, TLI
.getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(),
2556 Sub
.getValueType()),
2557 Sub
, DAG
.getConstant(B
.Range
, dl
, VT
), ISD::SETUGT
);
2559 // Determine the type of the test operands.
2560 bool UsePtrType
= false;
2561 if (!TLI
.isTypeLegal(VT
))
2564 for (unsigned i
= 0, e
= B
.Cases
.size(); i
!= e
; ++i
)
2565 if (!isUIntN(VT
.getSizeInBits(), B
.Cases
[i
].Mask
)) {
2566 // Switch table case range are encoded into series of masks.
2567 // Just use pointer type, it's guaranteed to fit.
2573 VT
= TLI
.getPointerTy(DAG
.getDataLayout());
2574 Sub
= DAG
.getZExtOrTrunc(Sub
, dl
, VT
);
2577 B
.RegVT
= VT
.getSimpleVT();
2578 B
.Reg
= FuncInfo
.CreateReg(B
.RegVT
);
2579 SDValue CopyTo
= DAG
.getCopyToReg(getControlRoot(), dl
, B
.Reg
, Sub
);
2581 MachineBasicBlock
* MBB
= B
.Cases
[0].ThisBB
;
2583 addSuccessorWithProb(SwitchBB
, B
.Default
, B
.DefaultProb
);
2584 addSuccessorWithProb(SwitchBB
, MBB
, B
.Prob
);
2585 SwitchBB
->normalizeSuccProbs();
2587 SDValue BrRange
= DAG
.getNode(ISD::BRCOND
, dl
,
2588 MVT::Other
, CopyTo
, RangeCmp
,
2589 DAG
.getBasicBlock(B
.Default
));
2591 // Avoid emitting unnecessary branches to the next block.
2592 if (MBB
!= NextBlock(SwitchBB
))
2593 BrRange
= DAG
.getNode(ISD::BR
, dl
, MVT::Other
, BrRange
,
2594 DAG
.getBasicBlock(MBB
));
2596 DAG
.setRoot(BrRange
);
2599 /// visitBitTestCase - this function produces one "bit test"
2600 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock
&BB
,
2601 MachineBasicBlock
* NextMBB
,
2602 BranchProbability BranchProbToNext
,
2605 MachineBasicBlock
*SwitchBB
) {
2606 SDLoc dl
= getCurSDLoc();
2608 SDValue ShiftOp
= DAG
.getCopyFromReg(getControlRoot(), dl
, Reg
, VT
);
2610 unsigned PopCount
= countPopulation(B
.Mask
);
2611 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2612 if (PopCount
== 1) {
2613 // Testing for a single bit; just compare the shift count with what it
2614 // would need to be to shift a 1 bit in that position.
2616 dl
, TLI
.getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
),
2617 ShiftOp
, DAG
.getConstant(countTrailingZeros(B
.Mask
), dl
, VT
),
2619 } else if (PopCount
== BB
.Range
) {
2620 // There is only one zero bit in the range, test for it directly.
2622 dl
, TLI
.getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
),
2623 ShiftOp
, DAG
.getConstant(countTrailingOnes(B
.Mask
), dl
, VT
),
2626 // Make desired shift
2627 SDValue SwitchVal
= DAG
.getNode(ISD::SHL
, dl
, VT
,
2628 DAG
.getConstant(1, dl
, VT
), ShiftOp
);
2630 // Emit bit tests and jumps
2631 SDValue AndOp
= DAG
.getNode(ISD::AND
, dl
,
2632 VT
, SwitchVal
, DAG
.getConstant(B
.Mask
, dl
, VT
));
2634 dl
, TLI
.getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
),
2635 AndOp
, DAG
.getConstant(0, dl
, VT
), ISD::SETNE
);
2638 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2639 addSuccessorWithProb(SwitchBB
, B
.TargetBB
, B
.ExtraProb
);
2640 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2641 addSuccessorWithProb(SwitchBB
, NextMBB
, BranchProbToNext
);
2642 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2643 // one as they are relative probabilities (and thus work more like weights),
2644 // and hence we need to normalize them to let the sum of them become one.
2645 SwitchBB
->normalizeSuccProbs();
2647 SDValue BrAnd
= DAG
.getNode(ISD::BRCOND
, dl
,
2648 MVT::Other
, getControlRoot(),
2649 Cmp
, DAG
.getBasicBlock(B
.TargetBB
));
2651 // Avoid emitting unnecessary branches to the next block.
2652 if (NextMBB
!= NextBlock(SwitchBB
))
2653 BrAnd
= DAG
.getNode(ISD::BR
, dl
, MVT::Other
, BrAnd
,
2654 DAG
.getBasicBlock(NextMBB
));
2659 void SelectionDAGBuilder::visitInvoke(const InvokeInst
&I
) {
2660 MachineBasicBlock
*InvokeMBB
= FuncInfo
.MBB
;
2662 // Retrieve successors. Look through artificial IR level blocks like
2663 // catchswitch for successors.
2664 MachineBasicBlock
*Return
= FuncInfo
.MBBMap
[I
.getSuccessor(0)];
2665 const BasicBlock
*EHPadBB
= I
.getSuccessor(1);
2667 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2668 // have to do anything here to lower funclet bundles.
2669 assert(!I
.hasOperandBundlesOtherThan(
2670 {LLVMContext::OB_deopt
, LLVMContext::OB_funclet
}) &&
2671 "Cannot lower invokes with arbitrary operand bundles yet!");
2673 const Value
*Callee(I
.getCalledValue());
2674 const Function
*Fn
= dyn_cast
<Function
>(Callee
);
2675 if (isa
<InlineAsm
>(Callee
))
2677 else if (Fn
&& Fn
->isIntrinsic()) {
2678 switch (Fn
->getIntrinsicID()) {
2680 llvm_unreachable("Cannot invoke this intrinsic");
2681 case Intrinsic::donothing
:
2682 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2684 case Intrinsic::experimental_patchpoint_void
:
2685 case Intrinsic::experimental_patchpoint_i64
:
2686 visitPatchpoint(&I
, EHPadBB
);
2688 case Intrinsic::experimental_gc_statepoint
:
2689 LowerStatepoint(ImmutableStatepoint(&I
), EHPadBB
);
2692 } else if (I
.countOperandBundlesOfType(LLVMContext::OB_deopt
)) {
2693 // Currently we do not lower any intrinsic calls with deopt operand bundles.
2694 // Eventually we will support lowering the @llvm.experimental.deoptimize
2695 // intrinsic, and right now there are no plans to support other intrinsics
2696 // with deopt state.
2697 LowerCallSiteWithDeoptBundle(&I
, getValue(Callee
), EHPadBB
);
2699 LowerCallTo(&I
, getValue(Callee
), false, EHPadBB
);
2702 // If the value of the invoke is used outside of its defining block, make it
2703 // available as a virtual register.
2704 // We already took care of the exported value for the statepoint instruction
2705 // during call to the LowerStatepoint.
2706 if (!isStatepoint(I
)) {
2707 CopyToExportRegsIfNeeded(&I
);
2710 SmallVector
<std::pair
<MachineBasicBlock
*, BranchProbability
>, 1> UnwindDests
;
2711 BranchProbabilityInfo
*BPI
= FuncInfo
.BPI
;
2712 BranchProbability EHPadBBProb
=
2713 BPI
? BPI
->getEdgeProbability(InvokeMBB
->getBasicBlock(), EHPadBB
)
2714 : BranchProbability::getZero();
2715 findUnwindDestinations(FuncInfo
, EHPadBB
, EHPadBBProb
, UnwindDests
);
2717 // Update successor info.
2718 addSuccessorWithProb(InvokeMBB
, Return
);
2719 for (auto &UnwindDest
: UnwindDests
) {
2720 UnwindDest
.first
->setIsEHPad();
2721 addSuccessorWithProb(InvokeMBB
, UnwindDest
.first
, UnwindDest
.second
);
2723 InvokeMBB
->normalizeSuccProbs();
2725 // Drop into normal successor.
2726 DAG
.setRoot(DAG
.getNode(ISD::BR
, getCurSDLoc(), MVT::Other
, getControlRoot(),
2727 DAG
.getBasicBlock(Return
)));
2730 void SelectionDAGBuilder::visitCallBr(const CallBrInst
&I
) {
2731 MachineBasicBlock
*CallBrMBB
= FuncInfo
.MBB
;
2733 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2734 // have to do anything here to lower funclet bundles.
2735 assert(!I
.hasOperandBundlesOtherThan(
2736 {LLVMContext::OB_deopt
, LLVMContext::OB_funclet
}) &&
2737 "Cannot lower callbrs with arbitrary operand bundles yet!");
2739 assert(isa
<InlineAsm
>(I
.getCalledValue()) &&
2740 "Only know how to handle inlineasm callbr");
2743 // Retrieve successors.
2744 MachineBasicBlock
*Return
= FuncInfo
.MBBMap
[I
.getDefaultDest()];
2746 // Update successor info.
2747 addSuccessorWithProb(CallBrMBB
, Return
);
2748 for (unsigned i
= 0, e
= I
.getNumIndirectDests(); i
< e
; ++i
) {
2749 MachineBasicBlock
*Target
= FuncInfo
.MBBMap
[I
.getIndirectDest(i
)];
2750 addSuccessorWithProb(CallBrMBB
, Target
);
2752 CallBrMBB
->normalizeSuccProbs();
2754 // Drop into default successor.
2755 DAG
.setRoot(DAG
.getNode(ISD::BR
, getCurSDLoc(),
2756 MVT::Other
, getControlRoot(),
2757 DAG
.getBasicBlock(Return
)));
2760 void SelectionDAGBuilder::visitResume(const ResumeInst
&RI
) {
2761 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2764 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst
&LP
) {
2765 assert(FuncInfo
.MBB
->isEHPad() &&
2766 "Call to landingpad not in landing pad!");
2768 // If there aren't registers to copy the values into (e.g., during SjLj
2769 // exceptions), then don't bother to create these DAG nodes.
2770 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2771 const Constant
*PersonalityFn
= FuncInfo
.Fn
->getPersonalityFn();
2772 if (TLI
.getExceptionPointerRegister(PersonalityFn
) == 0 &&
2773 TLI
.getExceptionSelectorRegister(PersonalityFn
) == 0)
2776 // If landingpad's return type is token type, we don't create DAG nodes
2777 // for its exception pointer and selector value. The extraction of exception
2778 // pointer or selector value from token type landingpads is not currently
2780 if (LP
.getType()->isTokenTy())
2783 SmallVector
<EVT
, 2> ValueVTs
;
2784 SDLoc dl
= getCurSDLoc();
2785 ComputeValueVTs(TLI
, DAG
.getDataLayout(), LP
.getType(), ValueVTs
);
2786 assert(ValueVTs
.size() == 2 && "Only two-valued landingpads are supported");
2788 // Get the two live-in registers as SDValues. The physregs have already been
2789 // copied into virtual registers.
2791 if (FuncInfo
.ExceptionPointerVirtReg
) {
2792 Ops
[0] = DAG
.getZExtOrTrunc(
2793 DAG
.getCopyFromReg(DAG
.getEntryNode(), dl
,
2794 FuncInfo
.ExceptionPointerVirtReg
,
2795 TLI
.getPointerTy(DAG
.getDataLayout())),
2798 Ops
[0] = DAG
.getConstant(0, dl
, TLI
.getPointerTy(DAG
.getDataLayout()));
2800 Ops
[1] = DAG
.getZExtOrTrunc(
2801 DAG
.getCopyFromReg(DAG
.getEntryNode(), dl
,
2802 FuncInfo
.ExceptionSelectorVirtReg
,
2803 TLI
.getPointerTy(DAG
.getDataLayout())),
2807 SDValue Res
= DAG
.getNode(ISD::MERGE_VALUES
, dl
,
2808 DAG
.getVTList(ValueVTs
), Ops
);
2812 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector
&Clusters
) {
2814 for (const CaseCluster
&CC
: Clusters
)
2815 assert(CC
.Low
== CC
.High
&& "Input clusters must be single-case");
2818 llvm::sort(Clusters
, [](const CaseCluster
&a
, const CaseCluster
&b
) {
2819 return a
.Low
->getValue().slt(b
.Low
->getValue());
2822 // Merge adjacent clusters with the same destination.
2823 const unsigned N
= Clusters
.size();
2824 unsigned DstIndex
= 0;
2825 for (unsigned SrcIndex
= 0; SrcIndex
< N
; ++SrcIndex
) {
2826 CaseCluster
&CC
= Clusters
[SrcIndex
];
2827 const ConstantInt
*CaseVal
= CC
.Low
;
2828 MachineBasicBlock
*Succ
= CC
.MBB
;
2830 if (DstIndex
!= 0 && Clusters
[DstIndex
- 1].MBB
== Succ
&&
2831 (CaseVal
->getValue() - Clusters
[DstIndex
- 1].High
->getValue()) == 1) {
2832 // If this case has the same successor and is a neighbour, merge it into
2833 // the previous cluster.
2834 Clusters
[DstIndex
- 1].High
= CaseVal
;
2835 Clusters
[DstIndex
- 1].Prob
+= CC
.Prob
;
2837 std::memmove(&Clusters
[DstIndex
++], &Clusters
[SrcIndex
],
2838 sizeof(Clusters
[SrcIndex
]));
2841 Clusters
.resize(DstIndex
);
2844 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock
*First
,
2845 MachineBasicBlock
*Last
) {
2847 for (unsigned i
= 0, e
= JTCases
.size(); i
!= e
; ++i
)
2848 if (JTCases
[i
].first
.HeaderBB
== First
)
2849 JTCases
[i
].first
.HeaderBB
= Last
;
2851 // Update BitTestCases.
2852 for (unsigned i
= 0, e
= BitTestCases
.size(); i
!= e
; ++i
)
2853 if (BitTestCases
[i
].Parent
== First
)
2854 BitTestCases
[i
].Parent
= Last
;
2857 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst
&I
) {
2858 MachineBasicBlock
*IndirectBrMBB
= FuncInfo
.MBB
;
2860 // Update machine-CFG edges with unique successors.
2861 SmallSet
<BasicBlock
*, 32> Done
;
2862 for (unsigned i
= 0, e
= I
.getNumSuccessors(); i
!= e
; ++i
) {
2863 BasicBlock
*BB
= I
.getSuccessor(i
);
2864 bool Inserted
= Done
.insert(BB
).second
;
2868 MachineBasicBlock
*Succ
= FuncInfo
.MBBMap
[BB
];
2869 addSuccessorWithProb(IndirectBrMBB
, Succ
);
2871 IndirectBrMBB
->normalizeSuccProbs();
2873 DAG
.setRoot(DAG
.getNode(ISD::BRIND
, getCurSDLoc(),
2874 MVT::Other
, getControlRoot(),
2875 getValue(I
.getAddress())));
2878 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst
&I
) {
2879 if (!DAG
.getTarget().Options
.TrapUnreachable
)
2882 // We may be able to ignore unreachable behind a noreturn call.
2883 if (DAG
.getTarget().Options
.NoTrapAfterNoreturn
) {
2884 const BasicBlock
&BB
= *I
.getParent();
2885 if (&I
!= &BB
.front()) {
2886 BasicBlock::const_iterator PredI
=
2887 std::prev(BasicBlock::const_iterator(&I
));
2888 if (const CallInst
*Call
= dyn_cast
<CallInst
>(&*PredI
)) {
2889 if (Call
->doesNotReturn())
2895 DAG
.setRoot(DAG
.getNode(ISD::TRAP
, getCurSDLoc(), MVT::Other
, DAG
.getRoot()));
2898 void SelectionDAGBuilder::visitFSub(const User
&I
) {
2899 // -0.0 - X --> fneg
2900 Type
*Ty
= I
.getType();
2901 if (isa
<Constant
>(I
.getOperand(0)) &&
2902 I
.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty
)) {
2903 SDValue Op2
= getValue(I
.getOperand(1));
2904 setValue(&I
, DAG
.getNode(ISD::FNEG
, getCurSDLoc(),
2905 Op2
.getValueType(), Op2
));
2909 visitBinary(I
, ISD::FSUB
);
2912 /// Checks if the given instruction performs a vector reduction, in which case
2913 /// we have the freedom to alter the elements in the result as long as the
2914 /// reduction of them stays unchanged.
2915 static bool isVectorReductionOp(const User
*I
) {
2916 const Instruction
*Inst
= dyn_cast
<Instruction
>(I
);
2917 if (!Inst
|| !Inst
->getType()->isVectorTy())
2920 auto OpCode
= Inst
->getOpcode();
2922 case Instruction::Add
:
2923 case Instruction::Mul
:
2924 case Instruction::And
:
2925 case Instruction::Or
:
2926 case Instruction::Xor
:
2928 case Instruction::FAdd
:
2929 case Instruction::FMul
:
2930 if (const FPMathOperator
*FPOp
= dyn_cast
<const FPMathOperator
>(Inst
))
2931 if (FPOp
->getFastMathFlags().isFast())
2938 unsigned ElemNum
= Inst
->getType()->getVectorNumElements();
2939 // Ensure the reduction size is a power of 2.
2940 if (!isPowerOf2_32(ElemNum
))
2943 unsigned ElemNumToReduce
= ElemNum
;
2945 // Do DFS search on the def-use chain from the given instruction. We only
2946 // allow four kinds of operations during the search until we reach the
2947 // instruction that extracts the first element from the vector:
2949 // 1. The reduction operation of the same opcode as the given instruction.
2953 // 3. ShuffleVector instruction together with a reduction operation that
2954 // does a partial reduction.
2956 // 4. ExtractElement that extracts the first element from the vector, and we
2957 // stop searching the def-use chain here.
2959 // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2960 // from 1-3 to the stack to continue the DFS. The given instruction is not
2961 // a reduction operation if we meet any other instructions other than those
2964 SmallVector
<const User
*, 16> UsersToVisit
{Inst
};
2965 SmallPtrSet
<const User
*, 16> Visited
;
2966 bool ReduxExtracted
= false;
2968 while (!UsersToVisit
.empty()) {
2969 auto User
= UsersToVisit
.back();
2970 UsersToVisit
.pop_back();
2971 if (!Visited
.insert(User
).second
)
2974 for (const auto &U
: User
->users()) {
2975 auto Inst
= dyn_cast
<Instruction
>(U
);
2979 if (Inst
->getOpcode() == OpCode
|| isa
<PHINode
>(U
)) {
2980 if (const FPMathOperator
*FPOp
= dyn_cast
<const FPMathOperator
>(Inst
))
2981 if (!isa
<PHINode
>(FPOp
) && !FPOp
->getFastMathFlags().isFast())
2983 UsersToVisit
.push_back(U
);
2984 } else if (const ShuffleVectorInst
*ShufInst
=
2985 dyn_cast
<ShuffleVectorInst
>(U
)) {
2986 // Detect the following pattern: A ShuffleVector instruction together
2987 // with a reduction that do partial reduction on the first and second
2988 // ElemNumToReduce / 2 elements, and store the result in
2989 // ElemNumToReduce / 2 elements in another vector.
2991 unsigned ResultElements
= ShufInst
->getType()->getVectorNumElements();
2992 if (ResultElements
< ElemNum
)
2995 if (ElemNumToReduce
== 1)
2997 if (!isa
<UndefValue
>(U
->getOperand(1)))
2999 for (unsigned i
= 0; i
< ElemNumToReduce
/ 2; ++i
)
3000 if (ShufInst
->getMaskValue(i
) != int(i
+ ElemNumToReduce
/ 2))
3002 for (unsigned i
= ElemNumToReduce
/ 2; i
< ElemNum
; ++i
)
3003 if (ShufInst
->getMaskValue(i
) != -1)
3006 // There is only one user of this ShuffleVector instruction, which
3007 // must be a reduction operation.
3008 if (!U
->hasOneUse())
3011 auto U2
= dyn_cast
<Instruction
>(*U
->user_begin());
3012 if (!U2
|| U2
->getOpcode() != OpCode
)
3015 // Check operands of the reduction operation.
3016 if ((U2
->getOperand(0) == U
->getOperand(0) && U2
->getOperand(1) == U
) ||
3017 (U2
->getOperand(1) == U
->getOperand(0) && U2
->getOperand(0) == U
)) {
3018 UsersToVisit
.push_back(U2
);
3019 ElemNumToReduce
/= 2;
3022 } else if (isa
<ExtractElementInst
>(U
)) {
3023 // At this moment we should have reduced all elements in the vector.
3024 if (ElemNumToReduce
!= 1)
3027 const ConstantInt
*Val
= dyn_cast
<ConstantInt
>(U
->getOperand(1));
3028 if (!Val
|| !Val
->isZero())
3031 ReduxExtracted
= true;
3036 return ReduxExtracted
;
3039 void SelectionDAGBuilder::visitUnary(const User
&I
, unsigned Opcode
) {
3042 SDValue Op
= getValue(I
.getOperand(0));
3043 SDValue UnNodeValue
= DAG
.getNode(Opcode
, getCurSDLoc(), Op
.getValueType(),
3045 setValue(&I
, UnNodeValue
);
3048 void SelectionDAGBuilder::visitBinary(const User
&I
, unsigned Opcode
) {
3050 if (auto *OFBinOp
= dyn_cast
<OverflowingBinaryOperator
>(&I
)) {
3051 Flags
.setNoSignedWrap(OFBinOp
->hasNoSignedWrap());
3052 Flags
.setNoUnsignedWrap(OFBinOp
->hasNoUnsignedWrap());
3054 if (auto *ExactOp
= dyn_cast
<PossiblyExactOperator
>(&I
)) {
3055 Flags
.setExact(ExactOp
->isExact());
3057 if (isVectorReductionOp(&I
)) {
3058 Flags
.setVectorReduction(true);
3059 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I
<< "\n");
3062 SDValue Op1
= getValue(I
.getOperand(0));
3063 SDValue Op2
= getValue(I
.getOperand(1));
3064 SDValue BinNodeValue
= DAG
.getNode(Opcode
, getCurSDLoc(), Op1
.getValueType(),
3066 setValue(&I
, BinNodeValue
);
3069 void SelectionDAGBuilder::visitShift(const User
&I
, unsigned Opcode
) {
3070 SDValue Op1
= getValue(I
.getOperand(0));
3071 SDValue Op2
= getValue(I
.getOperand(1));
3073 EVT ShiftTy
= DAG
.getTargetLoweringInfo().getShiftAmountTy(
3074 Op1
.getValueType(), DAG
.getDataLayout());
3076 // Coerce the shift amount to the right type if we can.
3077 if (!I
.getType()->isVectorTy() && Op2
.getValueType() != ShiftTy
) {
3078 unsigned ShiftSize
= ShiftTy
.getSizeInBits();
3079 unsigned Op2Size
= Op2
.getValueSizeInBits();
3080 SDLoc DL
= getCurSDLoc();
3082 // If the operand is smaller than the shift count type, promote it.
3083 if (ShiftSize
> Op2Size
)
3084 Op2
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, ShiftTy
, Op2
);
3086 // If the operand is larger than the shift count type but the shift
3087 // count type has enough bits to represent any shift value, truncate
3088 // it now. This is a common case and it exposes the truncate to
3089 // optimization early.
3090 else if (ShiftSize
>= Log2_32_Ceil(Op2
.getValueSizeInBits()))
3091 Op2
= DAG
.getNode(ISD::TRUNCATE
, DL
, ShiftTy
, Op2
);
3092 // Otherwise we'll need to temporarily settle for some other convenient
3093 // type. Type legalization will make adjustments once the shiftee is split.
3095 Op2
= DAG
.getZExtOrTrunc(Op2
, DL
, MVT::i32
);
3102 if (Opcode
== ISD::SRL
|| Opcode
== ISD::SRA
|| Opcode
== ISD::SHL
) {
3104 if (const OverflowingBinaryOperator
*OFBinOp
=
3105 dyn_cast
<const OverflowingBinaryOperator
>(&I
)) {
3106 nuw
= OFBinOp
->hasNoUnsignedWrap();
3107 nsw
= OFBinOp
->hasNoSignedWrap();
3109 if (const PossiblyExactOperator
*ExactOp
=
3110 dyn_cast
<const PossiblyExactOperator
>(&I
))
3111 exact
= ExactOp
->isExact();
3114 Flags
.setExact(exact
);
3115 Flags
.setNoSignedWrap(nsw
);
3116 Flags
.setNoUnsignedWrap(nuw
);
3117 SDValue Res
= DAG
.getNode(Opcode
, getCurSDLoc(), Op1
.getValueType(), Op1
, Op2
,
3122 void SelectionDAGBuilder::visitSDiv(const User
&I
) {
3123 SDValue Op1
= getValue(I
.getOperand(0));
3124 SDValue Op2
= getValue(I
.getOperand(1));
3127 Flags
.setExact(isa
<PossiblyExactOperator
>(&I
) &&
3128 cast
<PossiblyExactOperator
>(&I
)->isExact());
3129 setValue(&I
, DAG
.getNode(ISD::SDIV
, getCurSDLoc(), Op1
.getValueType(), Op1
,
3133 void SelectionDAGBuilder::visitICmp(const User
&I
) {
3134 ICmpInst::Predicate predicate
= ICmpInst::BAD_ICMP_PREDICATE
;
3135 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(&I
))
3136 predicate
= IC
->getPredicate();
3137 else if (const ConstantExpr
*IC
= dyn_cast
<ConstantExpr
>(&I
))
3138 predicate
= ICmpInst::Predicate(IC
->getPredicate());
3139 SDValue Op1
= getValue(I
.getOperand(0));
3140 SDValue Op2
= getValue(I
.getOperand(1));
3141 ISD::CondCode Opcode
= getICmpCondCode(predicate
);
3143 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3145 setValue(&I
, DAG
.getSetCC(getCurSDLoc(), DestVT
, Op1
, Op2
, Opcode
));
3148 void SelectionDAGBuilder::visitFCmp(const User
&I
) {
3149 FCmpInst::Predicate predicate
= FCmpInst::BAD_FCMP_PREDICATE
;
3150 if (const FCmpInst
*FC
= dyn_cast
<FCmpInst
>(&I
))
3151 predicate
= FC
->getPredicate();
3152 else if (const ConstantExpr
*FC
= dyn_cast
<ConstantExpr
>(&I
))
3153 predicate
= FCmpInst::Predicate(FC
->getPredicate());
3154 SDValue Op1
= getValue(I
.getOperand(0));
3155 SDValue Op2
= getValue(I
.getOperand(1));
3157 ISD::CondCode Condition
= getFCmpCondCode(predicate
);
3158 auto *FPMO
= dyn_cast
<FPMathOperator
>(&I
);
3159 if ((FPMO
&& FPMO
->hasNoNaNs()) || TM
.Options
.NoNaNsFPMath
)
3160 Condition
= getFCmpCodeWithoutNaN(Condition
);
3162 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3164 setValue(&I
, DAG
.getSetCC(getCurSDLoc(), DestVT
, Op1
, Op2
, Condition
));
3167 // Check if the condition of the select has one use or two users that are both
3168 // selects with the same condition.
3169 static bool hasOnlySelectUsers(const Value
*Cond
) {
3170 return llvm::all_of(Cond
->users(), [](const Value
*V
) {
3171 return isa
<SelectInst
>(V
);
3175 void SelectionDAGBuilder::visitSelect(const User
&I
) {
3176 SmallVector
<EVT
, 4> ValueVTs
;
3177 ComputeValueVTs(DAG
.getTargetLoweringInfo(), DAG
.getDataLayout(), I
.getType(),
3179 unsigned NumValues
= ValueVTs
.size();
3180 if (NumValues
== 0) return;
3182 SmallVector
<SDValue
, 4> Values(NumValues
);
3183 SDValue Cond
= getValue(I
.getOperand(0));
3184 SDValue LHSVal
= getValue(I
.getOperand(1));
3185 SDValue RHSVal
= getValue(I
.getOperand(2));
3186 auto BaseOps
= {Cond
};
3187 ISD::NodeType OpCode
= Cond
.getValueType().isVector() ?
3188 ISD::VSELECT
: ISD::SELECT
;
3190 // Min/max matching is only viable if all output VTs are the same.
3191 if (is_splat(ValueVTs
)) {
3192 EVT VT
= ValueVTs
[0];
3193 LLVMContext
&Ctx
= *DAG
.getContext();
3194 auto &TLI
= DAG
.getTargetLoweringInfo();
3196 // We care about the legality of the operation after it has been type
3198 while (TLI
.getTypeAction(Ctx
, VT
) != TargetLoweringBase::TypeLegal
&&
3199 VT
!= TLI
.getTypeToTransformTo(Ctx
, VT
))
3200 VT
= TLI
.getTypeToTransformTo(Ctx
, VT
);
3202 // If the vselect is legal, assume we want to leave this as a vector setcc +
3203 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3204 // min/max is legal on the scalar type.
3205 bool UseScalarMinMax
= VT
.isVector() &&
3206 !TLI
.isOperationLegalOrCustom(ISD::VSELECT
, VT
);
3209 auto SPR
= matchSelectPattern(const_cast<User
*>(&I
), LHS
, RHS
);
3210 ISD::NodeType Opc
= ISD::DELETED_NODE
;
3211 switch (SPR
.Flavor
) {
3212 case SPF_UMAX
: Opc
= ISD::UMAX
; break;
3213 case SPF_UMIN
: Opc
= ISD::UMIN
; break;
3214 case SPF_SMAX
: Opc
= ISD::SMAX
; break;
3215 case SPF_SMIN
: Opc
= ISD::SMIN
; break;
3217 switch (SPR
.NaNBehavior
) {
3218 case SPNB_NA
: llvm_unreachable("No NaN behavior for FP op?");
3219 case SPNB_RETURNS_NAN
: Opc
= ISD::FMINIMUM
; break;
3220 case SPNB_RETURNS_OTHER
: Opc
= ISD::FMINNUM
; break;
3221 case SPNB_RETURNS_ANY
: {
3222 if (TLI
.isOperationLegalOrCustom(ISD::FMINNUM
, VT
))
3224 else if (TLI
.isOperationLegalOrCustom(ISD::FMINIMUM
, VT
))
3225 Opc
= ISD::FMINIMUM
;
3226 else if (UseScalarMinMax
)
3227 Opc
= TLI
.isOperationLegalOrCustom(ISD::FMINNUM
, VT
.getScalarType()) ?
3228 ISD::FMINNUM
: ISD::FMINIMUM
;
3234 switch (SPR
.NaNBehavior
) {
3235 case SPNB_NA
: llvm_unreachable("No NaN behavior for FP op?");
3236 case SPNB_RETURNS_NAN
: Opc
= ISD::FMAXIMUM
; break;
3237 case SPNB_RETURNS_OTHER
: Opc
= ISD::FMAXNUM
; break;
3238 case SPNB_RETURNS_ANY
:
3240 if (TLI
.isOperationLegalOrCustom(ISD::FMAXNUM
, VT
))
3242 else if (TLI
.isOperationLegalOrCustom(ISD::FMAXIMUM
, VT
))
3243 Opc
= ISD::FMAXIMUM
;
3244 else if (UseScalarMinMax
)
3245 Opc
= TLI
.isOperationLegalOrCustom(ISD::FMAXNUM
, VT
.getScalarType()) ?
3246 ISD::FMAXNUM
: ISD::FMAXIMUM
;
3253 if (Opc
!= ISD::DELETED_NODE
&&
3254 (TLI
.isOperationLegalOrCustom(Opc
, VT
) ||
3256 TLI
.isOperationLegalOrCustom(Opc
, VT
.getScalarType()))) &&
3257 // If the underlying comparison instruction is used by any other
3258 // instruction, the consumed instructions won't be destroyed, so it is
3259 // not profitable to convert to a min/max.
3260 hasOnlySelectUsers(cast
<SelectInst
>(I
).getCondition())) {
3262 LHSVal
= getValue(LHS
);
3263 RHSVal
= getValue(RHS
);
3268 for (unsigned i
= 0; i
!= NumValues
; ++i
) {
3269 SmallVector
<SDValue
, 3> Ops(BaseOps
.begin(), BaseOps
.end());
3270 Ops
.push_back(SDValue(LHSVal
.getNode(), LHSVal
.getResNo() + i
));
3271 Ops
.push_back(SDValue(RHSVal
.getNode(), RHSVal
.getResNo() + i
));
3272 Values
[i
] = DAG
.getNode(OpCode
, getCurSDLoc(),
3273 LHSVal
.getNode()->getValueType(LHSVal
.getResNo()+i
),
3277 setValue(&I
, DAG
.getNode(ISD::MERGE_VALUES
, getCurSDLoc(),
3278 DAG
.getVTList(ValueVTs
), Values
));
3281 void SelectionDAGBuilder::visitTrunc(const User
&I
) {
3282 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3283 SDValue N
= getValue(I
.getOperand(0));
3284 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3286 setValue(&I
, DAG
.getNode(ISD::TRUNCATE
, getCurSDLoc(), DestVT
, N
));
3289 void SelectionDAGBuilder::visitZExt(const User
&I
) {
3290 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3291 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3292 SDValue N
= getValue(I
.getOperand(0));
3293 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3295 setValue(&I
, DAG
.getNode(ISD::ZERO_EXTEND
, getCurSDLoc(), DestVT
, N
));
3298 void SelectionDAGBuilder::visitSExt(const User
&I
) {
3299 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3300 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3301 SDValue N
= getValue(I
.getOperand(0));
3302 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3304 setValue(&I
, DAG
.getNode(ISD::SIGN_EXTEND
, getCurSDLoc(), DestVT
, N
));
3307 void SelectionDAGBuilder::visitFPTrunc(const User
&I
) {
3308 // FPTrunc is never a no-op cast, no need to check
3309 SDValue N
= getValue(I
.getOperand(0));
3310 SDLoc dl
= getCurSDLoc();
3311 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3312 EVT DestVT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
3313 setValue(&I
, DAG
.getNode(ISD::FP_ROUND
, dl
, DestVT
, N
,
3314 DAG
.getTargetConstant(
3315 0, dl
, TLI
.getPointerTy(DAG
.getDataLayout()))));
3318 void SelectionDAGBuilder::visitFPExt(const User
&I
) {
3319 // FPExt is never a no-op cast, no need to check
3320 SDValue N
= getValue(I
.getOperand(0));
3321 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3323 setValue(&I
, DAG
.getNode(ISD::FP_EXTEND
, getCurSDLoc(), DestVT
, N
));
3326 void SelectionDAGBuilder::visitFPToUI(const User
&I
) {
3327 // FPToUI is never a no-op cast, no need to check
3328 SDValue N
= getValue(I
.getOperand(0));
3329 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3331 setValue(&I
, DAG
.getNode(ISD::FP_TO_UINT
, getCurSDLoc(), DestVT
, N
));
3334 void SelectionDAGBuilder::visitFPToSI(const User
&I
) {
3335 // FPToSI is never a no-op cast, no need to check
3336 SDValue N
= getValue(I
.getOperand(0));
3337 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3339 setValue(&I
, DAG
.getNode(ISD::FP_TO_SINT
, getCurSDLoc(), DestVT
, N
));
3342 void SelectionDAGBuilder::visitUIToFP(const User
&I
) {
3343 // UIToFP is never a no-op cast, no need to check
3344 SDValue N
= getValue(I
.getOperand(0));
3345 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3347 setValue(&I
, DAG
.getNode(ISD::UINT_TO_FP
, getCurSDLoc(), DestVT
, N
));
3350 void SelectionDAGBuilder::visitSIToFP(const User
&I
) {
3351 // SIToFP is never a no-op cast, no need to check
3352 SDValue N
= getValue(I
.getOperand(0));
3353 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3355 setValue(&I
, DAG
.getNode(ISD::SINT_TO_FP
, getCurSDLoc(), DestVT
, N
));
3358 void SelectionDAGBuilder::visitPtrToInt(const User
&I
) {
3359 // What to do depends on the size of the integer and the size of the pointer.
3360 // We can either truncate, zero extend, or no-op, accordingly.
3361 SDValue N
= getValue(I
.getOperand(0));
3362 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3364 setValue(&I
, DAG
.getZExtOrTrunc(N
, getCurSDLoc(), DestVT
));
3367 void SelectionDAGBuilder::visitIntToPtr(const User
&I
) {
3368 // What to do depends on the size of the integer and the size of the pointer.
3369 // We can either truncate, zero extend, or no-op, accordingly.
3370 SDValue N
= getValue(I
.getOperand(0));
3371 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3373 setValue(&I
, DAG
.getZExtOrTrunc(N
, getCurSDLoc(), DestVT
));
3376 void SelectionDAGBuilder::visitBitCast(const User
&I
) {
3377 SDValue N
= getValue(I
.getOperand(0));
3378 SDLoc dl
= getCurSDLoc();
3379 EVT DestVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
3382 // BitCast assures us that source and destination are the same size so this is
3383 // either a BITCAST or a no-op.
3384 if (DestVT
!= N
.getValueType())
3385 setValue(&I
, DAG
.getNode(ISD::BITCAST
, dl
,
3386 DestVT
, N
)); // convert types.
3387 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3388 // might fold any kind of constant expression to an integer constant and that
3389 // is not what we are looking for. Only recognize a bitcast of a genuine
3390 // constant integer as an opaque constant.
3391 else if(ConstantInt
*C
= dyn_cast
<ConstantInt
>(I
.getOperand(0)))
3392 setValue(&I
, DAG
.getConstant(C
->getValue(), dl
, DestVT
, /*isTarget=*/false,
3395 setValue(&I
, N
); // noop cast.
3398 void SelectionDAGBuilder::visitAddrSpaceCast(const User
&I
) {
3399 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3400 const Value
*SV
= I
.getOperand(0);
3401 SDValue N
= getValue(SV
);
3402 EVT DestVT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
3404 unsigned SrcAS
= SV
->getType()->getPointerAddressSpace();
3405 unsigned DestAS
= I
.getType()->getPointerAddressSpace();
3407 if (!TLI
.isNoopAddrSpaceCast(SrcAS
, DestAS
))
3408 N
= DAG
.getAddrSpaceCast(getCurSDLoc(), DestVT
, N
, SrcAS
, DestAS
);
3413 void SelectionDAGBuilder::visitInsertElement(const User
&I
) {
3414 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3415 SDValue InVec
= getValue(I
.getOperand(0));
3416 SDValue InVal
= getValue(I
.getOperand(1));
3417 SDValue InIdx
= DAG
.getSExtOrTrunc(getValue(I
.getOperand(2)), getCurSDLoc(),
3418 TLI
.getVectorIdxTy(DAG
.getDataLayout()));
3419 setValue(&I
, DAG
.getNode(ISD::INSERT_VECTOR_ELT
, getCurSDLoc(),
3420 TLI
.getValueType(DAG
.getDataLayout(), I
.getType()),
3421 InVec
, InVal
, InIdx
));
3424 void SelectionDAGBuilder::visitExtractElement(const User
&I
) {
3425 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3426 SDValue InVec
= getValue(I
.getOperand(0));
3427 SDValue InIdx
= DAG
.getSExtOrTrunc(getValue(I
.getOperand(1)), getCurSDLoc(),
3428 TLI
.getVectorIdxTy(DAG
.getDataLayout()));
3429 setValue(&I
, DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, getCurSDLoc(),
3430 TLI
.getValueType(DAG
.getDataLayout(), I
.getType()),
3434 void SelectionDAGBuilder::visitShuffleVector(const User
&I
) {
3435 SDValue Src1
= getValue(I
.getOperand(0));
3436 SDValue Src2
= getValue(I
.getOperand(1));
3437 SDLoc DL
= getCurSDLoc();
3439 SmallVector
<int, 8> Mask
;
3440 ShuffleVectorInst::getShuffleMask(cast
<Constant
>(I
.getOperand(2)), Mask
);
3441 unsigned MaskNumElts
= Mask
.size();
3443 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3444 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
3445 EVT SrcVT
= Src1
.getValueType();
3446 unsigned SrcNumElts
= SrcVT
.getVectorNumElements();
3448 if (SrcNumElts
== MaskNumElts
) {
3449 setValue(&I
, DAG
.getVectorShuffle(VT
, DL
, Src1
, Src2
, Mask
));
3453 // Normalize the shuffle vector since mask and vector length don't match.
3454 if (SrcNumElts
< MaskNumElts
) {
3455 // Mask is longer than the source vectors. We can use concatenate vector to
3456 // make the mask and vectors lengths match.
3458 if (MaskNumElts
% SrcNumElts
== 0) {
3459 // Mask length is a multiple of the source vector length.
3460 // Check if the shuffle is some kind of concatenation of the input
3462 unsigned NumConcat
= MaskNumElts
/ SrcNumElts
;
3463 bool IsConcat
= true;
3464 SmallVector
<int, 8> ConcatSrcs(NumConcat
, -1);
3465 for (unsigned i
= 0; i
!= MaskNumElts
; ++i
) {
3469 // Ensure the indices in each SrcVT sized piece are sequential and that
3470 // the same source is used for the whole piece.
3471 if ((Idx
% SrcNumElts
!= (i
% SrcNumElts
)) ||
3472 (ConcatSrcs
[i
/ SrcNumElts
] >= 0 &&
3473 ConcatSrcs
[i
/ SrcNumElts
] != (int)(Idx
/ SrcNumElts
))) {
3477 // Remember which source this index came from.
3478 ConcatSrcs
[i
/ SrcNumElts
] = Idx
/ SrcNumElts
;
3481 // The shuffle is concatenating multiple vectors together. Just emit
3482 // a CONCAT_VECTORS operation.
3484 SmallVector
<SDValue
, 8> ConcatOps
;
3485 for (auto Src
: ConcatSrcs
) {
3487 ConcatOps
.push_back(DAG
.getUNDEF(SrcVT
));
3489 ConcatOps
.push_back(Src1
);
3491 ConcatOps
.push_back(Src2
);
3493 setValue(&I
, DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, ConcatOps
));
3498 unsigned PaddedMaskNumElts
= alignTo(MaskNumElts
, SrcNumElts
);
3499 unsigned NumConcat
= PaddedMaskNumElts
/ SrcNumElts
;
3500 EVT PaddedVT
= EVT::getVectorVT(*DAG
.getContext(), VT
.getScalarType(),
3503 // Pad both vectors with undefs to make them the same length as the mask.
3504 SDValue UndefVal
= DAG
.getUNDEF(SrcVT
);
3506 SmallVector
<SDValue
, 8> MOps1(NumConcat
, UndefVal
);
3507 SmallVector
<SDValue
, 8> MOps2(NumConcat
, UndefVal
);
3511 Src1
= Src1
.isUndef()
3512 ? DAG
.getUNDEF(PaddedVT
)
3513 : DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, PaddedVT
, MOps1
);
3514 Src2
= Src2
.isUndef()
3515 ? DAG
.getUNDEF(PaddedVT
)
3516 : DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, PaddedVT
, MOps2
);
3518 // Readjust mask for new input vector length.
3519 SmallVector
<int, 8> MappedOps(PaddedMaskNumElts
, -1);
3520 for (unsigned i
= 0; i
!= MaskNumElts
; ++i
) {
3522 if (Idx
>= (int)SrcNumElts
)
3523 Idx
-= SrcNumElts
- PaddedMaskNumElts
;
3527 SDValue Result
= DAG
.getVectorShuffle(PaddedVT
, DL
, Src1
, Src2
, MappedOps
);
3529 // If the concatenated vector was padded, extract a subvector with the
3530 // correct number of elements.
3531 if (MaskNumElts
!= PaddedMaskNumElts
)
3532 Result
= DAG
.getNode(
3533 ISD::EXTRACT_SUBVECTOR
, DL
, VT
, Result
,
3534 DAG
.getConstant(0, DL
, TLI
.getVectorIdxTy(DAG
.getDataLayout())));
3536 setValue(&I
, Result
);
3540 if (SrcNumElts
> MaskNumElts
) {
3541 // Analyze the access pattern of the vector to see if we can extract
3542 // two subvectors and do the shuffle.
3543 int StartIdx
[2] = { -1, -1 }; // StartIdx to extract from
3544 bool CanExtract
= true;
3545 for (int Idx
: Mask
) {
3550 if (Idx
>= (int)SrcNumElts
) {
3555 // If all the indices come from the same MaskNumElts sized portion of
3556 // the sources we can use extract. Also make sure the extract wouldn't
3557 // extract past the end of the source.
3558 int NewStartIdx
= alignDown(Idx
, MaskNumElts
);
3559 if (NewStartIdx
+ MaskNumElts
> SrcNumElts
||
3560 (StartIdx
[Input
] >= 0 && StartIdx
[Input
] != NewStartIdx
))
3562 // Make sure we always update StartIdx as we use it to track if all
3563 // elements are undef.
3564 StartIdx
[Input
] = NewStartIdx
;
3567 if (StartIdx
[0] < 0 && StartIdx
[1] < 0) {
3568 setValue(&I
, DAG
.getUNDEF(VT
)); // Vectors are not used.
3572 // Extract appropriate subvector and generate a vector shuffle
3573 for (unsigned Input
= 0; Input
< 2; ++Input
) {
3574 SDValue
&Src
= Input
== 0 ? Src1
: Src2
;
3575 if (StartIdx
[Input
] < 0)
3576 Src
= DAG
.getUNDEF(VT
);
3579 ISD::EXTRACT_SUBVECTOR
, DL
, VT
, Src
,
3580 DAG
.getConstant(StartIdx
[Input
], DL
,
3581 TLI
.getVectorIdxTy(DAG
.getDataLayout())));
3585 // Calculate new mask.
3586 SmallVector
<int, 8> MappedOps(Mask
.begin(), Mask
.end());
3587 for (int &Idx
: MappedOps
) {
3588 if (Idx
>= (int)SrcNumElts
)
3589 Idx
-= SrcNumElts
+ StartIdx
[1] - MaskNumElts
;
3594 setValue(&I
, DAG
.getVectorShuffle(VT
, DL
, Src1
, Src2
, MappedOps
));
3599 // We can't use either concat vectors or extract subvectors so fall back to
3600 // replacing the shuffle with extract and build vector.
3601 // to insert and build vector.
3602 EVT EltVT
= VT
.getVectorElementType();
3603 EVT IdxVT
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
3604 SmallVector
<SDValue
,8> Ops
;
3605 for (int Idx
: Mask
) {
3609 Res
= DAG
.getUNDEF(EltVT
);
3611 SDValue
&Src
= Idx
< (int)SrcNumElts
? Src1
: Src2
;
3612 if (Idx
>= (int)SrcNumElts
) Idx
-= SrcNumElts
;
3614 Res
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
,
3615 EltVT
, Src
, DAG
.getConstant(Idx
, DL
, IdxVT
));
3621 setValue(&I
, DAG
.getBuildVector(VT
, DL
, Ops
));
3624 void SelectionDAGBuilder::visitInsertValue(const User
&I
) {
3625 ArrayRef
<unsigned> Indices
;
3626 if (const InsertValueInst
*IV
= dyn_cast
<InsertValueInst
>(&I
))
3627 Indices
= IV
->getIndices();
3629 Indices
= cast
<ConstantExpr
>(&I
)->getIndices();
3631 const Value
*Op0
= I
.getOperand(0);
3632 const Value
*Op1
= I
.getOperand(1);
3633 Type
*AggTy
= I
.getType();
3634 Type
*ValTy
= Op1
->getType();
3635 bool IntoUndef
= isa
<UndefValue
>(Op0
);
3636 bool FromUndef
= isa
<UndefValue
>(Op1
);
3638 unsigned LinearIndex
= ComputeLinearIndex(AggTy
, Indices
);
3640 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3641 SmallVector
<EVT
, 4> AggValueVTs
;
3642 ComputeValueVTs(TLI
, DAG
.getDataLayout(), AggTy
, AggValueVTs
);
3643 SmallVector
<EVT
, 4> ValValueVTs
;
3644 ComputeValueVTs(TLI
, DAG
.getDataLayout(), ValTy
, ValValueVTs
);
3646 unsigned NumAggValues
= AggValueVTs
.size();
3647 unsigned NumValValues
= ValValueVTs
.size();
3648 SmallVector
<SDValue
, 4> Values(NumAggValues
);
3650 // Ignore an insertvalue that produces an empty object
3651 if (!NumAggValues
) {
3652 setValue(&I
, DAG
.getUNDEF(MVT(MVT::Other
)));
3656 SDValue Agg
= getValue(Op0
);
3658 // Copy the beginning value(s) from the original aggregate.
3659 for (; i
!= LinearIndex
; ++i
)
3660 Values
[i
] = IntoUndef
? DAG
.getUNDEF(AggValueVTs
[i
]) :
3661 SDValue(Agg
.getNode(), Agg
.getResNo() + i
);
3662 // Copy values from the inserted value(s).
3664 SDValue Val
= getValue(Op1
);
3665 for (; i
!= LinearIndex
+ NumValValues
; ++i
)
3666 Values
[i
] = FromUndef
? DAG
.getUNDEF(AggValueVTs
[i
]) :
3667 SDValue(Val
.getNode(), Val
.getResNo() + i
- LinearIndex
);
3669 // Copy remaining value(s) from the original aggregate.
3670 for (; i
!= NumAggValues
; ++i
)
3671 Values
[i
] = IntoUndef
? DAG
.getUNDEF(AggValueVTs
[i
]) :
3672 SDValue(Agg
.getNode(), Agg
.getResNo() + i
);
3674 setValue(&I
, DAG
.getNode(ISD::MERGE_VALUES
, getCurSDLoc(),
3675 DAG
.getVTList(AggValueVTs
), Values
));
3678 void SelectionDAGBuilder::visitExtractValue(const User
&I
) {
3679 ArrayRef
<unsigned> Indices
;
3680 if (const ExtractValueInst
*EV
= dyn_cast
<ExtractValueInst
>(&I
))
3681 Indices
= EV
->getIndices();
3683 Indices
= cast
<ConstantExpr
>(&I
)->getIndices();
3685 const Value
*Op0
= I
.getOperand(0);
3686 Type
*AggTy
= Op0
->getType();
3687 Type
*ValTy
= I
.getType();
3688 bool OutOfUndef
= isa
<UndefValue
>(Op0
);
3690 unsigned LinearIndex
= ComputeLinearIndex(AggTy
, Indices
);
3692 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3693 SmallVector
<EVT
, 4> ValValueVTs
;
3694 ComputeValueVTs(TLI
, DAG
.getDataLayout(), ValTy
, ValValueVTs
);
3696 unsigned NumValValues
= ValValueVTs
.size();
3698 // Ignore a extractvalue that produces an empty object
3699 if (!NumValValues
) {
3700 setValue(&I
, DAG
.getUNDEF(MVT(MVT::Other
)));
3704 SmallVector
<SDValue
, 4> Values(NumValValues
);
3706 SDValue Agg
= getValue(Op0
);
3707 // Copy out the selected value(s).
3708 for (unsigned i
= LinearIndex
; i
!= LinearIndex
+ NumValValues
; ++i
)
3709 Values
[i
- LinearIndex
] =
3711 DAG
.getUNDEF(Agg
.getNode()->getValueType(Agg
.getResNo() + i
)) :
3712 SDValue(Agg
.getNode(), Agg
.getResNo() + i
);
3714 setValue(&I
, DAG
.getNode(ISD::MERGE_VALUES
, getCurSDLoc(),
3715 DAG
.getVTList(ValValueVTs
), Values
));
3718 void SelectionDAGBuilder::visitGetElementPtr(const User
&I
) {
3719 Value
*Op0
= I
.getOperand(0);
3720 // Note that the pointer operand may be a vector of pointers. Take the scalar
3721 // element which holds a pointer.
3722 unsigned AS
= Op0
->getType()->getScalarType()->getPointerAddressSpace();
3723 SDValue N
= getValue(Op0
);
3724 SDLoc dl
= getCurSDLoc();
3726 // Normalize Vector GEP - all scalar operands should be converted to the
3728 unsigned VectorWidth
= I
.getType()->isVectorTy() ?
3729 cast
<VectorType
>(I
.getType())->getVectorNumElements() : 0;
3731 if (VectorWidth
&& !N
.getValueType().isVector()) {
3732 LLVMContext
&Context
= *DAG
.getContext();
3733 EVT VT
= EVT::getVectorVT(Context
, N
.getValueType(), VectorWidth
);
3734 N
= DAG
.getSplatBuildVector(VT
, dl
, N
);
3737 for (gep_type_iterator GTI
= gep_type_begin(&I
), E
= gep_type_end(&I
);
3739 const Value
*Idx
= GTI
.getOperand();
3740 if (StructType
*StTy
= GTI
.getStructTypeOrNull()) {
3741 unsigned Field
= cast
<Constant
>(Idx
)->getUniqueInteger().getZExtValue();
3744 uint64_t Offset
= DL
->getStructLayout(StTy
)->getElementOffset(Field
);
3746 // In an inbounds GEP with an offset that is nonnegative even when
3747 // interpreted as signed, assume there is no unsigned overflow.
3749 if (int64_t(Offset
) >= 0 && cast
<GEPOperator
>(I
).isInBounds())
3750 Flags
.setNoUnsignedWrap(true);
3752 N
= DAG
.getNode(ISD::ADD
, dl
, N
.getValueType(), N
,
3753 DAG
.getConstant(Offset
, dl
, N
.getValueType()), Flags
);
3756 unsigned IdxSize
= DAG
.getDataLayout().getIndexSizeInBits(AS
);
3757 MVT IdxTy
= MVT::getIntegerVT(IdxSize
);
3758 APInt
ElementSize(IdxSize
, DL
->getTypeAllocSize(GTI
.getIndexedType()));
3760 // If this is a scalar constant or a splat vector of constants,
3761 // handle it quickly.
3762 const auto *CI
= dyn_cast
<ConstantInt
>(Idx
);
3763 if (!CI
&& isa
<ConstantDataVector
>(Idx
) &&
3764 cast
<ConstantDataVector
>(Idx
)->getSplatValue())
3765 CI
= cast
<ConstantInt
>(cast
<ConstantDataVector
>(Idx
)->getSplatValue());
3770 APInt Offs
= ElementSize
* CI
->getValue().sextOrTrunc(IdxSize
);
3771 LLVMContext
&Context
= *DAG
.getContext();
3772 SDValue OffsVal
= VectorWidth
?
3773 DAG
.getConstant(Offs
, dl
, EVT::getVectorVT(Context
, IdxTy
, VectorWidth
)) :
3774 DAG
.getConstant(Offs
, dl
, IdxTy
);
3776 // In an inbouds GEP with an offset that is nonnegative even when
3777 // interpreted as signed, assume there is no unsigned overflow.
3779 if (Offs
.isNonNegative() && cast
<GEPOperator
>(I
).isInBounds())
3780 Flags
.setNoUnsignedWrap(true);
3782 N
= DAG
.getNode(ISD::ADD
, dl
, N
.getValueType(), N
, OffsVal
, Flags
);
3786 // N = N + Idx * ElementSize;
3787 SDValue IdxN
= getValue(Idx
);
3789 if (!IdxN
.getValueType().isVector() && VectorWidth
) {
3790 EVT VT
= EVT::getVectorVT(*Context
, IdxN
.getValueType(), VectorWidth
);
3791 IdxN
= DAG
.getSplatBuildVector(VT
, dl
, IdxN
);
3794 // If the index is smaller or larger than intptr_t, truncate or extend
3796 IdxN
= DAG
.getSExtOrTrunc(IdxN
, dl
, N
.getValueType());
3798 // If this is a multiply by a power of two, turn it into a shl
3799 // immediately. This is a very common case.
3800 if (ElementSize
!= 1) {
3801 if (ElementSize
.isPowerOf2()) {
3802 unsigned Amt
= ElementSize
.logBase2();
3803 IdxN
= DAG
.getNode(ISD::SHL
, dl
,
3804 N
.getValueType(), IdxN
,
3805 DAG
.getConstant(Amt
, dl
, IdxN
.getValueType()));
3807 SDValue Scale
= DAG
.getConstant(ElementSize
, dl
, IdxN
.getValueType());
3808 IdxN
= DAG
.getNode(ISD::MUL
, dl
,
3809 N
.getValueType(), IdxN
, Scale
);
3813 N
= DAG
.getNode(ISD::ADD
, dl
,
3814 N
.getValueType(), N
, IdxN
);
3821 void SelectionDAGBuilder::visitAlloca(const AllocaInst
&I
) {
3822 // If this is a fixed sized alloca in the entry block of the function,
3823 // allocate it statically on the stack.
3824 if (FuncInfo
.StaticAllocaMap
.count(&I
))
3825 return; // getValue will auto-populate this.
3827 SDLoc dl
= getCurSDLoc();
3828 Type
*Ty
= I
.getAllocatedType();
3829 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3830 auto &DL
= DAG
.getDataLayout();
3831 uint64_t TySize
= DL
.getTypeAllocSize(Ty
);
3833 std::max((unsigned)DL
.getPrefTypeAlignment(Ty
), I
.getAlignment());
3835 SDValue AllocSize
= getValue(I
.getArraySize());
3837 EVT IntPtr
= TLI
.getPointerTy(DAG
.getDataLayout(), DL
.getAllocaAddrSpace());
3838 if (AllocSize
.getValueType() != IntPtr
)
3839 AllocSize
= DAG
.getZExtOrTrunc(AllocSize
, dl
, IntPtr
);
3841 AllocSize
= DAG
.getNode(ISD::MUL
, dl
, IntPtr
,
3843 DAG
.getConstant(TySize
, dl
, IntPtr
));
3845 // Handle alignment. If the requested alignment is less than or equal to
3846 // the stack alignment, ignore it. If the size is greater than or equal to
3847 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3848 unsigned StackAlign
=
3849 DAG
.getSubtarget().getFrameLowering()->getStackAlignment();
3850 if (Align
<= StackAlign
)
3853 // Round the size of the allocation up to the stack alignment size
3854 // by add SA-1 to the size. This doesn't overflow because we're computing
3855 // an address inside an alloca.
3857 Flags
.setNoUnsignedWrap(true);
3858 AllocSize
= DAG
.getNode(ISD::ADD
, dl
, AllocSize
.getValueType(), AllocSize
,
3859 DAG
.getConstant(StackAlign
- 1, dl
, IntPtr
), Flags
);
3861 // Mask out the low bits for alignment purposes.
3863 DAG
.getNode(ISD::AND
, dl
, AllocSize
.getValueType(), AllocSize
,
3864 DAG
.getConstant(~(uint64_t)(StackAlign
- 1), dl
, IntPtr
));
3866 SDValue Ops
[] = {getRoot(), AllocSize
, DAG
.getConstant(Align
, dl
, IntPtr
)};
3867 SDVTList VTs
= DAG
.getVTList(AllocSize
.getValueType(), MVT::Other
);
3868 SDValue DSA
= DAG
.getNode(ISD::DYNAMIC_STACKALLOC
, dl
, VTs
, Ops
);
3870 DAG
.setRoot(DSA
.getValue(1));
3872 assert(FuncInfo
.MF
->getFrameInfo().hasVarSizedObjects());
3875 void SelectionDAGBuilder::visitLoad(const LoadInst
&I
) {
3877 return visitAtomicLoad(I
);
3879 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
3880 const Value
*SV
= I
.getOperand(0);
3881 if (TLI
.supportSwiftError()) {
3882 // Swifterror values can come from either a function parameter with
3883 // swifterror attribute or an alloca with swifterror attribute.
3884 if (const Argument
*Arg
= dyn_cast
<Argument
>(SV
)) {
3885 if (Arg
->hasSwiftErrorAttr())
3886 return visitLoadFromSwiftError(I
);
3889 if (const AllocaInst
*Alloca
= dyn_cast
<AllocaInst
>(SV
)) {
3890 if (Alloca
->isSwiftError())
3891 return visitLoadFromSwiftError(I
);
3895 SDValue Ptr
= getValue(SV
);
3897 Type
*Ty
= I
.getType();
3899 bool isVolatile
= I
.isVolatile();
3900 bool isNonTemporal
= I
.getMetadata(LLVMContext::MD_nontemporal
) != nullptr;
3901 bool isInvariant
= I
.getMetadata(LLVMContext::MD_invariant_load
) != nullptr;
3902 bool isDereferenceable
= isDereferenceablePointer(SV
, DAG
.getDataLayout());
3903 unsigned Alignment
= I
.getAlignment();
3906 I
.getAAMetadata(AAInfo
);
3907 const MDNode
*Ranges
= I
.getMetadata(LLVMContext::MD_range
);
3909 SmallVector
<EVT
, 4> ValueVTs
;
3910 SmallVector
<uint64_t, 4> Offsets
;
3911 ComputeValueVTs(TLI
, DAG
.getDataLayout(), Ty
, ValueVTs
, &Offsets
);
3912 unsigned NumValues
= ValueVTs
.size();
3917 bool ConstantMemory
= false;
3918 if (isVolatile
|| NumValues
> MaxParallelChains
)
3919 // Serialize volatile loads with other side effects.
3922 AA
->pointsToConstantMemory(MemoryLocation(
3924 LocationSize::precise(DAG
.getDataLayout().getTypeStoreSize(Ty
)),
3926 // Do not serialize (non-volatile) loads of constant memory with anything.
3927 Root
= DAG
.getEntryNode();
3928 ConstantMemory
= true;
3930 // Do not serialize non-volatile loads against each other.
3931 Root
= DAG
.getRoot();
3934 SDLoc dl
= getCurSDLoc();
3937 Root
= TLI
.prepareVolatileOrAtomicLoad(Root
, dl
, DAG
);
3939 // An aggregate load cannot wrap around the address space, so offsets to its
3940 // parts don't wrap either.
3942 Flags
.setNoUnsignedWrap(true);
3944 SmallVector
<SDValue
, 4> Values(NumValues
);
3945 SmallVector
<SDValue
, 4> Chains(std::min(MaxParallelChains
, NumValues
));
3946 EVT PtrVT
= Ptr
.getValueType();
3947 unsigned ChainI
= 0;
3948 for (unsigned i
= 0; i
!= NumValues
; ++i
, ++ChainI
) {
3949 // Serializing loads here may result in excessive register pressure, and
3950 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3951 // could recover a bit by hoisting nodes upward in the chain by recognizing
3952 // they are side-effect free or do not alias. The optimizer should really
3953 // avoid this case by converting large object/array copies to llvm.memcpy
3954 // (MaxParallelChains should always remain as failsafe).
3955 if (ChainI
== MaxParallelChains
) {
3956 assert(PendingLoads
.empty() && "PendingLoads must be serialized first");
3957 SDValue Chain
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
,
3958 makeArrayRef(Chains
.data(), ChainI
));
3962 SDValue A
= DAG
.getNode(ISD::ADD
, dl
,
3964 DAG
.getConstant(Offsets
[i
], dl
, PtrVT
),
3966 auto MMOFlags
= MachineMemOperand::MONone
;
3968 MMOFlags
|= MachineMemOperand::MOVolatile
;
3970 MMOFlags
|= MachineMemOperand::MONonTemporal
;
3972 MMOFlags
|= MachineMemOperand::MOInvariant
;
3973 if (isDereferenceable
)
3974 MMOFlags
|= MachineMemOperand::MODereferenceable
;
3975 MMOFlags
|= TLI
.getMMOFlags(I
);
3977 SDValue L
= DAG
.getLoad(ValueVTs
[i
], dl
, Root
, A
,
3978 MachinePointerInfo(SV
, Offsets
[i
]), Alignment
,
3979 MMOFlags
, AAInfo
, Ranges
);
3982 Chains
[ChainI
] = L
.getValue(1);
3985 if (!ConstantMemory
) {
3986 SDValue Chain
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
,
3987 makeArrayRef(Chains
.data(), ChainI
));
3991 PendingLoads
.push_back(Chain
);
3994 setValue(&I
, DAG
.getNode(ISD::MERGE_VALUES
, dl
,
3995 DAG
.getVTList(ValueVTs
), Values
));
3998 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst
&I
) {
3999 assert(DAG
.getTargetLoweringInfo().supportSwiftError() &&
4000 "call visitStoreToSwiftError when backend supports swifterror");
4002 SmallVector
<EVT
, 4> ValueVTs
;
4003 SmallVector
<uint64_t, 4> Offsets
;
4004 const Value
*SrcV
= I
.getOperand(0);
4005 ComputeValueVTs(DAG
.getTargetLoweringInfo(), DAG
.getDataLayout(),
4006 SrcV
->getType(), ValueVTs
, &Offsets
);
4007 assert(ValueVTs
.size() == 1 && Offsets
[0] == 0 &&
4008 "expect a single EVT for swifterror");
4010 SDValue Src
= getValue(SrcV
);
4011 // Create a virtual register, then update the virtual register.
4012 unsigned VReg
; bool CreatedVReg
;
4013 std::tie(VReg
, CreatedVReg
) = FuncInfo
.getOrCreateSwiftErrorVRegDefAt(&I
);
4014 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4015 // Chain can be getRoot or getControlRoot.
4016 SDValue CopyNode
= DAG
.getCopyToReg(getRoot(), getCurSDLoc(), VReg
,
4017 SDValue(Src
.getNode(), Src
.getResNo()));
4018 DAG
.setRoot(CopyNode
);
4020 FuncInfo
.setCurrentSwiftErrorVReg(FuncInfo
.MBB
, I
.getOperand(1), VReg
);
4023 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst
&I
) {
4024 assert(DAG
.getTargetLoweringInfo().supportSwiftError() &&
4025 "call visitLoadFromSwiftError when backend supports swifterror");
4027 assert(!I
.isVolatile() &&
4028 I
.getMetadata(LLVMContext::MD_nontemporal
) == nullptr &&
4029 I
.getMetadata(LLVMContext::MD_invariant_load
) == nullptr &&
4030 "Support volatile, non temporal, invariant for load_from_swift_error");
4032 const Value
*SV
= I
.getOperand(0);
4033 Type
*Ty
= I
.getType();
4035 I
.getAAMetadata(AAInfo
);
4038 !AA
->pointsToConstantMemory(MemoryLocation(
4039 SV
, LocationSize::precise(DAG
.getDataLayout().getTypeStoreSize(Ty
)),
4041 "load_from_swift_error should not be constant memory");
4043 SmallVector
<EVT
, 4> ValueVTs
;
4044 SmallVector
<uint64_t, 4> Offsets
;
4045 ComputeValueVTs(DAG
.getTargetLoweringInfo(), DAG
.getDataLayout(), Ty
,
4046 ValueVTs
, &Offsets
);
4047 assert(ValueVTs
.size() == 1 && Offsets
[0] == 0 &&
4048 "expect a single EVT for swifterror");
4050 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4051 SDValue L
= DAG
.getCopyFromReg(
4052 getRoot(), getCurSDLoc(),
4053 FuncInfo
.getOrCreateSwiftErrorVRegUseAt(&I
, FuncInfo
.MBB
, SV
).first
,
4059 void SelectionDAGBuilder::visitStore(const StoreInst
&I
) {
4061 return visitAtomicStore(I
);
4063 const Value
*SrcV
= I
.getOperand(0);
4064 const Value
*PtrV
= I
.getOperand(1);
4066 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4067 if (TLI
.supportSwiftError()) {
4068 // Swifterror values can come from either a function parameter with
4069 // swifterror attribute or an alloca with swifterror attribute.
4070 if (const Argument
*Arg
= dyn_cast
<Argument
>(PtrV
)) {
4071 if (Arg
->hasSwiftErrorAttr())
4072 return visitStoreToSwiftError(I
);
4075 if (const AllocaInst
*Alloca
= dyn_cast
<AllocaInst
>(PtrV
)) {
4076 if (Alloca
->isSwiftError())
4077 return visitStoreToSwiftError(I
);
4081 SmallVector
<EVT
, 4> ValueVTs
;
4082 SmallVector
<uint64_t, 4> Offsets
;
4083 ComputeValueVTs(DAG
.getTargetLoweringInfo(), DAG
.getDataLayout(),
4084 SrcV
->getType(), ValueVTs
, &Offsets
);
4085 unsigned NumValues
= ValueVTs
.size();
4089 // Get the lowered operands. Note that we do this after
4090 // checking if NumResults is zero, because with zero results
4091 // the operands won't have values in the map.
4092 SDValue Src
= getValue(SrcV
);
4093 SDValue Ptr
= getValue(PtrV
);
4095 SDValue Root
= getRoot();
4096 SmallVector
<SDValue
, 4> Chains(std::min(MaxParallelChains
, NumValues
));
4097 SDLoc dl
= getCurSDLoc();
4098 EVT PtrVT
= Ptr
.getValueType();
4099 unsigned Alignment
= I
.getAlignment();
4101 I
.getAAMetadata(AAInfo
);
4103 auto MMOFlags
= MachineMemOperand::MONone
;
4105 MMOFlags
|= MachineMemOperand::MOVolatile
;
4106 if (I
.getMetadata(LLVMContext::MD_nontemporal
) != nullptr)
4107 MMOFlags
|= MachineMemOperand::MONonTemporal
;
4108 MMOFlags
|= TLI
.getMMOFlags(I
);
4110 // An aggregate load cannot wrap around the address space, so offsets to its
4111 // parts don't wrap either.
4113 Flags
.setNoUnsignedWrap(true);
4115 unsigned ChainI
= 0;
4116 for (unsigned i
= 0; i
!= NumValues
; ++i
, ++ChainI
) {
4117 // See visitLoad comments.
4118 if (ChainI
== MaxParallelChains
) {
4119 SDValue Chain
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
,
4120 makeArrayRef(Chains
.data(), ChainI
));
4124 SDValue Add
= DAG
.getNode(ISD::ADD
, dl
, PtrVT
, Ptr
,
4125 DAG
.getConstant(Offsets
[i
], dl
, PtrVT
), Flags
);
4126 SDValue St
= DAG
.getStore(
4127 Root
, dl
, SDValue(Src
.getNode(), Src
.getResNo() + i
), Add
,
4128 MachinePointerInfo(PtrV
, Offsets
[i
]), Alignment
, MMOFlags
, AAInfo
);
4129 Chains
[ChainI
] = St
;
4132 SDValue StoreNode
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
,
4133 makeArrayRef(Chains
.data(), ChainI
));
4134 DAG
.setRoot(StoreNode
);
4137 void SelectionDAGBuilder::visitMaskedStore(const CallInst
&I
,
4138 bool IsCompressing
) {
4139 SDLoc sdl
= getCurSDLoc();
4141 auto getMaskedStoreOps
= [&](Value
* &Ptr
, Value
* &Mask
, Value
* &Src0
,
4142 unsigned& Alignment
) {
4143 // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4144 Src0
= I
.getArgOperand(0);
4145 Ptr
= I
.getArgOperand(1);
4146 Alignment
= cast
<ConstantInt
>(I
.getArgOperand(2))->getZExtValue();
4147 Mask
= I
.getArgOperand(3);
4149 auto getCompressingStoreOps
= [&](Value
* &Ptr
, Value
* &Mask
, Value
* &Src0
,
4150 unsigned& Alignment
) {
4151 // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4152 Src0
= I
.getArgOperand(0);
4153 Ptr
= I
.getArgOperand(1);
4154 Mask
= I
.getArgOperand(2);
4158 Value
*PtrOperand
, *MaskOperand
, *Src0Operand
;
4161 getCompressingStoreOps(PtrOperand
, MaskOperand
, Src0Operand
, Alignment
);
4163 getMaskedStoreOps(PtrOperand
, MaskOperand
, Src0Operand
, Alignment
);
4165 SDValue Ptr
= getValue(PtrOperand
);
4166 SDValue Src0
= getValue(Src0Operand
);
4167 SDValue Mask
= getValue(MaskOperand
);
4169 EVT VT
= Src0
.getValueType();
4171 Alignment
= DAG
.getEVTAlignment(VT
);
4174 I
.getAAMetadata(AAInfo
);
4176 MachineMemOperand
*MMO
=
4177 DAG
.getMachineFunction().
4178 getMachineMemOperand(MachinePointerInfo(PtrOperand
),
4179 MachineMemOperand::MOStore
, VT
.getStoreSize(),
4181 SDValue StoreNode
= DAG
.getMaskedStore(getRoot(), sdl
, Src0
, Ptr
, Mask
, VT
,
4182 MMO
, false /* Truncating */,
4184 DAG
.setRoot(StoreNode
);
4185 setValue(&I
, StoreNode
);
4188 // Get a uniform base for the Gather/Scatter intrinsic.
4189 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4190 // We try to represent it as a base pointer + vector of indices.
4191 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4192 // The first operand of the GEP may be a single pointer or a vector of pointers
4194 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4196 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
4197 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4199 // When the first GEP operand is a single pointer - it is the uniform base we
4200 // are looking for. If first operand of the GEP is a splat vector - we
4201 // extract the splat value and use it as a uniform base.
4202 // In all other cases the function returns 'false'.
4203 static bool getUniformBase(const Value
* &Ptr
, SDValue
& Base
, SDValue
& Index
,
4204 SDValue
&Scale
, SelectionDAGBuilder
* SDB
) {
4205 SelectionDAG
& DAG
= SDB
->DAG
;
4206 LLVMContext
&Context
= *DAG
.getContext();
4208 assert(Ptr
->getType()->isVectorTy() && "Uexpected pointer type");
4209 const GetElementPtrInst
*GEP
= dyn_cast
<GetElementPtrInst
>(Ptr
);
4213 const Value
*GEPPtr
= GEP
->getPointerOperand();
4214 if (!GEPPtr
->getType()->isVectorTy())
4216 else if (!(Ptr
= getSplatValue(GEPPtr
)))
4219 unsigned FinalIndex
= GEP
->getNumOperands() - 1;
4220 Value
*IndexVal
= GEP
->getOperand(FinalIndex
);
4222 // Ensure all the other indices are 0.
4223 for (unsigned i
= 1; i
< FinalIndex
; ++i
) {
4224 auto *C
= dyn_cast
<ConstantInt
>(GEP
->getOperand(i
));
4225 if (!C
|| !C
->isZero())
4229 // The operands of the GEP may be defined in another basic block.
4230 // In this case we'll not find nodes for the operands.
4231 if (!SDB
->findValue(Ptr
) || !SDB
->findValue(IndexVal
))
4234 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4235 const DataLayout
&DL
= DAG
.getDataLayout();
4236 Scale
= DAG
.getTargetConstant(DL
.getTypeAllocSize(GEP
->getResultElementType()),
4237 SDB
->getCurSDLoc(), TLI
.getPointerTy(DL
));
4238 Base
= SDB
->getValue(Ptr
);
4239 Index
= SDB
->getValue(IndexVal
);
4241 if (!Index
.getValueType().isVector()) {
4242 unsigned GEPWidth
= GEP
->getType()->getVectorNumElements();
4243 EVT VT
= EVT::getVectorVT(Context
, Index
.getValueType(), GEPWidth
);
4244 Index
= DAG
.getSplatBuildVector(VT
, SDLoc(Index
), Index
);
4249 void SelectionDAGBuilder::visitMaskedScatter(const CallInst
&I
) {
4250 SDLoc sdl
= getCurSDLoc();
4252 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4253 const Value
*Ptr
= I
.getArgOperand(1);
4254 SDValue Src0
= getValue(I
.getArgOperand(0));
4255 SDValue Mask
= getValue(I
.getArgOperand(3));
4256 EVT VT
= Src0
.getValueType();
4257 unsigned Alignment
= (cast
<ConstantInt
>(I
.getArgOperand(2)))->getZExtValue();
4259 Alignment
= DAG
.getEVTAlignment(VT
);
4260 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4263 I
.getAAMetadata(AAInfo
);
4268 const Value
*BasePtr
= Ptr
;
4269 bool UniformBase
= getUniformBase(BasePtr
, Base
, Index
, Scale
, this);
4271 const Value
*MemOpBasePtr
= UniformBase
? BasePtr
: nullptr;
4272 MachineMemOperand
*MMO
= DAG
.getMachineFunction().
4273 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr
),
4274 MachineMemOperand::MOStore
, VT
.getStoreSize(),
4277 Base
= DAG
.getConstant(0, sdl
, TLI
.getPointerTy(DAG
.getDataLayout()));
4278 Index
= getValue(Ptr
);
4279 Scale
= DAG
.getTargetConstant(1, sdl
, TLI
.getPointerTy(DAG
.getDataLayout()));
4281 SDValue Ops
[] = { getRoot(), Src0
, Mask
, Base
, Index
, Scale
};
4282 SDValue Scatter
= DAG
.getMaskedScatter(DAG
.getVTList(MVT::Other
), VT
, sdl
,
4284 DAG
.setRoot(Scatter
);
4285 setValue(&I
, Scatter
);
4288 void SelectionDAGBuilder::visitMaskedLoad(const CallInst
&I
, bool IsExpanding
) {
4289 SDLoc sdl
= getCurSDLoc();
4291 auto getMaskedLoadOps
= [&](Value
* &Ptr
, Value
* &Mask
, Value
* &Src0
,
4292 unsigned& Alignment
) {
4293 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4294 Ptr
= I
.getArgOperand(0);
4295 Alignment
= cast
<ConstantInt
>(I
.getArgOperand(1))->getZExtValue();
4296 Mask
= I
.getArgOperand(2);
4297 Src0
= I
.getArgOperand(3);
4299 auto getExpandingLoadOps
= [&](Value
* &Ptr
, Value
* &Mask
, Value
* &Src0
,
4300 unsigned& Alignment
) {
4301 // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4302 Ptr
= I
.getArgOperand(0);
4304 Mask
= I
.getArgOperand(1);
4305 Src0
= I
.getArgOperand(2);
4308 Value
*PtrOperand
, *MaskOperand
, *Src0Operand
;
4311 getExpandingLoadOps(PtrOperand
, MaskOperand
, Src0Operand
, Alignment
);
4313 getMaskedLoadOps(PtrOperand
, MaskOperand
, Src0Operand
, Alignment
);
4315 SDValue Ptr
= getValue(PtrOperand
);
4316 SDValue Src0
= getValue(Src0Operand
);
4317 SDValue Mask
= getValue(MaskOperand
);
4319 EVT VT
= Src0
.getValueType();
4321 Alignment
= DAG
.getEVTAlignment(VT
);
4324 I
.getAAMetadata(AAInfo
);
4325 const MDNode
*Ranges
= I
.getMetadata(LLVMContext::MD_range
);
4327 // Do not serialize masked loads of constant memory with anything.
4329 !AA
|| !AA
->pointsToConstantMemory(MemoryLocation(
4331 LocationSize::precise(
4332 DAG
.getDataLayout().getTypeStoreSize(I
.getType())),
4334 SDValue InChain
= AddToChain
? DAG
.getRoot() : DAG
.getEntryNode();
4336 MachineMemOperand
*MMO
=
4337 DAG
.getMachineFunction().
4338 getMachineMemOperand(MachinePointerInfo(PtrOperand
),
4339 MachineMemOperand::MOLoad
, VT
.getStoreSize(),
4340 Alignment
, AAInfo
, Ranges
);
4342 SDValue Load
= DAG
.getMaskedLoad(VT
, sdl
, InChain
, Ptr
, Mask
, Src0
, VT
, MMO
,
4343 ISD::NON_EXTLOAD
, IsExpanding
);
4345 PendingLoads
.push_back(Load
.getValue(1));
4349 void SelectionDAGBuilder::visitMaskedGather(const CallInst
&I
) {
4350 SDLoc sdl
= getCurSDLoc();
4352 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4353 const Value
*Ptr
= I
.getArgOperand(0);
4354 SDValue Src0
= getValue(I
.getArgOperand(3));
4355 SDValue Mask
= getValue(I
.getArgOperand(2));
4357 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4358 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
4359 unsigned Alignment
= (cast
<ConstantInt
>(I
.getArgOperand(1)))->getZExtValue();
4361 Alignment
= DAG
.getEVTAlignment(VT
);
4364 I
.getAAMetadata(AAInfo
);
4365 const MDNode
*Ranges
= I
.getMetadata(LLVMContext::MD_range
);
4367 SDValue Root
= DAG
.getRoot();
4371 const Value
*BasePtr
= Ptr
;
4372 bool UniformBase
= getUniformBase(BasePtr
, Base
, Index
, Scale
, this);
4373 bool ConstantMemory
= false;
4374 if (UniformBase
&& AA
&&
4375 AA
->pointsToConstantMemory(
4376 MemoryLocation(BasePtr
,
4377 LocationSize::precise(
4378 DAG
.getDataLayout().getTypeStoreSize(I
.getType())),
4380 // Do not serialize (non-volatile) loads of constant memory with anything.
4381 Root
= DAG
.getEntryNode();
4382 ConstantMemory
= true;
4385 MachineMemOperand
*MMO
=
4386 DAG
.getMachineFunction().
4387 getMachineMemOperand(MachinePointerInfo(UniformBase
? BasePtr
: nullptr),
4388 MachineMemOperand::MOLoad
, VT
.getStoreSize(),
4389 Alignment
, AAInfo
, Ranges
);
4392 Base
= DAG
.getConstant(0, sdl
, TLI
.getPointerTy(DAG
.getDataLayout()));
4393 Index
= getValue(Ptr
);
4394 Scale
= DAG
.getTargetConstant(1, sdl
, TLI
.getPointerTy(DAG
.getDataLayout()));
4396 SDValue Ops
[] = { Root
, Src0
, Mask
, Base
, Index
, Scale
};
4397 SDValue Gather
= DAG
.getMaskedGather(DAG
.getVTList(VT
, MVT::Other
), VT
, sdl
,
4400 SDValue OutChain
= Gather
.getValue(1);
4401 if (!ConstantMemory
)
4402 PendingLoads
.push_back(OutChain
);
4403 setValue(&I
, Gather
);
4406 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst
&I
) {
4407 SDLoc dl
= getCurSDLoc();
4408 AtomicOrdering SuccessOrdering
= I
.getSuccessOrdering();
4409 AtomicOrdering FailureOrdering
= I
.getFailureOrdering();
4410 SyncScope::ID SSID
= I
.getSyncScopeID();
4412 SDValue InChain
= getRoot();
4414 MVT MemVT
= getValue(I
.getCompareOperand()).getSimpleValueType();
4415 SDVTList VTs
= DAG
.getVTList(MemVT
, MVT::i1
, MVT::Other
);
4417 auto Alignment
= DAG
.getEVTAlignment(MemVT
);
4419 // FIXME: Volatile isn't really correct; we should keep track of atomic
4420 // orderings in the memoperand.
4421 auto Flags
= MachineMemOperand::MOVolatile
| MachineMemOperand::MOLoad
|
4422 MachineMemOperand::MOStore
;
4424 MachineFunction
&MF
= DAG
.getMachineFunction();
4425 MachineMemOperand
*MMO
=
4426 MF
.getMachineMemOperand(MachinePointerInfo(I
.getPointerOperand()),
4427 Flags
, MemVT
.getStoreSize(), Alignment
,
4428 AAMDNodes(), nullptr, SSID
, SuccessOrdering
,
4431 SDValue L
= DAG
.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS
,
4432 dl
, MemVT
, VTs
, InChain
,
4433 getValue(I
.getPointerOperand()),
4434 getValue(I
.getCompareOperand()),
4435 getValue(I
.getNewValOperand()), MMO
);
4437 SDValue OutChain
= L
.getValue(2);
4440 DAG
.setRoot(OutChain
);
4443 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst
&I
) {
4444 SDLoc dl
= getCurSDLoc();
4446 switch (I
.getOperation()) {
4447 default: llvm_unreachable("Unknown atomicrmw operation");
4448 case AtomicRMWInst::Xchg
: NT
= ISD::ATOMIC_SWAP
; break;
4449 case AtomicRMWInst::Add
: NT
= ISD::ATOMIC_LOAD_ADD
; break;
4450 case AtomicRMWInst::Sub
: NT
= ISD::ATOMIC_LOAD_SUB
; break;
4451 case AtomicRMWInst::And
: NT
= ISD::ATOMIC_LOAD_AND
; break;
4452 case AtomicRMWInst::Nand
: NT
= ISD::ATOMIC_LOAD_NAND
; break;
4453 case AtomicRMWInst::Or
: NT
= ISD::ATOMIC_LOAD_OR
; break;
4454 case AtomicRMWInst::Xor
: NT
= ISD::ATOMIC_LOAD_XOR
; break;
4455 case AtomicRMWInst::Max
: NT
= ISD::ATOMIC_LOAD_MAX
; break;
4456 case AtomicRMWInst::Min
: NT
= ISD::ATOMIC_LOAD_MIN
; break;
4457 case AtomicRMWInst::UMax
: NT
= ISD::ATOMIC_LOAD_UMAX
; break;
4458 case AtomicRMWInst::UMin
: NT
= ISD::ATOMIC_LOAD_UMIN
; break;
4459 case AtomicRMWInst::FAdd
: NT
= ISD::ATOMIC_LOAD_FADD
; break;
4460 case AtomicRMWInst::FSub
: NT
= ISD::ATOMIC_LOAD_FSUB
; break;
4462 AtomicOrdering Ordering
= I
.getOrdering();
4463 SyncScope::ID SSID
= I
.getSyncScopeID();
4465 SDValue InChain
= getRoot();
4467 auto MemVT
= getValue(I
.getValOperand()).getSimpleValueType();
4468 auto Alignment
= DAG
.getEVTAlignment(MemVT
);
4470 // For now, atomics are considered to be volatile always, and they are
4472 // FIXME: Volatile isn't really correct; we should keep track of atomic
4473 // orderings in the memoperand.
4474 auto Flags
= MachineMemOperand::MOVolatile
|
4475 MachineMemOperand::MOLoad
| MachineMemOperand::MOStore
;
4477 MachineFunction
&MF
= DAG
.getMachineFunction();
4478 MachineMemOperand
*MMO
=
4479 MF
.getMachineMemOperand(MachinePointerInfo(I
.getPointerOperand()), Flags
,
4480 MemVT
.getStoreSize(), Alignment
, AAMDNodes(),
4481 nullptr, SSID
, Ordering
);
4484 DAG
.getAtomic(NT
, dl
, MemVT
, InChain
,
4485 getValue(I
.getPointerOperand()), getValue(I
.getValOperand()),
4488 SDValue OutChain
= L
.getValue(1);
4491 DAG
.setRoot(OutChain
);
4494 void SelectionDAGBuilder::visitFence(const FenceInst
&I
) {
4495 SDLoc dl
= getCurSDLoc();
4496 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4499 Ops
[1] = DAG
.getConstant((unsigned)I
.getOrdering(), dl
,
4500 TLI
.getFenceOperandTy(DAG
.getDataLayout()));
4501 Ops
[2] = DAG
.getConstant(I
.getSyncScopeID(), dl
,
4502 TLI
.getFenceOperandTy(DAG
.getDataLayout()));
4503 DAG
.setRoot(DAG
.getNode(ISD::ATOMIC_FENCE
, dl
, MVT::Other
, Ops
));
4506 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst
&I
) {
4507 SDLoc dl
= getCurSDLoc();
4508 AtomicOrdering Order
= I
.getOrdering();
4509 SyncScope::ID SSID
= I
.getSyncScopeID();
4511 SDValue InChain
= getRoot();
4513 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4514 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
4516 if (!TLI
.supportsUnalignedAtomics() &&
4517 I
.getAlignment() < VT
.getStoreSize())
4518 report_fatal_error("Cannot generate unaligned atomic load");
4520 MachineMemOperand
*MMO
=
4521 DAG
.getMachineFunction().
4522 getMachineMemOperand(MachinePointerInfo(I
.getPointerOperand()),
4523 MachineMemOperand::MOVolatile
|
4524 MachineMemOperand::MOLoad
,
4526 I
.getAlignment() ? I
.getAlignment() :
4527 DAG
.getEVTAlignment(VT
),
4528 AAMDNodes(), nullptr, SSID
, Order
);
4530 InChain
= TLI
.prepareVolatileOrAtomicLoad(InChain
, dl
, DAG
);
4532 DAG
.getAtomic(ISD::ATOMIC_LOAD
, dl
, VT
, VT
, InChain
,
4533 getValue(I
.getPointerOperand()), MMO
);
4535 SDValue OutChain
= L
.getValue(1);
4538 DAG
.setRoot(OutChain
);
4541 void SelectionDAGBuilder::visitAtomicStore(const StoreInst
&I
) {
4542 SDLoc dl
= getCurSDLoc();
4544 AtomicOrdering Ordering
= I
.getOrdering();
4545 SyncScope::ID SSID
= I
.getSyncScopeID();
4547 SDValue InChain
= getRoot();
4549 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4551 TLI
.getValueType(DAG
.getDataLayout(), I
.getValueOperand()->getType());
4553 if (I
.getAlignment() < VT
.getStoreSize())
4554 report_fatal_error("Cannot generate unaligned atomic store");
4556 // For now, atomics are considered to be volatile always, and they are
4558 // FIXME: Volatile isn't really correct; we should keep track of atomic
4559 // orderings in the memoperand.
4560 auto Flags
= MachineMemOperand::MOVolatile
| MachineMemOperand::MOStore
;
4562 MachineFunction
&MF
= DAG
.getMachineFunction();
4563 MachineMemOperand
*MMO
=
4564 MF
.getMachineMemOperand(MachinePointerInfo(I
.getPointerOperand()), Flags
,
4565 VT
.getStoreSize(), I
.getAlignment(), AAMDNodes(),
4566 nullptr, SSID
, Ordering
);
4568 DAG
.getAtomic(ISD::ATOMIC_STORE
, dl
, VT
, InChain
,
4569 getValue(I
.getPointerOperand()), getValue(I
.getValueOperand()),
4573 DAG
.setRoot(OutChain
);
4576 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4578 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst
&I
,
4579 unsigned Intrinsic
) {
4580 // Ignore the callsite's attributes. A specific call site may be marked with
4581 // readnone, but the lowering code will expect the chain based on the
4583 const Function
*F
= I
.getCalledFunction();
4584 bool HasChain
= !F
->doesNotAccessMemory();
4585 bool OnlyLoad
= HasChain
&& F
->onlyReadsMemory();
4587 // Build the operand list.
4588 SmallVector
<SDValue
, 8> Ops
;
4589 if (HasChain
) { // If this intrinsic has side-effects, chainify it.
4591 // We don't need to serialize loads against other loads.
4592 Ops
.push_back(DAG
.getRoot());
4594 Ops
.push_back(getRoot());
4598 // Info is set by getTgtMemInstrinsic
4599 TargetLowering::IntrinsicInfo Info
;
4600 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4601 bool IsTgtIntrinsic
= TLI
.getTgtMemIntrinsic(Info
, I
,
4602 DAG
.getMachineFunction(),
4605 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4606 if (!IsTgtIntrinsic
|| Info
.opc
== ISD::INTRINSIC_VOID
||
4607 Info
.opc
== ISD::INTRINSIC_W_CHAIN
)
4608 Ops
.push_back(DAG
.getTargetConstant(Intrinsic
, getCurSDLoc(),
4609 TLI
.getPointerTy(DAG
.getDataLayout())));
4611 // Add all operands of the call to the operand list.
4612 for (unsigned i
= 0, e
= I
.getNumArgOperands(); i
!= e
; ++i
) {
4613 SDValue Op
= getValue(I
.getArgOperand(i
));
4617 SmallVector
<EVT
, 4> ValueVTs
;
4618 ComputeValueVTs(TLI
, DAG
.getDataLayout(), I
.getType(), ValueVTs
);
4621 ValueVTs
.push_back(MVT::Other
);
4623 SDVTList VTs
= DAG
.getVTList(ValueVTs
);
4627 if (IsTgtIntrinsic
) {
4628 // This is target intrinsic that touches memory
4629 Result
= DAG
.getMemIntrinsicNode(Info
.opc
, getCurSDLoc(), VTs
,
4631 MachinePointerInfo(Info
.ptrVal
, Info
.offset
), Info
.align
,
4632 Info
.flags
, Info
.size
);
4633 } else if (!HasChain
) {
4634 Result
= DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, getCurSDLoc(), VTs
, Ops
);
4635 } else if (!I
.getType()->isVoidTy()) {
4636 Result
= DAG
.getNode(ISD::INTRINSIC_W_CHAIN
, getCurSDLoc(), VTs
, Ops
);
4638 Result
= DAG
.getNode(ISD::INTRINSIC_VOID
, getCurSDLoc(), VTs
, Ops
);
4642 SDValue Chain
= Result
.getValue(Result
.getNode()->getNumValues()-1);
4644 PendingLoads
.push_back(Chain
);
4649 if (!I
.getType()->isVoidTy()) {
4650 if (VectorType
*PTy
= dyn_cast
<VectorType
>(I
.getType())) {
4651 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), PTy
);
4652 Result
= DAG
.getNode(ISD::BITCAST
, getCurSDLoc(), VT
, Result
);
4654 Result
= lowerRangeToAssertZExt(DAG
, I
, Result
);
4656 setValue(&I
, Result
);
4660 /// GetSignificand - Get the significand and build it into a floating-point
4661 /// number with exponent of 1:
4663 /// Op = (Op & 0x007fffff) | 0x3f800000;
4665 /// where Op is the hexadecimal representation of floating point value.
4666 static SDValue
GetSignificand(SelectionDAG
&DAG
, SDValue Op
, const SDLoc
&dl
) {
4667 SDValue t1
= DAG
.getNode(ISD::AND
, dl
, MVT::i32
, Op
,
4668 DAG
.getConstant(0x007fffff, dl
, MVT::i32
));
4669 SDValue t2
= DAG
.getNode(ISD::OR
, dl
, MVT::i32
, t1
,
4670 DAG
.getConstant(0x3f800000, dl
, MVT::i32
));
4671 return DAG
.getNode(ISD::BITCAST
, dl
, MVT::f32
, t2
);
4674 /// GetExponent - Get the exponent:
4676 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4678 /// where Op is the hexadecimal representation of floating point value.
4679 static SDValue
GetExponent(SelectionDAG
&DAG
, SDValue Op
,
4680 const TargetLowering
&TLI
, const SDLoc
&dl
) {
4681 SDValue t0
= DAG
.getNode(ISD::AND
, dl
, MVT::i32
, Op
,
4682 DAG
.getConstant(0x7f800000, dl
, MVT::i32
));
4683 SDValue t1
= DAG
.getNode(
4684 ISD::SRL
, dl
, MVT::i32
, t0
,
4685 DAG
.getConstant(23, dl
, TLI
.getPointerTy(DAG
.getDataLayout())));
4686 SDValue t2
= DAG
.getNode(ISD::SUB
, dl
, MVT::i32
, t1
,
4687 DAG
.getConstant(127, dl
, MVT::i32
));
4688 return DAG
.getNode(ISD::SINT_TO_FP
, dl
, MVT::f32
, t2
);
4691 /// getF32Constant - Get 32-bit floating point constant.
4692 static SDValue
getF32Constant(SelectionDAG
&DAG
, unsigned Flt
,
4694 return DAG
.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt
)), dl
,
4698 static SDValue
getLimitedPrecisionExp2(SDValue t0
, const SDLoc
&dl
,
4699 SelectionDAG
&DAG
) {
4700 // TODO: What fast-math-flags should be set on the floating-point nodes?
4702 // IntegerPartOfX = ((int32_t)(t0);
4703 SDValue IntegerPartOfX
= DAG
.getNode(ISD::FP_TO_SINT
, dl
, MVT::i32
, t0
);
4705 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
4706 SDValue t1
= DAG
.getNode(ISD::SINT_TO_FP
, dl
, MVT::f32
, IntegerPartOfX
);
4707 SDValue X
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t0
, t1
);
4709 // IntegerPartOfX <<= 23;
4710 IntegerPartOfX
= DAG
.getNode(
4711 ISD::SHL
, dl
, MVT::i32
, IntegerPartOfX
,
4712 DAG
.getConstant(23, dl
, DAG
.getTargetLoweringInfo().getPointerTy(
4713 DAG
.getDataLayout())));
4715 SDValue TwoToFractionalPartOfX
;
4716 if (LimitFloatPrecision
<= 6) {
4717 // For floating-point precision of 6:
4719 // TwoToFractionalPartOfX =
4721 // (0.735607626f + 0.252464424f * x) * x;
4723 // error 0.0144103317, which is 6 bits
4724 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4725 getF32Constant(DAG
, 0x3e814304, dl
));
4726 SDValue t3
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t2
,
4727 getF32Constant(DAG
, 0x3f3c50c8, dl
));
4728 SDValue t4
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t3
, X
);
4729 TwoToFractionalPartOfX
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t4
,
4730 getF32Constant(DAG
, 0x3f7f5e7e, dl
));
4731 } else if (LimitFloatPrecision
<= 12) {
4732 // For floating-point precision of 12:
4734 // TwoToFractionalPartOfX =
4737 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4739 // error 0.000107046256, which is 13 to 14 bits
4740 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4741 getF32Constant(DAG
, 0x3da235e3, dl
));
4742 SDValue t3
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t2
,
4743 getF32Constant(DAG
, 0x3e65b8f3, dl
));
4744 SDValue t4
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t3
, X
);
4745 SDValue t5
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t4
,
4746 getF32Constant(DAG
, 0x3f324b07, dl
));
4747 SDValue t6
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t5
, X
);
4748 TwoToFractionalPartOfX
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t6
,
4749 getF32Constant(DAG
, 0x3f7ff8fd, dl
));
4750 } else { // LimitFloatPrecision <= 18
4751 // For floating-point precision of 18:
4753 // TwoToFractionalPartOfX =
4757 // (0.554906021e-1f +
4758 // (0.961591928e-2f +
4759 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4760 // error 2.47208000*10^(-7), which is better than 18 bits
4761 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4762 getF32Constant(DAG
, 0x3924b03e, dl
));
4763 SDValue t3
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t2
,
4764 getF32Constant(DAG
, 0x3ab24b87, dl
));
4765 SDValue t4
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t3
, X
);
4766 SDValue t5
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t4
,
4767 getF32Constant(DAG
, 0x3c1d8c17, dl
));
4768 SDValue t6
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t5
, X
);
4769 SDValue t7
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t6
,
4770 getF32Constant(DAG
, 0x3d634a1d, dl
));
4771 SDValue t8
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t7
, X
);
4772 SDValue t9
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t8
,
4773 getF32Constant(DAG
, 0x3e75fe14, dl
));
4774 SDValue t10
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t9
, X
);
4775 SDValue t11
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t10
,
4776 getF32Constant(DAG
, 0x3f317234, dl
));
4777 SDValue t12
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t11
, X
);
4778 TwoToFractionalPartOfX
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t12
,
4779 getF32Constant(DAG
, 0x3f800000, dl
));
4782 // Add the exponent into the result in integer domain.
4783 SDValue t13
= DAG
.getNode(ISD::BITCAST
, dl
, MVT::i32
, TwoToFractionalPartOfX
);
4784 return DAG
.getNode(ISD::BITCAST
, dl
, MVT::f32
,
4785 DAG
.getNode(ISD::ADD
, dl
, MVT::i32
, t13
, IntegerPartOfX
));
4788 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4789 /// limited-precision mode.
4790 static SDValue
expandExp(const SDLoc
&dl
, SDValue Op
, SelectionDAG
&DAG
,
4791 const TargetLowering
&TLI
) {
4792 if (Op
.getValueType() == MVT::f32
&&
4793 LimitFloatPrecision
> 0 && LimitFloatPrecision
<= 18) {
4795 // Put the exponent in the right bit position for later addition to the
4798 // #define LOG2OFe 1.4426950f
4799 // t0 = Op * LOG2OFe
4801 // TODO: What fast-math-flags should be set here?
4802 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, Op
,
4803 getF32Constant(DAG
, 0x3fb8aa3b, dl
));
4804 return getLimitedPrecisionExp2(t0
, dl
, DAG
);
4807 // No special expansion.
4808 return DAG
.getNode(ISD::FEXP
, dl
, Op
.getValueType(), Op
);
4811 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4812 /// limited-precision mode.
4813 static SDValue
expandLog(const SDLoc
&dl
, SDValue Op
, SelectionDAG
&DAG
,
4814 const TargetLowering
&TLI
) {
4815 // TODO: What fast-math-flags should be set on the floating-point nodes?
4817 if (Op
.getValueType() == MVT::f32
&&
4818 LimitFloatPrecision
> 0 && LimitFloatPrecision
<= 18) {
4819 SDValue Op1
= DAG
.getNode(ISD::BITCAST
, dl
, MVT::i32
, Op
);
4821 // Scale the exponent by log(2) [0.69314718f].
4822 SDValue Exp
= GetExponent(DAG
, Op1
, TLI
, dl
);
4823 SDValue LogOfExponent
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, Exp
,
4824 getF32Constant(DAG
, 0x3f317218, dl
));
4826 // Get the significand and build it into a floating-point number with
4828 SDValue X
= GetSignificand(DAG
, Op1
, dl
);
4830 SDValue LogOfMantissa
;
4831 if (LimitFloatPrecision
<= 6) {
4832 // For floating-point precision of 6:
4836 // (1.4034025f - 0.23903021f * x) * x;
4838 // error 0.0034276066, which is better than 8 bits
4839 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4840 getF32Constant(DAG
, 0xbe74c456, dl
));
4841 SDValue t1
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t0
,
4842 getF32Constant(DAG
, 0x3fb3a2b1, dl
));
4843 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
4844 LogOfMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t2
,
4845 getF32Constant(DAG
, 0x3f949a29, dl
));
4846 } else if (LimitFloatPrecision
<= 12) {
4847 // For floating-point precision of 12:
4853 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4855 // error 0.000061011436, which is 14 bits
4856 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4857 getF32Constant(DAG
, 0xbd67b6d6, dl
));
4858 SDValue t1
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t0
,
4859 getF32Constant(DAG
, 0x3ee4f4b8, dl
));
4860 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
4861 SDValue t3
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t2
,
4862 getF32Constant(DAG
, 0x3fbc278b, dl
));
4863 SDValue t4
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t3
, X
);
4864 SDValue t5
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t4
,
4865 getF32Constant(DAG
, 0x40348e95, dl
));
4866 SDValue t6
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t5
, X
);
4867 LogOfMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t6
,
4868 getF32Constant(DAG
, 0x3fdef31a, dl
));
4869 } else { // LimitFloatPrecision <= 18
4870 // For floating-point precision of 18:
4878 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4880 // error 0.0000023660568, which is better than 18 bits
4881 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4882 getF32Constant(DAG
, 0xbc91e5ac, dl
));
4883 SDValue t1
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t0
,
4884 getF32Constant(DAG
, 0x3e4350aa, dl
));
4885 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
4886 SDValue t3
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t2
,
4887 getF32Constant(DAG
, 0x3f60d3e3, 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
, 0x4011cdf0, dl
));
4891 SDValue t6
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t5
, X
);
4892 SDValue t7
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t6
,
4893 getF32Constant(DAG
, 0x406cfd1c, 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
, 0x408797cb, dl
));
4897 SDValue t10
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t9
, X
);
4898 LogOfMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t10
,
4899 getF32Constant(DAG
, 0x4006dcab, dl
));
4902 return DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, LogOfExponent
, LogOfMantissa
);
4905 // No special expansion.
4906 return DAG
.getNode(ISD::FLOG
, dl
, Op
.getValueType(), Op
);
4909 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4910 /// limited-precision mode.
4911 static SDValue
expandLog2(const SDLoc
&dl
, SDValue Op
, SelectionDAG
&DAG
,
4912 const TargetLowering
&TLI
) {
4913 // TODO: What fast-math-flags should be set on the floating-point nodes?
4915 if (Op
.getValueType() == MVT::f32
&&
4916 LimitFloatPrecision
> 0 && LimitFloatPrecision
<= 18) {
4917 SDValue Op1
= DAG
.getNode(ISD::BITCAST
, dl
, MVT::i32
, Op
);
4919 // Get the exponent.
4920 SDValue LogOfExponent
= GetExponent(DAG
, Op1
, TLI
, dl
);
4922 // Get the significand and build it into a floating-point number with
4924 SDValue X
= GetSignificand(DAG
, Op1
, dl
);
4926 // Different possible minimax approximations of significand in
4927 // floating-point for various degrees of accuracy over [1,2].
4928 SDValue Log2ofMantissa
;
4929 if (LimitFloatPrecision
<= 6) {
4930 // For floating-point precision of 6:
4932 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4934 // error 0.0049451742, which is more than 7 bits
4935 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4936 getF32Constant(DAG
, 0xbeb08fe0, dl
));
4937 SDValue t1
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t0
,
4938 getF32Constant(DAG
, 0x40019463, dl
));
4939 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
4940 Log2ofMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t2
,
4941 getF32Constant(DAG
, 0x3fd6633d, dl
));
4942 } else if (LimitFloatPrecision
<= 12) {
4943 // For floating-point precision of 12:
4949 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4951 // error 0.0000876136000, which is better than 13 bits
4952 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4953 getF32Constant(DAG
, 0xbda7262e, dl
));
4954 SDValue t1
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t0
,
4955 getF32Constant(DAG
, 0x3f25280b, dl
));
4956 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
4957 SDValue t3
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t2
,
4958 getF32Constant(DAG
, 0x4007b923, dl
));
4959 SDValue t4
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t3
, X
);
4960 SDValue t5
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t4
,
4961 getF32Constant(DAG
, 0x40823e2f, dl
));
4962 SDValue t6
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t5
, X
);
4963 Log2ofMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t6
,
4964 getF32Constant(DAG
, 0x4020d29c, dl
));
4965 } else { // LimitFloatPrecision <= 18
4966 // For floating-point precision of 18:
4975 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4977 // error 0.0000018516, which is better than 18 bits
4978 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
4979 getF32Constant(DAG
, 0xbcd2769e, dl
));
4980 SDValue t1
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t0
,
4981 getF32Constant(DAG
, 0x3e8ce0b9, dl
));
4982 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
4983 SDValue t3
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t2
,
4984 getF32Constant(DAG
, 0x3fa22ae7, dl
));
4985 SDValue t4
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t3
, X
);
4986 SDValue t5
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t4
,
4987 getF32Constant(DAG
, 0x40525723, dl
));
4988 SDValue t6
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t5
, X
);
4989 SDValue t7
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t6
,
4990 getF32Constant(DAG
, 0x40aaf200, dl
));
4991 SDValue t8
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t7
, X
);
4992 SDValue t9
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t8
,
4993 getF32Constant(DAG
, 0x40c39dad, dl
));
4994 SDValue t10
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t9
, X
);
4995 Log2ofMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t10
,
4996 getF32Constant(DAG
, 0x4042902c, dl
));
4999 return DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, LogOfExponent
, Log2ofMantissa
);
5002 // No special expansion.
5003 return DAG
.getNode(ISD::FLOG2
, dl
, Op
.getValueType(), Op
);
5006 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5007 /// limited-precision mode.
5008 static SDValue
expandLog10(const SDLoc
&dl
, SDValue Op
, SelectionDAG
&DAG
,
5009 const TargetLowering
&TLI
) {
5010 // TODO: What fast-math-flags should be set on the floating-point nodes?
5012 if (Op
.getValueType() == MVT::f32
&&
5013 LimitFloatPrecision
> 0 && LimitFloatPrecision
<= 18) {
5014 SDValue Op1
= DAG
.getNode(ISD::BITCAST
, dl
, MVT::i32
, Op
);
5016 // Scale the exponent by log10(2) [0.30102999f].
5017 SDValue Exp
= GetExponent(DAG
, Op1
, TLI
, dl
);
5018 SDValue LogOfExponent
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, Exp
,
5019 getF32Constant(DAG
, 0x3e9a209a, dl
));
5021 // Get the significand and build it into a floating-point number with
5023 SDValue X
= GetSignificand(DAG
, Op1
, dl
);
5025 SDValue Log10ofMantissa
;
5026 if (LimitFloatPrecision
<= 6) {
5027 // For floating-point precision of 6:
5029 // Log10ofMantissa =
5031 // (0.60948995f - 0.10380950f * x) * x;
5033 // error 0.0014886165, which is 6 bits
5034 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
5035 getF32Constant(DAG
, 0xbdd49a13, dl
));
5036 SDValue t1
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t0
,
5037 getF32Constant(DAG
, 0x3f1c0789, dl
));
5038 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
5039 Log10ofMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t2
,
5040 getF32Constant(DAG
, 0x3f011300, dl
));
5041 } else if (LimitFloatPrecision
<= 12) {
5042 // For floating-point precision of 12:
5044 // Log10ofMantissa =
5047 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5049 // error 0.00019228036, which is better than 12 bits
5050 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
5051 getF32Constant(DAG
, 0x3d431f31, dl
));
5052 SDValue t1
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t0
,
5053 getF32Constant(DAG
, 0x3ea21fb2, dl
));
5054 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
5055 SDValue t3
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t2
,
5056 getF32Constant(DAG
, 0x3f6ae232, dl
));
5057 SDValue t4
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t3
, X
);
5058 Log10ofMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t4
,
5059 getF32Constant(DAG
, 0x3f25f7c3, dl
));
5060 } else { // LimitFloatPrecision <= 18
5061 // For floating-point precision of 18:
5063 // Log10ofMantissa =
5068 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5070 // error 0.0000037995730, which is better than 18 bits
5071 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, X
,
5072 getF32Constant(DAG
, 0x3c5d51ce, dl
));
5073 SDValue t1
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t0
,
5074 getF32Constant(DAG
, 0x3e00685a, dl
));
5075 SDValue t2
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t1
, X
);
5076 SDValue t3
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t2
,
5077 getF32Constant(DAG
, 0x3efb6798, dl
));
5078 SDValue t4
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t3
, X
);
5079 SDValue t5
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t4
,
5080 getF32Constant(DAG
, 0x3f88d192, dl
));
5081 SDValue t6
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t5
, X
);
5082 SDValue t7
= DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, t6
,
5083 getF32Constant(DAG
, 0x3fc4316c, dl
));
5084 SDValue t8
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, t7
, X
);
5085 Log10ofMantissa
= DAG
.getNode(ISD::FSUB
, dl
, MVT::f32
, t8
,
5086 getF32Constant(DAG
, 0x3f57ce70, dl
));
5089 return DAG
.getNode(ISD::FADD
, dl
, MVT::f32
, LogOfExponent
, Log10ofMantissa
);
5092 // No special expansion.
5093 return DAG
.getNode(ISD::FLOG10
, dl
, Op
.getValueType(), Op
);
5096 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5097 /// limited-precision mode.
5098 static SDValue
expandExp2(const SDLoc
&dl
, SDValue Op
, SelectionDAG
&DAG
,
5099 const TargetLowering
&TLI
) {
5100 if (Op
.getValueType() == MVT::f32
&&
5101 LimitFloatPrecision
> 0 && LimitFloatPrecision
<= 18)
5102 return getLimitedPrecisionExp2(Op
, dl
, DAG
);
5104 // No special expansion.
5105 return DAG
.getNode(ISD::FEXP2
, dl
, Op
.getValueType(), Op
);
5108 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5109 /// limited-precision mode with x == 10.0f.
5110 static SDValue
expandPow(const SDLoc
&dl
, SDValue LHS
, SDValue RHS
,
5111 SelectionDAG
&DAG
, const TargetLowering
&TLI
) {
5112 bool IsExp10
= false;
5113 if (LHS
.getValueType() == MVT::f32
&& RHS
.getValueType() == MVT::f32
&&
5114 LimitFloatPrecision
> 0 && LimitFloatPrecision
<= 18) {
5115 if (ConstantFPSDNode
*LHSC
= dyn_cast
<ConstantFPSDNode
>(LHS
)) {
5117 IsExp10
= LHSC
->isExactlyValue(Ten
);
5121 // TODO: What fast-math-flags should be set on the FMUL node?
5123 // Put the exponent in the right bit position for later addition to the
5126 // #define LOG2OF10 3.3219281f
5127 // t0 = Op * LOG2OF10;
5128 SDValue t0
= DAG
.getNode(ISD::FMUL
, dl
, MVT::f32
, RHS
,
5129 getF32Constant(DAG
, 0x40549a78, dl
));
5130 return getLimitedPrecisionExp2(t0
, dl
, DAG
);
5133 // No special expansion.
5134 return DAG
.getNode(ISD::FPOW
, dl
, LHS
.getValueType(), LHS
, RHS
);
5137 /// ExpandPowI - Expand a llvm.powi intrinsic.
5138 static SDValue
ExpandPowI(const SDLoc
&DL
, SDValue LHS
, SDValue RHS
,
5139 SelectionDAG
&DAG
) {
5140 // If RHS is a constant, we can expand this out to a multiplication tree,
5141 // otherwise we end up lowering to a call to __powidf2 (for example). When
5142 // optimizing for size, we only want to do this if the expansion would produce
5143 // a small number of multiplies, otherwise we do the full expansion.
5144 if (ConstantSDNode
*RHSC
= dyn_cast
<ConstantSDNode
>(RHS
)) {
5145 // Get the exponent as a positive value.
5146 unsigned Val
= RHSC
->getSExtValue();
5147 if ((int)Val
< 0) Val
= -Val
;
5149 // powi(x, 0) -> 1.0
5151 return DAG
.getConstantFP(1.0, DL
, LHS
.getValueType());
5153 const Function
&F
= DAG
.getMachineFunction().getFunction();
5154 if (!F
.optForSize() ||
5155 // If optimizing for size, don't insert too many multiplies.
5156 // This inserts up to 5 multiplies.
5157 countPopulation(Val
) + Log2_32(Val
) < 7) {
5158 // We use the simple binary decomposition method to generate the multiply
5159 // sequence. There are more optimal ways to do this (for example,
5160 // powi(x,15) generates one more multiply than it should), but this has
5161 // the benefit of being both really simple and much better than a libcall.
5162 SDValue Res
; // Logically starts equal to 1.0
5163 SDValue CurSquare
= LHS
;
5164 // TODO: Intrinsics should have fast-math-flags that propagate to these
5169 Res
= DAG
.getNode(ISD::FMUL
, DL
,Res
.getValueType(), Res
, CurSquare
);
5171 Res
= CurSquare
; // 1.0*CurSquare.
5174 CurSquare
= DAG
.getNode(ISD::FMUL
, DL
, CurSquare
.getValueType(),
5175 CurSquare
, CurSquare
);
5179 // If the original was negative, invert the result, producing 1/(x*x*x).
5180 if (RHSC
->getSExtValue() < 0)
5181 Res
= DAG
.getNode(ISD::FDIV
, DL
, LHS
.getValueType(),
5182 DAG
.getConstantFP(1.0, DL
, LHS
.getValueType()), Res
);
5187 // Otherwise, expand to a libcall.
5188 return DAG
.getNode(ISD::FPOWI
, DL
, LHS
.getValueType(), LHS
, RHS
);
5191 // getUnderlyingArgReg - Find underlying register used for a truncated or
5192 // bitcasted argument.
5193 static unsigned getUnderlyingArgReg(const SDValue
&N
) {
5194 switch (N
.getOpcode()) {
5195 case ISD::CopyFromReg
:
5196 return cast
<RegisterSDNode
>(N
.getOperand(1))->getReg();
5198 case ISD::AssertZext
:
5199 case ISD::AssertSext
:
5201 return getUnderlyingArgReg(N
.getOperand(0));
5207 /// If the DbgValueInst is a dbg_value of a function argument, create the
5208 /// corresponding DBG_VALUE machine instruction for it now. At the end of
5209 /// instruction selection, they will be inserted to the entry BB.
5210 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5211 const Value
*V
, DILocalVariable
*Variable
, DIExpression
*Expr
,
5212 DILocation
*DL
, bool IsDbgDeclare
, const SDValue
&N
) {
5213 const Argument
*Arg
= dyn_cast
<Argument
>(V
);
5217 if (!IsDbgDeclare
) {
5218 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5219 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5221 bool IsInEntryBlock
= FuncInfo
.MBB
== &FuncInfo
.MF
->front();
5222 if (!IsInEntryBlock
)
5225 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5226 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5227 // variable that also is a param.
5229 // Although, if we are at the top of the entry block already, we can still
5230 // emit using ArgDbgValue. This might catch some situations when the
5231 // dbg.value refers to an argument that isn't used in the entry block, so
5232 // any CopyToReg node would be optimized out and the only way to express
5233 // this DBG_VALUE is by using the physical reg (or FI) as done in this
5234 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
5235 // we should only emit as ArgDbgValue if the Variable is an argument to the
5236 // current function, and the dbg.value intrinsic is found in the entry
5238 bool VariableIsFunctionInputArg
= Variable
->isParameter() &&
5239 !DL
->getInlinedAt();
5240 bool IsInPrologue
= SDNodeOrder
== LowestSDNodeOrder
;
5241 if (!IsInPrologue
&& !VariableIsFunctionInputArg
)
5244 // Here we assume that a function argument on IR level only can be used to
5245 // describe one input parameter on source level. If we for example have
5246 // source code like this
5248 // struct A { long x, y; };
5249 // void foo(struct A a, long b) {
5257 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
5259 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5260 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5261 // call void @llvm.dbg.value(metadata i32 %b, "b",
5263 // call void @llvm.dbg.value(metadata i32 %a1, "b"
5266 // then the last dbg.value is describing a parameter "b" using a value that
5267 // is an argument. But since we already has used %a1 to describe a parameter
5268 // we should not handle that last dbg.value here (that would result in an
5269 // incorrect hoisting of the DBG_VALUE to the function entry).
5270 // Notice that we allow one dbg.value per IR level argument, to accomodate
5271 // for the situation with fragments above.
5272 if (VariableIsFunctionInputArg
) {
5273 unsigned ArgNo
= Arg
->getArgNo();
5274 if (ArgNo
>= FuncInfo
.DescribedArgs
.size())
5275 FuncInfo
.DescribedArgs
.resize(ArgNo
+ 1, false);
5276 else if (!IsInPrologue
&& FuncInfo
.DescribedArgs
.test(ArgNo
))
5278 FuncInfo
.DescribedArgs
.set(ArgNo
);
5282 MachineFunction
&MF
= DAG
.getMachineFunction();
5283 const TargetInstrInfo
*TII
= DAG
.getSubtarget().getInstrInfo();
5285 bool IsIndirect
= false;
5286 Optional
<MachineOperand
> Op
;
5287 // Some arguments' frame index is recorded during argument lowering.
5288 int FI
= FuncInfo
.getArgumentFrameIndex(Arg
);
5289 if (FI
!= std::numeric_limits
<int>::max())
5290 Op
= MachineOperand::CreateFI(FI
);
5292 if (!Op
&& N
.getNode()) {
5293 unsigned Reg
= getUnderlyingArgReg(N
);
5294 if (Reg
&& TargetRegisterInfo::isVirtualRegister(Reg
)) {
5295 MachineRegisterInfo
&RegInfo
= MF
.getRegInfo();
5296 unsigned PR
= RegInfo
.getLiveInPhysReg(Reg
);
5301 Op
= MachineOperand::CreateReg(Reg
, false);
5302 IsIndirect
= IsDbgDeclare
;
5306 if (!Op
&& N
.getNode())
5307 // Check if frame index is available.
5308 if (LoadSDNode
*LNode
= dyn_cast
<LoadSDNode
>(N
.getNode()))
5309 if (FrameIndexSDNode
*FINode
=
5310 dyn_cast
<FrameIndexSDNode
>(LNode
->getBasePtr().getNode()))
5311 Op
= MachineOperand::CreateFI(FINode
->getIndex());
5314 // Check if ValueMap has reg number.
5315 DenseMap
<const Value
*, unsigned>::iterator VMI
= FuncInfo
.ValueMap
.find(V
);
5316 if (VMI
!= FuncInfo
.ValueMap
.end()) {
5317 const auto &TLI
= DAG
.getTargetLoweringInfo();
5318 RegsForValue
RFV(V
->getContext(), TLI
, DAG
.getDataLayout(), VMI
->second
,
5319 V
->getType(), getABIRegCopyCC(V
));
5320 if (RFV
.occupiesMultipleRegs()) {
5321 unsigned Offset
= 0;
5322 for (auto RegAndSize
: RFV
.getRegsAndSizes()) {
5323 Op
= MachineOperand::CreateReg(RegAndSize
.first
, false);
5324 auto FragmentExpr
= DIExpression::createFragmentExpression(
5325 Expr
, Offset
, RegAndSize
.second
);
5328 FuncInfo
.ArgDbgValues
.push_back(
5329 BuildMI(MF
, DL
, TII
->get(TargetOpcode::DBG_VALUE
), IsDbgDeclare
,
5330 Op
->getReg(), Variable
, *FragmentExpr
));
5331 Offset
+= RegAndSize
.second
;
5335 Op
= MachineOperand::CreateReg(VMI
->second
, false);
5336 IsIndirect
= IsDbgDeclare
;
5343 assert(Variable
->isValidLocationForIntrinsic(DL
) &&
5344 "Expected inlined-at fields to agree");
5345 IsIndirect
= (Op
->isReg()) ? IsIndirect
: true;
5346 FuncInfo
.ArgDbgValues
.push_back(
5347 BuildMI(MF
, DL
, TII
->get(TargetOpcode::DBG_VALUE
), IsIndirect
,
5348 *Op
, Variable
, Expr
));
5353 /// Return the appropriate SDDbgValue based on N.
5354 SDDbgValue
*SelectionDAGBuilder::getDbgValue(SDValue N
,
5355 DILocalVariable
*Variable
,
5358 unsigned DbgSDNodeOrder
) {
5359 if (auto *FISDN
= dyn_cast
<FrameIndexSDNode
>(N
.getNode())) {
5360 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5361 // stack slot locations.
5363 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5364 // debug values here after optimization:
5366 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
5367 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5369 // Both describe the direct values of their associated variables.
5370 return DAG
.getFrameIndexDbgValue(Variable
, Expr
, FISDN
->getIndex(),
5371 /*IsIndirect*/ false, dl
, DbgSDNodeOrder
);
5373 return DAG
.getDbgValue(Variable
, Expr
, N
.getNode(), N
.getResNo(),
5374 /*IsIndirect*/ false, dl
, DbgSDNodeOrder
);
5377 // VisualStudio defines setjmp as _setjmp
5378 #if defined(_MSC_VER) && defined(setjmp) && \
5379 !defined(setjmp_undefined_for_msvc)
5380 # pragma push_macro("setjmp")
5382 # define setjmp_undefined_for_msvc
5385 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic
) {
5386 switch (Intrinsic
) {
5387 case Intrinsic::smul_fix
:
5388 return ISD::SMULFIX
;
5389 case Intrinsic::umul_fix
:
5390 return ISD::UMULFIX
;
5392 llvm_unreachable("Unhandled fixed point intrinsic");
5396 /// Lower the call to the specified intrinsic function. If we want to emit this
5397 /// as a call to a named external function, return the name. Otherwise, lower it
5398 /// and return null.
5400 SelectionDAGBuilder::visitIntrinsicCall(const CallInst
&I
, unsigned Intrinsic
) {
5401 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
5402 SDLoc sdl
= getCurSDLoc();
5403 DebugLoc dl
= getCurDebugLoc();
5406 switch (Intrinsic
) {
5408 // By default, turn this into a target intrinsic node.
5409 visitTargetIntrinsic(I
, Intrinsic
);
5411 case Intrinsic::vastart
: visitVAStart(I
); return nullptr;
5412 case Intrinsic::vaend
: visitVAEnd(I
); return nullptr;
5413 case Intrinsic::vacopy
: visitVACopy(I
); return nullptr;
5414 case Intrinsic::returnaddress
:
5415 setValue(&I
, DAG
.getNode(ISD::RETURNADDR
, sdl
,
5416 TLI
.getPointerTy(DAG
.getDataLayout()),
5417 getValue(I
.getArgOperand(0))));
5419 case Intrinsic::addressofreturnaddress
:
5420 setValue(&I
, DAG
.getNode(ISD::ADDROFRETURNADDR
, sdl
,
5421 TLI
.getPointerTy(DAG
.getDataLayout())));
5423 case Intrinsic::sponentry
:
5424 setValue(&I
, DAG
.getNode(ISD::SPONENTRY
, sdl
,
5425 TLI
.getPointerTy(DAG
.getDataLayout())));
5427 case Intrinsic::frameaddress
:
5428 setValue(&I
, DAG
.getNode(ISD::FRAMEADDR
, sdl
,
5429 TLI
.getPointerTy(DAG
.getDataLayout()),
5430 getValue(I
.getArgOperand(0))));
5432 case Intrinsic::read_register
: {
5433 Value
*Reg
= I
.getArgOperand(0);
5434 SDValue Chain
= getRoot();
5436 DAG
.getMDNode(cast
<MDNode
>(cast
<MetadataAsValue
>(Reg
)->getMetadata()));
5437 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
5438 Res
= DAG
.getNode(ISD::READ_REGISTER
, sdl
,
5439 DAG
.getVTList(VT
, MVT::Other
), Chain
, RegName
);
5441 DAG
.setRoot(Res
.getValue(1));
5444 case Intrinsic::write_register
: {
5445 Value
*Reg
= I
.getArgOperand(0);
5446 Value
*RegValue
= I
.getArgOperand(1);
5447 SDValue Chain
= getRoot();
5449 DAG
.getMDNode(cast
<MDNode
>(cast
<MetadataAsValue
>(Reg
)->getMetadata()));
5450 DAG
.setRoot(DAG
.getNode(ISD::WRITE_REGISTER
, sdl
, MVT::Other
, Chain
,
5451 RegName
, getValue(RegValue
)));
5454 case Intrinsic::setjmp
:
5455 return &"_setjmp"[!TLI
.usesUnderscoreSetJmp()];
5456 case Intrinsic::longjmp
:
5457 return &"_longjmp"[!TLI
.usesUnderscoreLongJmp()];
5458 case Intrinsic::memcpy
: {
5459 const auto &MCI
= cast
<MemCpyInst
>(I
);
5460 SDValue Op1
= getValue(I
.getArgOperand(0));
5461 SDValue Op2
= getValue(I
.getArgOperand(1));
5462 SDValue Op3
= getValue(I
.getArgOperand(2));
5463 // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5464 unsigned DstAlign
= std::max
<unsigned>(MCI
.getDestAlignment(), 1);
5465 unsigned SrcAlign
= std::max
<unsigned>(MCI
.getSourceAlignment(), 1);
5466 unsigned Align
= MinAlign(DstAlign
, SrcAlign
);
5467 bool isVol
= MCI
.isVolatile();
5468 bool isTC
= I
.isTailCall() && isInTailCallPosition(&I
, DAG
.getTarget());
5469 // FIXME: Support passing different dest/src alignments to the memcpy DAG
5471 SDValue MC
= DAG
.getMemcpy(getRoot(), sdl
, Op1
, Op2
, Op3
, Align
, isVol
,
5473 MachinePointerInfo(I
.getArgOperand(0)),
5474 MachinePointerInfo(I
.getArgOperand(1)));
5475 updateDAGForMaybeTailCall(MC
);
5478 case Intrinsic::memset
: {
5479 const auto &MSI
= cast
<MemSetInst
>(I
);
5480 SDValue Op1
= getValue(I
.getArgOperand(0));
5481 SDValue Op2
= getValue(I
.getArgOperand(1));
5482 SDValue Op3
= getValue(I
.getArgOperand(2));
5483 // @llvm.memset defines 0 and 1 to both mean no alignment.
5484 unsigned Align
= std::max
<unsigned>(MSI
.getDestAlignment(), 1);
5485 bool isVol
= MSI
.isVolatile();
5486 bool isTC
= I
.isTailCall() && isInTailCallPosition(&I
, DAG
.getTarget());
5487 SDValue MS
= DAG
.getMemset(getRoot(), sdl
, Op1
, Op2
, Op3
, Align
, isVol
,
5488 isTC
, MachinePointerInfo(I
.getArgOperand(0)));
5489 updateDAGForMaybeTailCall(MS
);
5492 case Intrinsic::memmove
: {
5493 const auto &MMI
= cast
<MemMoveInst
>(I
);
5494 SDValue Op1
= getValue(I
.getArgOperand(0));
5495 SDValue Op2
= getValue(I
.getArgOperand(1));
5496 SDValue Op3
= getValue(I
.getArgOperand(2));
5497 // @llvm.memmove defines 0 and 1 to both mean no alignment.
5498 unsigned DstAlign
= std::max
<unsigned>(MMI
.getDestAlignment(), 1);
5499 unsigned SrcAlign
= std::max
<unsigned>(MMI
.getSourceAlignment(), 1);
5500 unsigned Align
= MinAlign(DstAlign
, SrcAlign
);
5501 bool isVol
= MMI
.isVolatile();
5502 bool isTC
= I
.isTailCall() && isInTailCallPosition(&I
, DAG
.getTarget());
5503 // FIXME: Support passing different dest/src alignments to the memmove DAG
5505 SDValue MM
= DAG
.getMemmove(getRoot(), sdl
, Op1
, Op2
, Op3
, Align
, isVol
,
5506 isTC
, MachinePointerInfo(I
.getArgOperand(0)),
5507 MachinePointerInfo(I
.getArgOperand(1)));
5508 updateDAGForMaybeTailCall(MM
);
5511 case Intrinsic::memcpy_element_unordered_atomic
: {
5512 const AtomicMemCpyInst
&MI
= cast
<AtomicMemCpyInst
>(I
);
5513 SDValue Dst
= getValue(MI
.getRawDest());
5514 SDValue Src
= getValue(MI
.getRawSource());
5515 SDValue Length
= getValue(MI
.getLength());
5517 unsigned DstAlign
= MI
.getDestAlignment();
5518 unsigned SrcAlign
= MI
.getSourceAlignment();
5519 Type
*LengthTy
= MI
.getLength()->getType();
5520 unsigned ElemSz
= MI
.getElementSizeInBytes();
5521 bool isTC
= I
.isTailCall() && isInTailCallPosition(&I
, DAG
.getTarget());
5522 SDValue MC
= DAG
.getAtomicMemcpy(getRoot(), sdl
, Dst
, DstAlign
, Src
,
5523 SrcAlign
, Length
, LengthTy
, ElemSz
, isTC
,
5524 MachinePointerInfo(MI
.getRawDest()),
5525 MachinePointerInfo(MI
.getRawSource()));
5526 updateDAGForMaybeTailCall(MC
);
5529 case Intrinsic::memmove_element_unordered_atomic
: {
5530 auto &MI
= cast
<AtomicMemMoveInst
>(I
);
5531 SDValue Dst
= getValue(MI
.getRawDest());
5532 SDValue Src
= getValue(MI
.getRawSource());
5533 SDValue Length
= getValue(MI
.getLength());
5535 unsigned DstAlign
= MI
.getDestAlignment();
5536 unsigned SrcAlign
= MI
.getSourceAlignment();
5537 Type
*LengthTy
= MI
.getLength()->getType();
5538 unsigned ElemSz
= MI
.getElementSizeInBytes();
5539 bool isTC
= I
.isTailCall() && isInTailCallPosition(&I
, DAG
.getTarget());
5540 SDValue MC
= DAG
.getAtomicMemmove(getRoot(), sdl
, Dst
, DstAlign
, Src
,
5541 SrcAlign
, Length
, LengthTy
, ElemSz
, isTC
,
5542 MachinePointerInfo(MI
.getRawDest()),
5543 MachinePointerInfo(MI
.getRawSource()));
5544 updateDAGForMaybeTailCall(MC
);
5547 case Intrinsic::memset_element_unordered_atomic
: {
5548 auto &MI
= cast
<AtomicMemSetInst
>(I
);
5549 SDValue Dst
= getValue(MI
.getRawDest());
5550 SDValue Val
= getValue(MI
.getValue());
5551 SDValue Length
= getValue(MI
.getLength());
5553 unsigned DstAlign
= MI
.getDestAlignment();
5554 Type
*LengthTy
= MI
.getLength()->getType();
5555 unsigned ElemSz
= MI
.getElementSizeInBytes();
5556 bool isTC
= I
.isTailCall() && isInTailCallPosition(&I
, DAG
.getTarget());
5557 SDValue MC
= DAG
.getAtomicMemset(getRoot(), sdl
, Dst
, DstAlign
, Val
, Length
,
5558 LengthTy
, ElemSz
, isTC
,
5559 MachinePointerInfo(MI
.getRawDest()));
5560 updateDAGForMaybeTailCall(MC
);
5563 case Intrinsic::dbg_addr
:
5564 case Intrinsic::dbg_declare
: {
5565 const auto &DI
= cast
<DbgVariableIntrinsic
>(I
);
5566 DILocalVariable
*Variable
= DI
.getVariable();
5567 DIExpression
*Expression
= DI
.getExpression();
5568 dropDanglingDebugInfo(Variable
, Expression
);
5569 assert(Variable
&& "Missing variable");
5571 // Check if address has undef value.
5572 const Value
*Address
= DI
.getVariableLocation();
5573 if (!Address
|| isa
<UndefValue
>(Address
) ||
5574 (Address
->use_empty() && !isa
<Argument
>(Address
))) {
5575 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
<< "\n");
5579 bool isParameter
= Variable
->isParameter() || isa
<Argument
>(Address
);
5581 // Check if this variable can be described by a frame index, typically
5582 // either as a static alloca or a byval parameter.
5583 int FI
= std::numeric_limits
<int>::max();
5584 if (const auto *AI
=
5585 dyn_cast
<AllocaInst
>(Address
->stripInBoundsConstantOffsets())) {
5586 if (AI
->isStaticAlloca()) {
5587 auto I
= FuncInfo
.StaticAllocaMap
.find(AI
);
5588 if (I
!= FuncInfo
.StaticAllocaMap
.end())
5591 } else if (const auto *Arg
= dyn_cast
<Argument
>(
5592 Address
->stripInBoundsConstantOffsets())) {
5593 FI
= FuncInfo
.getArgumentFrameIndex(Arg
);
5596 // llvm.dbg.addr is control dependent and always generates indirect
5597 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5598 // the MachineFunction variable table.
5599 if (FI
!= std::numeric_limits
<int>::max()) {
5600 if (Intrinsic
== Intrinsic::dbg_addr
) {
5601 SDDbgValue
*SDV
= DAG
.getFrameIndexDbgValue(
5602 Variable
, Expression
, FI
, /*IsIndirect*/ true, dl
, SDNodeOrder
);
5603 DAG
.AddDbgValue(SDV
, getRoot().getNode(), isParameter
);
5608 SDValue
&N
= NodeMap
[Address
];
5609 if (!N
.getNode() && isa
<Argument
>(Address
))
5610 // Check unused arguments map.
5611 N
= UnusedArgNodeMap
[Address
];
5614 if (const BitCastInst
*BCI
= dyn_cast
<BitCastInst
>(Address
))
5615 Address
= BCI
->getOperand(0);
5616 // Parameters are handled specially.
5617 auto FINode
= dyn_cast
<FrameIndexSDNode
>(N
.getNode());
5618 if (isParameter
&& FINode
) {
5619 // Byval parameter. We have a frame index at this point.
5621 DAG
.getFrameIndexDbgValue(Variable
, Expression
, FINode
->getIndex(),
5622 /*IsIndirect*/ true, dl
, SDNodeOrder
);
5623 } else if (isa
<Argument
>(Address
)) {
5624 // Address is an argument, so try to emit its dbg value using
5625 // virtual register info from the FuncInfo.ValueMap.
5626 EmitFuncArgumentDbgValue(Address
, Variable
, Expression
, dl
, true, N
);
5629 SDV
= DAG
.getDbgValue(Variable
, Expression
, N
.getNode(), N
.getResNo(),
5630 true, dl
, SDNodeOrder
);
5632 DAG
.AddDbgValue(SDV
, N
.getNode(), isParameter
);
5634 // If Address is an argument then try to emit its dbg value using
5635 // virtual register info from the FuncInfo.ValueMap.
5636 if (!EmitFuncArgumentDbgValue(Address
, Variable
, Expression
, dl
, true,
5638 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
<< "\n");
5643 case Intrinsic::dbg_label
: {
5644 const DbgLabelInst
&DI
= cast
<DbgLabelInst
>(I
);
5645 DILabel
*Label
= DI
.getLabel();
5646 assert(Label
&& "Missing label");
5649 SDV
= DAG
.getDbgLabel(Label
, dl
, SDNodeOrder
);
5650 DAG
.AddDbgLabel(SDV
);
5653 case Intrinsic::dbg_value
: {
5654 const DbgValueInst
&DI
= cast
<DbgValueInst
>(I
);
5655 assert(DI
.getVariable() && "Missing variable");
5657 DILocalVariable
*Variable
= DI
.getVariable();
5658 DIExpression
*Expression
= DI
.getExpression();
5659 dropDanglingDebugInfo(Variable
, Expression
);
5660 const Value
*V
= DI
.getValue();
5664 if (handleDebugValue(V
, Variable
, Expression
, dl
, DI
.getDebugLoc(),
5668 // TODO: Dangling debug info will eventually either be resolved or produce
5669 // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5670 // between the original dbg.value location and its resolved DBG_VALUE, which
5671 // we should ideally fill with an extra Undef DBG_VALUE.
5673 DanglingDebugInfoMap
[V
].emplace_back(&DI
, dl
, SDNodeOrder
);
5677 case Intrinsic::eh_typeid_for
: {
5678 // Find the type id for the given typeinfo.
5679 GlobalValue
*GV
= ExtractTypeInfo(I
.getArgOperand(0));
5680 unsigned TypeID
= DAG
.getMachineFunction().getTypeIDFor(GV
);
5681 Res
= DAG
.getConstant(TypeID
, sdl
, MVT::i32
);
5686 case Intrinsic::eh_return_i32
:
5687 case Intrinsic::eh_return_i64
:
5688 DAG
.getMachineFunction().setCallsEHReturn(true);
5689 DAG
.setRoot(DAG
.getNode(ISD::EH_RETURN
, sdl
,
5692 getValue(I
.getArgOperand(0)),
5693 getValue(I
.getArgOperand(1))));
5695 case Intrinsic::eh_unwind_init
:
5696 DAG
.getMachineFunction().setCallsUnwindInit(true);
5698 case Intrinsic::eh_dwarf_cfa
:
5699 setValue(&I
, DAG
.getNode(ISD::EH_DWARF_CFA
, sdl
,
5700 TLI
.getPointerTy(DAG
.getDataLayout()),
5701 getValue(I
.getArgOperand(0))));
5703 case Intrinsic::eh_sjlj_callsite
: {
5704 MachineModuleInfo
&MMI
= DAG
.getMachineFunction().getMMI();
5705 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(I
.getArgOperand(0));
5706 assert(CI
&& "Non-constant call site value in eh.sjlj.callsite!");
5707 assert(MMI
.getCurrentCallSite() == 0 && "Overlapping call sites!");
5709 MMI
.setCurrentCallSite(CI
->getZExtValue());
5712 case Intrinsic::eh_sjlj_functioncontext
: {
5713 // Get and store the index of the function context.
5714 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
5716 cast
<AllocaInst
>(I
.getArgOperand(0)->stripPointerCasts());
5717 int FI
= FuncInfo
.StaticAllocaMap
[FnCtx
];
5718 MFI
.setFunctionContextIndex(FI
);
5721 case Intrinsic::eh_sjlj_setjmp
: {
5724 Ops
[1] = getValue(I
.getArgOperand(0));
5725 SDValue Op
= DAG
.getNode(ISD::EH_SJLJ_SETJMP
, sdl
,
5726 DAG
.getVTList(MVT::i32
, MVT::Other
), Ops
);
5727 setValue(&I
, Op
.getValue(0));
5728 DAG
.setRoot(Op
.getValue(1));
5731 case Intrinsic::eh_sjlj_longjmp
:
5732 DAG
.setRoot(DAG
.getNode(ISD::EH_SJLJ_LONGJMP
, sdl
, MVT::Other
,
5733 getRoot(), getValue(I
.getArgOperand(0))));
5735 case Intrinsic::eh_sjlj_setup_dispatch
:
5736 DAG
.setRoot(DAG
.getNode(ISD::EH_SJLJ_SETUP_DISPATCH
, sdl
, MVT::Other
,
5739 case Intrinsic::masked_gather
:
5740 visitMaskedGather(I
);
5742 case Intrinsic::masked_load
:
5745 case Intrinsic::masked_scatter
:
5746 visitMaskedScatter(I
);
5748 case Intrinsic::masked_store
:
5749 visitMaskedStore(I
);
5751 case Intrinsic::masked_expandload
:
5752 visitMaskedLoad(I
, true /* IsExpanding */);
5754 case Intrinsic::masked_compressstore
:
5755 visitMaskedStore(I
, true /* IsCompressing */);
5757 case Intrinsic::x86_mmx_pslli_w
:
5758 case Intrinsic::x86_mmx_pslli_d
:
5759 case Intrinsic::x86_mmx_pslli_q
:
5760 case Intrinsic::x86_mmx_psrli_w
:
5761 case Intrinsic::x86_mmx_psrli_d
:
5762 case Intrinsic::x86_mmx_psrli_q
:
5763 case Intrinsic::x86_mmx_psrai_w
:
5764 case Intrinsic::x86_mmx_psrai_d
: {
5765 SDValue ShAmt
= getValue(I
.getArgOperand(1));
5766 if (isa
<ConstantSDNode
>(ShAmt
)) {
5767 visitTargetIntrinsic(I
, Intrinsic
);
5770 unsigned NewIntrinsic
= 0;
5771 EVT ShAmtVT
= MVT::v2i32
;
5772 switch (Intrinsic
) {
5773 case Intrinsic::x86_mmx_pslli_w
:
5774 NewIntrinsic
= Intrinsic::x86_mmx_psll_w
;
5776 case Intrinsic::x86_mmx_pslli_d
:
5777 NewIntrinsic
= Intrinsic::x86_mmx_psll_d
;
5779 case Intrinsic::x86_mmx_pslli_q
:
5780 NewIntrinsic
= Intrinsic::x86_mmx_psll_q
;
5782 case Intrinsic::x86_mmx_psrli_w
:
5783 NewIntrinsic
= Intrinsic::x86_mmx_psrl_w
;
5785 case Intrinsic::x86_mmx_psrli_d
:
5786 NewIntrinsic
= Intrinsic::x86_mmx_psrl_d
;
5788 case Intrinsic::x86_mmx_psrli_q
:
5789 NewIntrinsic
= Intrinsic::x86_mmx_psrl_q
;
5791 case Intrinsic::x86_mmx_psrai_w
:
5792 NewIntrinsic
= Intrinsic::x86_mmx_psra_w
;
5794 case Intrinsic::x86_mmx_psrai_d
:
5795 NewIntrinsic
= Intrinsic::x86_mmx_psra_d
;
5797 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5800 // The vector shift intrinsics with scalars uses 32b shift amounts but
5801 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5803 // We must do this early because v2i32 is not a legal type.
5806 ShOps
[1] = DAG
.getConstant(0, sdl
, MVT::i32
);
5807 ShAmt
= DAG
.getBuildVector(ShAmtVT
, sdl
, ShOps
);
5808 EVT DestVT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
5809 ShAmt
= DAG
.getNode(ISD::BITCAST
, sdl
, DestVT
, ShAmt
);
5810 Res
= DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, sdl
, DestVT
,
5811 DAG
.getConstant(NewIntrinsic
, sdl
, MVT::i32
),
5812 getValue(I
.getArgOperand(0)), ShAmt
);
5816 case Intrinsic::powi
:
5817 setValue(&I
, ExpandPowI(sdl
, getValue(I
.getArgOperand(0)),
5818 getValue(I
.getArgOperand(1)), DAG
));
5820 case Intrinsic::log
:
5821 setValue(&I
, expandLog(sdl
, getValue(I
.getArgOperand(0)), DAG
, TLI
));
5823 case Intrinsic::log2
:
5824 setValue(&I
, expandLog2(sdl
, getValue(I
.getArgOperand(0)), DAG
, TLI
));
5826 case Intrinsic::log10
:
5827 setValue(&I
, expandLog10(sdl
, getValue(I
.getArgOperand(0)), DAG
, TLI
));
5829 case Intrinsic::exp
:
5830 setValue(&I
, expandExp(sdl
, getValue(I
.getArgOperand(0)), DAG
, TLI
));
5832 case Intrinsic::exp2
:
5833 setValue(&I
, expandExp2(sdl
, getValue(I
.getArgOperand(0)), DAG
, TLI
));
5835 case Intrinsic::pow
:
5836 setValue(&I
, expandPow(sdl
, getValue(I
.getArgOperand(0)),
5837 getValue(I
.getArgOperand(1)), DAG
, TLI
));
5839 case Intrinsic::sqrt
:
5840 case Intrinsic::fabs
:
5841 case Intrinsic::sin
:
5842 case Intrinsic::cos
:
5843 case Intrinsic::floor
:
5844 case Intrinsic::ceil
:
5845 case Intrinsic::trunc
:
5846 case Intrinsic::rint
:
5847 case Intrinsic::nearbyint
:
5848 case Intrinsic::round
:
5849 case Intrinsic::canonicalize
: {
5851 switch (Intrinsic
) {
5852 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5853 case Intrinsic::sqrt
: Opcode
= ISD::FSQRT
; break;
5854 case Intrinsic::fabs
: Opcode
= ISD::FABS
; break;
5855 case Intrinsic::sin
: Opcode
= ISD::FSIN
; break;
5856 case Intrinsic::cos
: Opcode
= ISD::FCOS
; break;
5857 case Intrinsic::floor
: Opcode
= ISD::FFLOOR
; break;
5858 case Intrinsic::ceil
: Opcode
= ISD::FCEIL
; break;
5859 case Intrinsic::trunc
: Opcode
= ISD::FTRUNC
; break;
5860 case Intrinsic::rint
: Opcode
= ISD::FRINT
; break;
5861 case Intrinsic::nearbyint
: Opcode
= ISD::FNEARBYINT
; break;
5862 case Intrinsic::round
: Opcode
= ISD::FROUND
; break;
5863 case Intrinsic::canonicalize
: Opcode
= ISD::FCANONICALIZE
; break;
5866 setValue(&I
, DAG
.getNode(Opcode
, sdl
,
5867 getValue(I
.getArgOperand(0)).getValueType(),
5868 getValue(I
.getArgOperand(0))));
5871 case Intrinsic::minnum
: {
5872 auto VT
= getValue(I
.getArgOperand(0)).getValueType();
5874 I
.hasNoNaNs() && TLI
.isOperationLegalOrCustom(ISD::FMINIMUM
, VT
)
5877 setValue(&I
, DAG
.getNode(Opc
, sdl
, VT
,
5878 getValue(I
.getArgOperand(0)),
5879 getValue(I
.getArgOperand(1))));
5882 case Intrinsic::maxnum
: {
5883 auto VT
= getValue(I
.getArgOperand(0)).getValueType();
5885 I
.hasNoNaNs() && TLI
.isOperationLegalOrCustom(ISD::FMAXIMUM
, VT
)
5888 setValue(&I
, DAG
.getNode(Opc
, sdl
, VT
,
5889 getValue(I
.getArgOperand(0)),
5890 getValue(I
.getArgOperand(1))));
5893 case Intrinsic::minimum
:
5894 setValue(&I
, DAG
.getNode(ISD::FMINIMUM
, sdl
,
5895 getValue(I
.getArgOperand(0)).getValueType(),
5896 getValue(I
.getArgOperand(0)),
5897 getValue(I
.getArgOperand(1))));
5899 case Intrinsic::maximum
:
5900 setValue(&I
, DAG
.getNode(ISD::FMAXIMUM
, sdl
,
5901 getValue(I
.getArgOperand(0)).getValueType(),
5902 getValue(I
.getArgOperand(0)),
5903 getValue(I
.getArgOperand(1))));
5905 case Intrinsic::copysign
:
5906 setValue(&I
, DAG
.getNode(ISD::FCOPYSIGN
, sdl
,
5907 getValue(I
.getArgOperand(0)).getValueType(),
5908 getValue(I
.getArgOperand(0)),
5909 getValue(I
.getArgOperand(1))));
5911 case Intrinsic::fma
:
5912 setValue(&I
, DAG
.getNode(ISD::FMA
, sdl
,
5913 getValue(I
.getArgOperand(0)).getValueType(),
5914 getValue(I
.getArgOperand(0)),
5915 getValue(I
.getArgOperand(1)),
5916 getValue(I
.getArgOperand(2))));
5918 case Intrinsic::experimental_constrained_fadd
:
5919 case Intrinsic::experimental_constrained_fsub
:
5920 case Intrinsic::experimental_constrained_fmul
:
5921 case Intrinsic::experimental_constrained_fdiv
:
5922 case Intrinsic::experimental_constrained_frem
:
5923 case Intrinsic::experimental_constrained_fma
:
5924 case Intrinsic::experimental_constrained_sqrt
:
5925 case Intrinsic::experimental_constrained_pow
:
5926 case Intrinsic::experimental_constrained_powi
:
5927 case Intrinsic::experimental_constrained_sin
:
5928 case Intrinsic::experimental_constrained_cos
:
5929 case Intrinsic::experimental_constrained_exp
:
5930 case Intrinsic::experimental_constrained_exp2
:
5931 case Intrinsic::experimental_constrained_log
:
5932 case Intrinsic::experimental_constrained_log10
:
5933 case Intrinsic::experimental_constrained_log2
:
5934 case Intrinsic::experimental_constrained_rint
:
5935 case Intrinsic::experimental_constrained_nearbyint
:
5936 case Intrinsic::experimental_constrained_maxnum
:
5937 case Intrinsic::experimental_constrained_minnum
:
5938 case Intrinsic::experimental_constrained_ceil
:
5939 case Intrinsic::experimental_constrained_floor
:
5940 case Intrinsic::experimental_constrained_round
:
5941 case Intrinsic::experimental_constrained_trunc
:
5942 visitConstrainedFPIntrinsic(cast
<ConstrainedFPIntrinsic
>(I
));
5944 case Intrinsic::fmuladd
: {
5945 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
5946 if (TM
.Options
.AllowFPOpFusion
!= FPOpFusion::Strict
&&
5947 TLI
.isFMAFasterThanFMulAndFAdd(VT
)) {
5948 setValue(&I
, DAG
.getNode(ISD::FMA
, sdl
,
5949 getValue(I
.getArgOperand(0)).getValueType(),
5950 getValue(I
.getArgOperand(0)),
5951 getValue(I
.getArgOperand(1)),
5952 getValue(I
.getArgOperand(2))));
5954 // TODO: Intrinsic calls should have fast-math-flags.
5955 SDValue Mul
= DAG
.getNode(ISD::FMUL
, sdl
,
5956 getValue(I
.getArgOperand(0)).getValueType(),
5957 getValue(I
.getArgOperand(0)),
5958 getValue(I
.getArgOperand(1)));
5959 SDValue Add
= DAG
.getNode(ISD::FADD
, sdl
,
5960 getValue(I
.getArgOperand(0)).getValueType(),
5962 getValue(I
.getArgOperand(2)));
5967 case Intrinsic::convert_to_fp16
:
5968 setValue(&I
, DAG
.getNode(ISD::BITCAST
, sdl
, MVT::i16
,
5969 DAG
.getNode(ISD::FP_ROUND
, sdl
, MVT::f16
,
5970 getValue(I
.getArgOperand(0)),
5971 DAG
.getTargetConstant(0, sdl
,
5974 case Intrinsic::convert_from_fp16
:
5975 setValue(&I
, DAG
.getNode(ISD::FP_EXTEND
, sdl
,
5976 TLI
.getValueType(DAG
.getDataLayout(), I
.getType()),
5977 DAG
.getNode(ISD::BITCAST
, sdl
, MVT::f16
,
5978 getValue(I
.getArgOperand(0)))));
5980 case Intrinsic::pcmarker
: {
5981 SDValue Tmp
= getValue(I
.getArgOperand(0));
5982 DAG
.setRoot(DAG
.getNode(ISD::PCMARKER
, sdl
, MVT::Other
, getRoot(), Tmp
));
5985 case Intrinsic::readcyclecounter
: {
5986 SDValue Op
= getRoot();
5987 Res
= DAG
.getNode(ISD::READCYCLECOUNTER
, sdl
,
5988 DAG
.getVTList(MVT::i64
, MVT::Other
), Op
);
5990 DAG
.setRoot(Res
.getValue(1));
5993 case Intrinsic::bitreverse
:
5994 setValue(&I
, DAG
.getNode(ISD::BITREVERSE
, sdl
,
5995 getValue(I
.getArgOperand(0)).getValueType(),
5996 getValue(I
.getArgOperand(0))));
5998 case Intrinsic::bswap
:
5999 setValue(&I
, DAG
.getNode(ISD::BSWAP
, sdl
,
6000 getValue(I
.getArgOperand(0)).getValueType(),
6001 getValue(I
.getArgOperand(0))));
6003 case Intrinsic::cttz
: {
6004 SDValue Arg
= getValue(I
.getArgOperand(0));
6005 ConstantInt
*CI
= cast
<ConstantInt
>(I
.getArgOperand(1));
6006 EVT Ty
= Arg
.getValueType();
6007 setValue(&I
, DAG
.getNode(CI
->isZero() ? ISD::CTTZ
: ISD::CTTZ_ZERO_UNDEF
,
6011 case Intrinsic::ctlz
: {
6012 SDValue Arg
= getValue(I
.getArgOperand(0));
6013 ConstantInt
*CI
= cast
<ConstantInt
>(I
.getArgOperand(1));
6014 EVT Ty
= Arg
.getValueType();
6015 setValue(&I
, DAG
.getNode(CI
->isZero() ? ISD::CTLZ
: ISD::CTLZ_ZERO_UNDEF
,
6019 case Intrinsic::ctpop
: {
6020 SDValue Arg
= getValue(I
.getArgOperand(0));
6021 EVT Ty
= Arg
.getValueType();
6022 setValue(&I
, DAG
.getNode(ISD::CTPOP
, sdl
, Ty
, Arg
));
6025 case Intrinsic::fshl
:
6026 case Intrinsic::fshr
: {
6027 bool IsFSHL
= Intrinsic
== Intrinsic::fshl
;
6028 SDValue X
= getValue(I
.getArgOperand(0));
6029 SDValue Y
= getValue(I
.getArgOperand(1));
6030 SDValue Z
= getValue(I
.getArgOperand(2));
6031 EVT VT
= X
.getValueType();
6032 SDValue BitWidthC
= DAG
.getConstant(VT
.getScalarSizeInBits(), sdl
, VT
);
6033 SDValue Zero
= DAG
.getConstant(0, sdl
, VT
);
6034 SDValue ShAmt
= DAG
.getNode(ISD::UREM
, sdl
, VT
, Z
, BitWidthC
);
6036 auto FunnelOpcode
= IsFSHL
? ISD::FSHL
: ISD::FSHR
;
6037 if (TLI
.isOperationLegalOrCustom(FunnelOpcode
, VT
)) {
6038 setValue(&I
, DAG
.getNode(FunnelOpcode
, sdl
, VT
, X
, Y
, Z
));
6042 // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6043 // avoid the select that is necessary in the general case to filter out
6044 // the 0-shift possibility that leads to UB.
6045 if (X
== Y
&& isPowerOf2_32(VT
.getScalarSizeInBits())) {
6046 auto RotateOpcode
= IsFSHL
? ISD::ROTL
: ISD::ROTR
;
6047 if (TLI
.isOperationLegalOrCustom(RotateOpcode
, VT
)) {
6048 setValue(&I
, DAG
.getNode(RotateOpcode
, sdl
, VT
, X
, Z
));
6052 // Some targets only rotate one way. Try the opposite direction.
6053 RotateOpcode
= IsFSHL
? ISD::ROTR
: ISD::ROTL
;
6054 if (TLI
.isOperationLegalOrCustom(RotateOpcode
, VT
)) {
6055 // Negate the shift amount because it is safe to ignore the high bits.
6056 SDValue NegShAmt
= DAG
.getNode(ISD::SUB
, sdl
, VT
, Zero
, Z
);
6057 setValue(&I
, DAG
.getNode(RotateOpcode
, sdl
, VT
, X
, NegShAmt
));
6061 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6062 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6063 SDValue NegZ
= DAG
.getNode(ISD::SUB
, sdl
, VT
, Zero
, Z
);
6064 SDValue NShAmt
= DAG
.getNode(ISD::UREM
, sdl
, VT
, NegZ
, BitWidthC
);
6065 SDValue ShX
= DAG
.getNode(ISD::SHL
, sdl
, VT
, X
, IsFSHL
? ShAmt
: NShAmt
);
6066 SDValue ShY
= DAG
.getNode(ISD::SRL
, sdl
, VT
, X
, IsFSHL
? NShAmt
: ShAmt
);
6067 setValue(&I
, DAG
.getNode(ISD::OR
, sdl
, VT
, ShX
, ShY
));
6071 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6072 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6073 SDValue InvShAmt
= DAG
.getNode(ISD::SUB
, sdl
, VT
, BitWidthC
, ShAmt
);
6074 SDValue ShX
= DAG
.getNode(ISD::SHL
, sdl
, VT
, X
, IsFSHL
? ShAmt
: InvShAmt
);
6075 SDValue ShY
= DAG
.getNode(ISD::SRL
, sdl
, VT
, Y
, IsFSHL
? InvShAmt
: ShAmt
);
6076 SDValue Or
= DAG
.getNode(ISD::OR
, sdl
, VT
, ShX
, ShY
);
6078 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6079 // and that is undefined. We must compare and select to avoid UB.
6082 CCVT
= EVT::getVectorVT(*Context
, CCVT
, VT
.getVectorNumElements());
6084 // For fshl, 0-shift returns the 1st arg (X).
6085 // For fshr, 0-shift returns the 2nd arg (Y).
6086 SDValue IsZeroShift
= DAG
.getSetCC(sdl
, CCVT
, ShAmt
, Zero
, ISD::SETEQ
);
6087 setValue(&I
, DAG
.getSelect(sdl
, VT
, IsZeroShift
, IsFSHL
? X
: Y
, Or
));
6090 case Intrinsic::sadd_sat
: {
6091 SDValue Op1
= getValue(I
.getArgOperand(0));
6092 SDValue Op2
= getValue(I
.getArgOperand(1));
6093 setValue(&I
, DAG
.getNode(ISD::SADDSAT
, sdl
, Op1
.getValueType(), Op1
, Op2
));
6096 case Intrinsic::uadd_sat
: {
6097 SDValue Op1
= getValue(I
.getArgOperand(0));
6098 SDValue Op2
= getValue(I
.getArgOperand(1));
6099 setValue(&I
, DAG
.getNode(ISD::UADDSAT
, sdl
, Op1
.getValueType(), Op1
, Op2
));
6102 case Intrinsic::ssub_sat
: {
6103 SDValue Op1
= getValue(I
.getArgOperand(0));
6104 SDValue Op2
= getValue(I
.getArgOperand(1));
6105 setValue(&I
, DAG
.getNode(ISD::SSUBSAT
, sdl
, Op1
.getValueType(), Op1
, Op2
));
6108 case Intrinsic::usub_sat
: {
6109 SDValue Op1
= getValue(I
.getArgOperand(0));
6110 SDValue Op2
= getValue(I
.getArgOperand(1));
6111 setValue(&I
, DAG
.getNode(ISD::USUBSAT
, sdl
, Op1
.getValueType(), Op1
, Op2
));
6114 case Intrinsic::smul_fix
:
6115 case Intrinsic::umul_fix
: {
6116 SDValue Op1
= getValue(I
.getArgOperand(0));
6117 SDValue Op2
= getValue(I
.getArgOperand(1));
6118 SDValue Op3
= getValue(I
.getArgOperand(2));
6119 setValue(&I
, DAG
.getNode(FixedPointIntrinsicToOpcode(Intrinsic
), sdl
,
6120 Op1
.getValueType(), Op1
, Op2
, Op3
));
6123 case Intrinsic::stacksave
: {
6124 SDValue Op
= getRoot();
6126 ISD::STACKSAVE
, sdl
,
6127 DAG
.getVTList(TLI
.getPointerTy(DAG
.getDataLayout()), MVT::Other
), Op
);
6129 DAG
.setRoot(Res
.getValue(1));
6132 case Intrinsic::stackrestore
:
6133 Res
= getValue(I
.getArgOperand(0));
6134 DAG
.setRoot(DAG
.getNode(ISD::STACKRESTORE
, sdl
, MVT::Other
, getRoot(), Res
));
6136 case Intrinsic::get_dynamic_area_offset
: {
6137 SDValue Op
= getRoot();
6138 EVT PtrTy
= TLI
.getPointerTy(DAG
.getDataLayout());
6139 EVT ResTy
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
6140 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6143 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6145 Res
= DAG
.getNode(ISD::GET_DYNAMIC_AREA_OFFSET
, sdl
, DAG
.getVTList(ResTy
),
6151 case Intrinsic::stackguard
: {
6152 EVT PtrTy
= TLI
.getPointerTy(DAG
.getDataLayout());
6153 MachineFunction
&MF
= DAG
.getMachineFunction();
6154 const Module
&M
= *MF
.getFunction().getParent();
6155 SDValue Chain
= getRoot();
6156 if (TLI
.useLoadStackGuardNode()) {
6157 Res
= getLoadStackGuard(DAG
, sdl
, Chain
);
6159 const Value
*Global
= TLI
.getSDagStackGuard(M
);
6160 unsigned Align
= DL
->getPrefTypeAlignment(Global
->getType());
6161 Res
= DAG
.getLoad(PtrTy
, sdl
, Chain
, getValue(Global
),
6162 MachinePointerInfo(Global
, 0), Align
,
6163 MachineMemOperand::MOVolatile
);
6165 if (TLI
.useStackGuardXorFP())
6166 Res
= TLI
.emitStackGuardXorFP(DAG
, Res
, sdl
);
6171 case Intrinsic::stackprotector
: {
6172 // Emit code into the DAG to store the stack guard onto the stack.
6173 MachineFunction
&MF
= DAG
.getMachineFunction();
6174 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
6175 EVT PtrTy
= TLI
.getPointerTy(DAG
.getDataLayout());
6176 SDValue Src
, Chain
= getRoot();
6178 if (TLI
.useLoadStackGuardNode())
6179 Src
= getLoadStackGuard(DAG
, sdl
, Chain
);
6181 Src
= getValue(I
.getArgOperand(0)); // The guard's value.
6183 AllocaInst
*Slot
= cast
<AllocaInst
>(I
.getArgOperand(1));
6185 int FI
= FuncInfo
.StaticAllocaMap
[Slot
];
6186 MFI
.setStackProtectorIndex(FI
);
6188 SDValue FIN
= DAG
.getFrameIndex(FI
, PtrTy
);
6190 // Store the stack protector onto the stack.
6191 Res
= DAG
.getStore(Chain
, sdl
, Src
, FIN
, MachinePointerInfo::getFixedStack(
6192 DAG
.getMachineFunction(), FI
),
6193 /* Alignment = */ 0, MachineMemOperand::MOVolatile
);
6198 case Intrinsic::objectsize
: {
6199 // If we don't know by now, we're never going to know.
6200 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(I
.getArgOperand(1));
6202 assert(CI
&& "Non-constant type in __builtin_object_size?");
6204 SDValue Arg
= getValue(I
.getCalledValue());
6205 EVT Ty
= Arg
.getValueType();
6208 Res
= DAG
.getConstant(-1ULL, sdl
, Ty
);
6210 Res
= DAG
.getConstant(0, sdl
, Ty
);
6216 case Intrinsic::is_constant
:
6217 // If this wasn't constant-folded away by now, then it's not a
6219 setValue(&I
, DAG
.getConstant(0, sdl
, MVT::i1
));
6222 case Intrinsic::annotation
:
6223 case Intrinsic::ptr_annotation
:
6224 case Intrinsic::launder_invariant_group
:
6225 case Intrinsic::strip_invariant_group
:
6226 // Drop the intrinsic, but forward the value
6227 setValue(&I
, getValue(I
.getOperand(0)));
6229 case Intrinsic::assume
:
6230 case Intrinsic::var_annotation
:
6231 case Intrinsic::sideeffect
:
6232 // Discard annotate attributes, assumptions, and artificial side-effects.
6235 case Intrinsic::codeview_annotation
: {
6236 // Emit a label associated with this metadata.
6237 MachineFunction
&MF
= DAG
.getMachineFunction();
6239 MF
.getMMI().getContext().createTempSymbol("annotation", true);
6240 Metadata
*MD
= cast
<MetadataAsValue
>(I
.getArgOperand(0))->getMetadata();
6241 MF
.addCodeViewAnnotation(Label
, cast
<MDNode
>(MD
));
6242 Res
= DAG
.getLabelNode(ISD::ANNOTATION_LABEL
, sdl
, getRoot(), Label
);
6247 case Intrinsic::init_trampoline
: {
6248 const Function
*F
= cast
<Function
>(I
.getArgOperand(1)->stripPointerCasts());
6252 Ops
[1] = getValue(I
.getArgOperand(0));
6253 Ops
[2] = getValue(I
.getArgOperand(1));
6254 Ops
[3] = getValue(I
.getArgOperand(2));
6255 Ops
[4] = DAG
.getSrcValue(I
.getArgOperand(0));
6256 Ops
[5] = DAG
.getSrcValue(F
);
6258 Res
= DAG
.getNode(ISD::INIT_TRAMPOLINE
, sdl
, MVT::Other
, Ops
);
6263 case Intrinsic::adjust_trampoline
:
6264 setValue(&I
, DAG
.getNode(ISD::ADJUST_TRAMPOLINE
, sdl
,
6265 TLI
.getPointerTy(DAG
.getDataLayout()),
6266 getValue(I
.getArgOperand(0))));
6268 case Intrinsic::gcroot
: {
6269 assert(DAG
.getMachineFunction().getFunction().hasGC() &&
6270 "only valid in functions with gc specified, enforced by Verifier");
6271 assert(GFI
&& "implied by previous");
6272 const Value
*Alloca
= I
.getArgOperand(0)->stripPointerCasts();
6273 const Constant
*TypeMap
= cast
<Constant
>(I
.getArgOperand(1));
6275 FrameIndexSDNode
*FI
= cast
<FrameIndexSDNode
>(getValue(Alloca
).getNode());
6276 GFI
->addStackRoot(FI
->getIndex(), TypeMap
);
6279 case Intrinsic::gcread
:
6280 case Intrinsic::gcwrite
:
6281 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6282 case Intrinsic::flt_rounds
:
6283 setValue(&I
, DAG
.getNode(ISD::FLT_ROUNDS_
, sdl
, MVT::i32
));
6286 case Intrinsic::expect
:
6287 // Just replace __builtin_expect(exp, c) with EXP.
6288 setValue(&I
, getValue(I
.getArgOperand(0)));
6291 case Intrinsic::debugtrap
:
6292 case Intrinsic::trap
: {
6293 StringRef TrapFuncName
=
6295 .getAttribute(AttributeList::FunctionIndex
, "trap-func-name")
6296 .getValueAsString();
6297 if (TrapFuncName
.empty()) {
6298 ISD::NodeType Op
= (Intrinsic
== Intrinsic::trap
) ?
6299 ISD::TRAP
: ISD::DEBUGTRAP
;
6300 DAG
.setRoot(DAG
.getNode(Op
, sdl
,MVT::Other
, getRoot()));
6303 TargetLowering::ArgListTy Args
;
6305 TargetLowering::CallLoweringInfo
CLI(DAG
);
6306 CLI
.setDebugLoc(sdl
).setChain(getRoot()).setLibCallee(
6307 CallingConv::C
, I
.getType(),
6308 DAG
.getExternalSymbol(TrapFuncName
.data(),
6309 TLI
.getPointerTy(DAG
.getDataLayout())),
6312 std::pair
<SDValue
, SDValue
> Result
= TLI
.LowerCallTo(CLI
);
6313 DAG
.setRoot(Result
.second
);
6317 case Intrinsic::uadd_with_overflow
:
6318 case Intrinsic::sadd_with_overflow
:
6319 case Intrinsic::usub_with_overflow
:
6320 case Intrinsic::ssub_with_overflow
:
6321 case Intrinsic::umul_with_overflow
:
6322 case Intrinsic::smul_with_overflow
: {
6324 switch (Intrinsic
) {
6325 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6326 case Intrinsic::uadd_with_overflow
: Op
= ISD::UADDO
; break;
6327 case Intrinsic::sadd_with_overflow
: Op
= ISD::SADDO
; break;
6328 case Intrinsic::usub_with_overflow
: Op
= ISD::USUBO
; break;
6329 case Intrinsic::ssub_with_overflow
: Op
= ISD::SSUBO
; break;
6330 case Intrinsic::umul_with_overflow
: Op
= ISD::UMULO
; break;
6331 case Intrinsic::smul_with_overflow
: Op
= ISD::SMULO
; break;
6333 SDValue Op1
= getValue(I
.getArgOperand(0));
6334 SDValue Op2
= getValue(I
.getArgOperand(1));
6336 EVT ResultVT
= Op1
.getValueType();
6337 EVT OverflowVT
= MVT::i1
;
6338 if (ResultVT
.isVector())
6339 OverflowVT
= EVT::getVectorVT(
6340 *Context
, OverflowVT
, ResultVT
.getVectorNumElements());
6342 SDVTList VTs
= DAG
.getVTList(ResultVT
, OverflowVT
);
6343 setValue(&I
, DAG
.getNode(Op
, sdl
, VTs
, Op1
, Op2
));
6346 case Intrinsic::prefetch
: {
6348 unsigned rw
= cast
<ConstantInt
>(I
.getArgOperand(1))->getZExtValue();
6349 auto Flags
= rw
== 0 ? MachineMemOperand::MOLoad
:MachineMemOperand::MOStore
;
6350 Ops
[0] = DAG
.getRoot();
6351 Ops
[1] = getValue(I
.getArgOperand(0));
6352 Ops
[2] = getValue(I
.getArgOperand(1));
6353 Ops
[3] = getValue(I
.getArgOperand(2));
6354 Ops
[4] = getValue(I
.getArgOperand(3));
6355 SDValue Result
= DAG
.getMemIntrinsicNode(ISD::PREFETCH
, sdl
,
6356 DAG
.getVTList(MVT::Other
), Ops
,
6357 EVT::getIntegerVT(*Context
, 8),
6358 MachinePointerInfo(I
.getArgOperand(0)),
6362 // Chain the prefetch in parallell with any pending loads, to stay out of
6363 // the way of later optimizations.
6364 PendingLoads
.push_back(Result
);
6366 DAG
.setRoot(Result
);
6369 case Intrinsic::lifetime_start
:
6370 case Intrinsic::lifetime_end
: {
6371 bool IsStart
= (Intrinsic
== Intrinsic::lifetime_start
);
6372 // Stack coloring is not enabled in O0, discard region information.
6373 if (TM
.getOptLevel() == CodeGenOpt::None
)
6376 SmallVector
<Value
*, 4> Allocas
;
6377 GetUnderlyingObjects(I
.getArgOperand(1), Allocas
, *DL
);
6379 for (SmallVectorImpl
<Value
*>::iterator Object
= Allocas
.begin(),
6380 E
= Allocas
.end(); Object
!= E
; ++Object
) {
6381 AllocaInst
*LifetimeObject
= dyn_cast_or_null
<AllocaInst
>(*Object
);
6383 // Could not find an Alloca.
6384 if (!LifetimeObject
)
6387 // First check that the Alloca is static, otherwise it won't have a
6388 // valid frame index.
6389 auto SI
= FuncInfo
.StaticAllocaMap
.find(LifetimeObject
);
6390 if (SI
== FuncInfo
.StaticAllocaMap
.end())
6393 int FI
= SI
->second
;
6398 DAG
.getFrameIndex(FI
, TLI
.getFrameIndexTy(DAG
.getDataLayout()), true);
6399 unsigned Opcode
= (IsStart
? ISD::LIFETIME_START
: ISD::LIFETIME_END
);
6401 Res
= DAG
.getNode(Opcode
, sdl
, MVT::Other
, Ops
);
6406 case Intrinsic::invariant_start
:
6407 // Discard region information.
6408 setValue(&I
, DAG
.getUNDEF(TLI
.getPointerTy(DAG
.getDataLayout())));
6410 case Intrinsic::invariant_end
:
6411 // Discard region information.
6413 case Intrinsic::clear_cache
:
6414 return TLI
.getClearCacheBuiltinName();
6415 case Intrinsic::donothing
:
6418 case Intrinsic::experimental_stackmap
:
6421 case Intrinsic::experimental_patchpoint_void
:
6422 case Intrinsic::experimental_patchpoint_i64
:
6423 visitPatchpoint(&I
);
6425 case Intrinsic::experimental_gc_statepoint
:
6426 LowerStatepoint(ImmutableStatepoint(&I
));
6428 case Intrinsic::experimental_gc_result
:
6429 visitGCResult(cast
<GCResultInst
>(I
));
6431 case Intrinsic::experimental_gc_relocate
:
6432 visitGCRelocate(cast
<GCRelocateInst
>(I
));
6434 case Intrinsic::instrprof_increment
:
6435 llvm_unreachable("instrprof failed to lower an increment");
6436 case Intrinsic::instrprof_value_profile
:
6437 llvm_unreachable("instrprof failed to lower a value profiling call");
6438 case Intrinsic::localescape
: {
6439 MachineFunction
&MF
= DAG
.getMachineFunction();
6440 const TargetInstrInfo
*TII
= DAG
.getSubtarget().getInstrInfo();
6442 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6443 // is the same on all targets.
6444 for (unsigned Idx
= 0, E
= I
.getNumArgOperands(); Idx
< E
; ++Idx
) {
6445 Value
*Arg
= I
.getArgOperand(Idx
)->stripPointerCasts();
6446 if (isa
<ConstantPointerNull
>(Arg
))
6447 continue; // Skip null pointers. They represent a hole in index space.
6448 AllocaInst
*Slot
= cast
<AllocaInst
>(Arg
);
6449 assert(FuncInfo
.StaticAllocaMap
.count(Slot
) &&
6450 "can only escape static allocas");
6451 int FI
= FuncInfo
.StaticAllocaMap
[Slot
];
6452 MCSymbol
*FrameAllocSym
=
6453 MF
.getMMI().getContext().getOrCreateFrameAllocSymbol(
6454 GlobalValue::dropLLVMManglingEscape(MF
.getName()), Idx
);
6455 BuildMI(*FuncInfo
.MBB
, FuncInfo
.InsertPt
, dl
,
6456 TII
->get(TargetOpcode::LOCAL_ESCAPE
))
6457 .addSym(FrameAllocSym
)
6464 case Intrinsic::localrecover
: {
6465 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6466 MachineFunction
&MF
= DAG
.getMachineFunction();
6467 MVT PtrVT
= TLI
.getPointerTy(DAG
.getDataLayout(), 0);
6469 // Get the symbol that defines the frame offset.
6470 auto *Fn
= cast
<Function
>(I
.getArgOperand(0)->stripPointerCasts());
6471 auto *Idx
= cast
<ConstantInt
>(I
.getArgOperand(2));
6473 unsigned(Idx
->getLimitedValue(std::numeric_limits
<int>::max()));
6474 MCSymbol
*FrameAllocSym
=
6475 MF
.getMMI().getContext().getOrCreateFrameAllocSymbol(
6476 GlobalValue::dropLLVMManglingEscape(Fn
->getName()), IdxVal
);
6478 // Create a MCSymbol for the label to avoid any target lowering
6479 // that would make this PC relative.
6480 SDValue OffsetSym
= DAG
.getMCSymbol(FrameAllocSym
, PtrVT
);
6482 DAG
.getNode(ISD::LOCAL_RECOVER
, sdl
, PtrVT
, OffsetSym
);
6484 // Add the offset to the FP.
6485 Value
*FP
= I
.getArgOperand(1);
6486 SDValue FPVal
= getValue(FP
);
6487 SDValue Add
= DAG
.getNode(ISD::ADD
, sdl
, PtrVT
, FPVal
, OffsetVal
);
6493 case Intrinsic::eh_exceptionpointer
:
6494 case Intrinsic::eh_exceptioncode
: {
6495 // Get the exception pointer vreg, copy from it, and resize it to fit.
6496 const auto *CPI
= cast
<CatchPadInst
>(I
.getArgOperand(0));
6497 MVT PtrVT
= TLI
.getPointerTy(DAG
.getDataLayout());
6498 const TargetRegisterClass
*PtrRC
= TLI
.getRegClassFor(PtrVT
);
6499 unsigned VReg
= FuncInfo
.getCatchPadExceptionPointerVReg(CPI
, PtrRC
);
6501 DAG
.getCopyFromReg(DAG
.getEntryNode(), getCurSDLoc(), VReg
, PtrVT
);
6502 if (Intrinsic
== Intrinsic::eh_exceptioncode
)
6503 N
= DAG
.getZExtOrTrunc(N
, getCurSDLoc(), MVT::i32
);
6507 case Intrinsic::xray_customevent
: {
6508 // Here we want to make sure that the intrinsic behaves as if it has a
6509 // specific calling convention, and only for x86_64.
6510 // FIXME: Support other platforms later.
6511 const auto &Triple
= DAG
.getTarget().getTargetTriple();
6512 if (Triple
.getArch() != Triple::x86_64
|| !Triple
.isOSLinux())
6515 SDLoc DL
= getCurSDLoc();
6516 SmallVector
<SDValue
, 8> Ops
;
6518 // We want to say that we always want the arguments in registers.
6519 SDValue LogEntryVal
= getValue(I
.getArgOperand(0));
6520 SDValue StrSizeVal
= getValue(I
.getArgOperand(1));
6521 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
6522 SDValue Chain
= getRoot();
6523 Ops
.push_back(LogEntryVal
);
6524 Ops
.push_back(StrSizeVal
);
6525 Ops
.push_back(Chain
);
6527 // We need to enforce the calling convention for the callsite, so that
6528 // argument ordering is enforced correctly, and that register allocation can
6529 // see that some registers may be assumed clobbered and have to preserve
6530 // them across calls to the intrinsic.
6531 MachineSDNode
*MN
= DAG
.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL
,
6533 SDValue patchableNode
= SDValue(MN
, 0);
6534 DAG
.setRoot(patchableNode
);
6535 setValue(&I
, patchableNode
);
6538 case Intrinsic::xray_typedevent
: {
6539 // Here we want to make sure that the intrinsic behaves as if it has a
6540 // specific calling convention, and only for x86_64.
6541 // FIXME: Support other platforms later.
6542 const auto &Triple
= DAG
.getTarget().getTargetTriple();
6543 if (Triple
.getArch() != Triple::x86_64
|| !Triple
.isOSLinux())
6546 SDLoc DL
= getCurSDLoc();
6547 SmallVector
<SDValue
, 8> Ops
;
6549 // We want to say that we always want the arguments in registers.
6550 // It's unclear to me how manipulating the selection DAG here forces callers
6551 // to provide arguments in registers instead of on the stack.
6552 SDValue LogTypeId
= getValue(I
.getArgOperand(0));
6553 SDValue LogEntryVal
= getValue(I
.getArgOperand(1));
6554 SDValue StrSizeVal
= getValue(I
.getArgOperand(2));
6555 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
6556 SDValue Chain
= getRoot();
6557 Ops
.push_back(LogTypeId
);
6558 Ops
.push_back(LogEntryVal
);
6559 Ops
.push_back(StrSizeVal
);
6560 Ops
.push_back(Chain
);
6562 // We need to enforce the calling convention for the callsite, so that
6563 // argument ordering is enforced correctly, and that register allocation can
6564 // see that some registers may be assumed clobbered and have to preserve
6565 // them across calls to the intrinsic.
6566 MachineSDNode
*MN
= DAG
.getMachineNode(
6567 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL
, DL
, NodeTys
, Ops
);
6568 SDValue patchableNode
= SDValue(MN
, 0);
6569 DAG
.setRoot(patchableNode
);
6570 setValue(&I
, patchableNode
);
6573 case Intrinsic::experimental_deoptimize
:
6574 LowerDeoptimizeCall(&I
);
6577 case Intrinsic::experimental_vector_reduce_fadd
:
6578 case Intrinsic::experimental_vector_reduce_fmul
:
6579 case Intrinsic::experimental_vector_reduce_add
:
6580 case Intrinsic::experimental_vector_reduce_mul
:
6581 case Intrinsic::experimental_vector_reduce_and
:
6582 case Intrinsic::experimental_vector_reduce_or
:
6583 case Intrinsic::experimental_vector_reduce_xor
:
6584 case Intrinsic::experimental_vector_reduce_smax
:
6585 case Intrinsic::experimental_vector_reduce_smin
:
6586 case Intrinsic::experimental_vector_reduce_umax
:
6587 case Intrinsic::experimental_vector_reduce_umin
:
6588 case Intrinsic::experimental_vector_reduce_fmax
:
6589 case Intrinsic::experimental_vector_reduce_fmin
:
6590 visitVectorReduce(I
, Intrinsic
);
6593 case Intrinsic::icall_branch_funnel
: {
6594 SmallVector
<SDValue
, 16> Ops
;
6595 Ops
.push_back(DAG
.getRoot());
6596 Ops
.push_back(getValue(I
.getArgOperand(0)));
6599 auto *Base
= dyn_cast
<GlobalObject
>(GetPointerBaseWithConstantOffset(
6600 I
.getArgOperand(1), Offset
, DAG
.getDataLayout()));
6603 "llvm.icall.branch.funnel operand must be a GlobalValue");
6604 Ops
.push_back(DAG
.getTargetGlobalAddress(Base
, getCurSDLoc(), MVT::i64
, 0));
6606 struct BranchFunnelTarget
{
6610 SmallVector
<BranchFunnelTarget
, 8> Targets
;
6612 for (unsigned Op
= 1, N
= I
.getNumArgOperands(); Op
!= N
; Op
+= 2) {
6613 auto *ElemBase
= dyn_cast
<GlobalObject
>(GetPointerBaseWithConstantOffset(
6614 I
.getArgOperand(Op
), Offset
, DAG
.getDataLayout()));
6615 if (ElemBase
!= Base
)
6616 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6617 "to the same GlobalValue");
6619 SDValue Val
= getValue(I
.getArgOperand(Op
+ 1));
6620 auto *GA
= dyn_cast
<GlobalAddressSDNode
>(Val
);
6623 "llvm.icall.branch.funnel operand must be a GlobalValue");
6624 Targets
.push_back({Offset
, DAG
.getTargetGlobalAddress(
6625 GA
->getGlobal(), getCurSDLoc(),
6626 Val
.getValueType(), GA
->getOffset())});
6629 [](const BranchFunnelTarget
&T1
, const BranchFunnelTarget
&T2
) {
6630 return T1
.Offset
< T2
.Offset
;
6633 for (auto &T
: Targets
) {
6634 Ops
.push_back(DAG
.getTargetConstant(T
.Offset
, getCurSDLoc(), MVT::i32
));
6635 Ops
.push_back(T
.Target
);
6638 SDValue
N(DAG
.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL
,
6639 getCurSDLoc(), MVT::Other
, Ops
),
6647 case Intrinsic::wasm_landingpad_index
:
6648 // Information this intrinsic contained has been transferred to
6649 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6655 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6656 const ConstrainedFPIntrinsic
&FPI
) {
6657 SDLoc sdl
= getCurSDLoc();
6659 switch (FPI
.getIntrinsicID()) {
6660 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6661 case Intrinsic::experimental_constrained_fadd
:
6662 Opcode
= ISD::STRICT_FADD
;
6664 case Intrinsic::experimental_constrained_fsub
:
6665 Opcode
= ISD::STRICT_FSUB
;
6667 case Intrinsic::experimental_constrained_fmul
:
6668 Opcode
= ISD::STRICT_FMUL
;
6670 case Intrinsic::experimental_constrained_fdiv
:
6671 Opcode
= ISD::STRICT_FDIV
;
6673 case Intrinsic::experimental_constrained_frem
:
6674 Opcode
= ISD::STRICT_FREM
;
6676 case Intrinsic::experimental_constrained_fma
:
6677 Opcode
= ISD::STRICT_FMA
;
6679 case Intrinsic::experimental_constrained_sqrt
:
6680 Opcode
= ISD::STRICT_FSQRT
;
6682 case Intrinsic::experimental_constrained_pow
:
6683 Opcode
= ISD::STRICT_FPOW
;
6685 case Intrinsic::experimental_constrained_powi
:
6686 Opcode
= ISD::STRICT_FPOWI
;
6688 case Intrinsic::experimental_constrained_sin
:
6689 Opcode
= ISD::STRICT_FSIN
;
6691 case Intrinsic::experimental_constrained_cos
:
6692 Opcode
= ISD::STRICT_FCOS
;
6694 case Intrinsic::experimental_constrained_exp
:
6695 Opcode
= ISD::STRICT_FEXP
;
6697 case Intrinsic::experimental_constrained_exp2
:
6698 Opcode
= ISD::STRICT_FEXP2
;
6700 case Intrinsic::experimental_constrained_log
:
6701 Opcode
= ISD::STRICT_FLOG
;
6703 case Intrinsic::experimental_constrained_log10
:
6704 Opcode
= ISD::STRICT_FLOG10
;
6706 case Intrinsic::experimental_constrained_log2
:
6707 Opcode
= ISD::STRICT_FLOG2
;
6709 case Intrinsic::experimental_constrained_rint
:
6710 Opcode
= ISD::STRICT_FRINT
;
6712 case Intrinsic::experimental_constrained_nearbyint
:
6713 Opcode
= ISD::STRICT_FNEARBYINT
;
6715 case Intrinsic::experimental_constrained_maxnum
:
6716 Opcode
= ISD::STRICT_FMAXNUM
;
6718 case Intrinsic::experimental_constrained_minnum
:
6719 Opcode
= ISD::STRICT_FMINNUM
;
6721 case Intrinsic::experimental_constrained_ceil
:
6722 Opcode
= ISD::STRICT_FCEIL
;
6724 case Intrinsic::experimental_constrained_floor
:
6725 Opcode
= ISD::STRICT_FFLOOR
;
6727 case Intrinsic::experimental_constrained_round
:
6728 Opcode
= ISD::STRICT_FROUND
;
6730 case Intrinsic::experimental_constrained_trunc
:
6731 Opcode
= ISD::STRICT_FTRUNC
;
6734 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
6735 SDValue Chain
= getRoot();
6736 SmallVector
<EVT
, 4> ValueVTs
;
6737 ComputeValueVTs(TLI
, DAG
.getDataLayout(), FPI
.getType(), ValueVTs
);
6738 ValueVTs
.push_back(MVT::Other
); // Out chain
6740 SDVTList VTs
= DAG
.getVTList(ValueVTs
);
6742 if (FPI
.isUnaryOp())
6743 Result
= DAG
.getNode(Opcode
, sdl
, VTs
,
6744 { Chain
, getValue(FPI
.getArgOperand(0)) });
6745 else if (FPI
.isTernaryOp())
6746 Result
= DAG
.getNode(Opcode
, sdl
, VTs
,
6747 { Chain
, getValue(FPI
.getArgOperand(0)),
6748 getValue(FPI
.getArgOperand(1)),
6749 getValue(FPI
.getArgOperand(2)) });
6751 Result
= DAG
.getNode(Opcode
, sdl
, VTs
,
6752 { Chain
, getValue(FPI
.getArgOperand(0)),
6753 getValue(FPI
.getArgOperand(1)) });
6755 assert(Result
.getNode()->getNumValues() == 2);
6756 SDValue OutChain
= Result
.getValue(1);
6757 DAG
.setRoot(OutChain
);
6758 SDValue FPResult
= Result
.getValue(0);
6759 setValue(&FPI
, FPResult
);
6762 std::pair
<SDValue
, SDValue
>
6763 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo
&CLI
,
6764 const BasicBlock
*EHPadBB
) {
6765 MachineFunction
&MF
= DAG
.getMachineFunction();
6766 MachineModuleInfo
&MMI
= MF
.getMMI();
6767 MCSymbol
*BeginLabel
= nullptr;
6770 // Insert a label before the invoke call to mark the try range. This can be
6771 // used to detect deletion of the invoke via the MachineModuleInfo.
6772 BeginLabel
= MMI
.getContext().createTempSymbol();
6774 // For SjLj, keep track of which landing pads go with which invokes
6775 // so as to maintain the ordering of pads in the LSDA.
6776 unsigned CallSiteIndex
= MMI
.getCurrentCallSite();
6777 if (CallSiteIndex
) {
6778 MF
.setCallSiteBeginLabel(BeginLabel
, CallSiteIndex
);
6779 LPadToCallSiteMap
[FuncInfo
.MBBMap
[EHPadBB
]].push_back(CallSiteIndex
);
6781 // Now that the call site is handled, stop tracking it.
6782 MMI
.setCurrentCallSite(0);
6785 // Both PendingLoads and PendingExports must be flushed here;
6786 // this call might not return.
6788 DAG
.setRoot(DAG
.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel
));
6790 CLI
.setChain(getRoot());
6792 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
6793 std::pair
<SDValue
, SDValue
> Result
= TLI
.LowerCallTo(CLI
);
6795 assert((CLI
.IsTailCall
|| Result
.second
.getNode()) &&
6796 "Non-null chain expected with non-tail call!");
6797 assert((Result
.second
.getNode() || !Result
.first
.getNode()) &&
6798 "Null value expected with tail call!");
6800 if (!Result
.second
.getNode()) {
6801 // As a special case, a null chain means that a tail call has been emitted
6802 // and the DAG root is already updated.
6805 // Since there's no actual continuation from this block, nothing can be
6806 // relying on us setting vregs for them.
6807 PendingExports
.clear();
6809 DAG
.setRoot(Result
.second
);
6813 // Insert a label at the end of the invoke call to mark the try range. This
6814 // can be used to detect deletion of the invoke via the MachineModuleInfo.
6815 MCSymbol
*EndLabel
= MMI
.getContext().createTempSymbol();
6816 DAG
.setRoot(DAG
.getEHLabel(getCurSDLoc(), getRoot(), EndLabel
));
6818 // Inform MachineModuleInfo of range.
6819 auto Pers
= classifyEHPersonality(FuncInfo
.Fn
->getPersonalityFn());
6820 // There is a platform (e.g. wasm) that uses funclet style IR but does not
6821 // actually use outlined funclets and their LSDA info style.
6822 if (MF
.hasEHFunclets() && isFuncletEHPersonality(Pers
)) {
6824 WinEHFuncInfo
*EHInfo
= DAG
.getMachineFunction().getWinEHFuncInfo();
6825 EHInfo
->addIPToStateRange(cast
<InvokeInst
>(CLI
.CS
.getInstruction()),
6826 BeginLabel
, EndLabel
);
6827 } else if (!isScopedEHPersonality(Pers
)) {
6828 MF
.addInvoke(FuncInfo
.MBBMap
[EHPadBB
], BeginLabel
, EndLabel
);
6835 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS
, SDValue Callee
,
6837 const BasicBlock
*EHPadBB
) {
6838 auto &DL
= DAG
.getDataLayout();
6839 FunctionType
*FTy
= CS
.getFunctionType();
6840 Type
*RetTy
= CS
.getType();
6842 TargetLowering::ArgListTy Args
;
6843 Args
.reserve(CS
.arg_size());
6845 const Value
*SwiftErrorVal
= nullptr;
6846 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
6848 // We can't tail call inside a function with a swifterror argument. Lowering
6849 // does not support this yet. It would have to move into the swifterror
6850 // register before the call.
6851 auto *Caller
= CS
.getInstruction()->getParent()->getParent();
6852 if (TLI
.supportSwiftError() &&
6853 Caller
->getAttributes().hasAttrSomewhere(Attribute::SwiftError
))
6856 for (ImmutableCallSite::arg_iterator i
= CS
.arg_begin(), e
= CS
.arg_end();
6858 TargetLowering::ArgListEntry Entry
;
6859 const Value
*V
= *i
;
6862 if (V
->getType()->isEmptyTy())
6865 SDValue ArgNode
= getValue(V
);
6866 Entry
.Node
= ArgNode
; Entry
.Ty
= V
->getType();
6868 Entry
.setAttributes(&CS
, i
- CS
.arg_begin());
6870 // Use swifterror virtual register as input to the call.
6871 if (Entry
.IsSwiftError
&& TLI
.supportSwiftError()) {
6873 // We find the virtual register for the actual swifterror argument.
6874 // Instead of using the Value, we use the virtual register instead.
6875 Entry
.Node
= DAG
.getRegister(FuncInfo
6876 .getOrCreateSwiftErrorVRegUseAt(
6877 CS
.getInstruction(), FuncInfo
.MBB
, V
)
6879 EVT(TLI
.getPointerTy(DL
)));
6882 Args
.push_back(Entry
);
6884 // If we have an explicit sret argument that is an Instruction, (i.e., it
6885 // might point to function-local memory), we can't meaningfully tail-call.
6886 if (Entry
.IsSRet
&& isa
<Instruction
>(V
))
6890 // Check if target-independent constraints permit a tail call here.
6891 // Target-dependent constraints are checked within TLI->LowerCallTo.
6892 if (isTailCall
&& !isInTailCallPosition(CS
, DAG
.getTarget()))
6895 // Disable tail calls if there is an swifterror argument. Targets have not
6896 // been updated to support tail calls.
6897 if (TLI
.supportSwiftError() && SwiftErrorVal
)
6900 TargetLowering::CallLoweringInfo
CLI(DAG
);
6901 CLI
.setDebugLoc(getCurSDLoc())
6902 .setChain(getRoot())
6903 .setCallee(RetTy
, FTy
, Callee
, std::move(Args
), CS
)
6904 .setTailCall(isTailCall
)
6905 .setConvergent(CS
.isConvergent());
6906 std::pair
<SDValue
, SDValue
> Result
= lowerInvokable(CLI
, EHPadBB
);
6908 if (Result
.first
.getNode()) {
6909 const Instruction
*Inst
= CS
.getInstruction();
6910 Result
.first
= lowerRangeToAssertZExt(DAG
, *Inst
, Result
.first
);
6911 setValue(Inst
, Result
.first
);
6914 // The last element of CLI.InVals has the SDValue for swifterror return.
6915 // Here we copy it to a virtual register and update SwiftErrorMap for
6917 if (SwiftErrorVal
&& TLI
.supportSwiftError()) {
6918 // Get the last element of InVals.
6919 SDValue Src
= CLI
.InVals
.back();
6920 unsigned VReg
; bool CreatedVReg
;
6921 std::tie(VReg
, CreatedVReg
) =
6922 FuncInfo
.getOrCreateSwiftErrorVRegDefAt(CS
.getInstruction());
6923 SDValue CopyNode
= CLI
.DAG
.getCopyToReg(Result
.second
, CLI
.DL
, VReg
, Src
);
6924 // We update the virtual register for the actual swifterror argument.
6926 FuncInfo
.setCurrentSwiftErrorVReg(FuncInfo
.MBB
, SwiftErrorVal
, VReg
);
6927 DAG
.setRoot(CopyNode
);
6931 static SDValue
getMemCmpLoad(const Value
*PtrVal
, MVT LoadVT
,
6932 SelectionDAGBuilder
&Builder
) {
6933 // Check to see if this load can be trivially constant folded, e.g. if the
6934 // input is from a string literal.
6935 if (const Constant
*LoadInput
= dyn_cast
<Constant
>(PtrVal
)) {
6936 // Cast pointer to the type we really want to load.
6938 Type::getIntNTy(PtrVal
->getContext(), LoadVT
.getScalarSizeInBits());
6939 if (LoadVT
.isVector())
6940 LoadTy
= VectorType::get(LoadTy
, LoadVT
.getVectorNumElements());
6942 LoadInput
= ConstantExpr::getBitCast(const_cast<Constant
*>(LoadInput
),
6943 PointerType::getUnqual(LoadTy
));
6945 if (const Constant
*LoadCst
= ConstantFoldLoadFromConstPtr(
6946 const_cast<Constant
*>(LoadInput
), LoadTy
, *Builder
.DL
))
6947 return Builder
.getValue(LoadCst
);
6950 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
6951 // still constant memory, the input chain can be the entry node.
6953 bool ConstantMemory
= false;
6955 // Do not serialize (non-volatile) loads of constant memory with anything.
6956 if (Builder
.AA
&& Builder
.AA
->pointsToConstantMemory(PtrVal
)) {
6957 Root
= Builder
.DAG
.getEntryNode();
6958 ConstantMemory
= true;
6960 // Do not serialize non-volatile loads against each other.
6961 Root
= Builder
.DAG
.getRoot();
6964 SDValue Ptr
= Builder
.getValue(PtrVal
);
6965 SDValue LoadVal
= Builder
.DAG
.getLoad(LoadVT
, Builder
.getCurSDLoc(), Root
,
6966 Ptr
, MachinePointerInfo(PtrVal
),
6967 /* Alignment = */ 1);
6969 if (!ConstantMemory
)
6970 Builder
.PendingLoads
.push_back(LoadVal
.getValue(1));
6974 /// Record the value for an instruction that produces an integer result,
6975 /// converting the type where necessary.
6976 void SelectionDAGBuilder::processIntegerCallValue(const Instruction
&I
,
6979 EVT VT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
6982 Value
= DAG
.getSExtOrTrunc(Value
, getCurSDLoc(), VT
);
6984 Value
= DAG
.getZExtOrTrunc(Value
, getCurSDLoc(), VT
);
6985 setValue(&I
, Value
);
6988 /// See if we can lower a memcmp call into an optimized form. If so, return
6989 /// true and lower it. Otherwise return false, and it will be lowered like a
6991 /// The caller already checked that \p I calls the appropriate LibFunc with a
6992 /// correct prototype.
6993 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst
&I
) {
6994 const Value
*LHS
= I
.getArgOperand(0), *RHS
= I
.getArgOperand(1);
6995 const Value
*Size
= I
.getArgOperand(2);
6996 const ConstantInt
*CSize
= dyn_cast
<ConstantInt
>(Size
);
6997 if (CSize
&& CSize
->getZExtValue() == 0) {
6998 EVT CallVT
= DAG
.getTargetLoweringInfo().getValueType(DAG
.getDataLayout(),
7000 setValue(&I
, DAG
.getConstant(0, getCurSDLoc(), CallVT
));
7004 const SelectionDAGTargetInfo
&TSI
= DAG
.getSelectionDAGInfo();
7005 std::pair
<SDValue
, SDValue
> Res
= TSI
.EmitTargetCodeForMemcmp(
7006 DAG
, getCurSDLoc(), DAG
.getRoot(), getValue(LHS
), getValue(RHS
),
7007 getValue(Size
), MachinePointerInfo(LHS
), MachinePointerInfo(RHS
));
7008 if (Res
.first
.getNode()) {
7009 processIntegerCallValue(I
, Res
.first
, true);
7010 PendingLoads
.push_back(Res
.second
);
7014 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
7015 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
7016 if (!CSize
|| !isOnlyUsedInZeroEqualityComparison(&I
))
7019 // If the target has a fast compare for the given size, it will return a
7020 // preferred load type for that size. Require that the load VT is legal and
7021 // that the target supports unaligned loads of that type. Otherwise, return
7023 auto hasFastLoadsAndCompare
= [&](unsigned NumBits
) {
7024 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
7025 MVT LVT
= TLI
.hasFastEqualityCompare(NumBits
);
7026 if (LVT
!= MVT::INVALID_SIMPLE_VALUE_TYPE
) {
7027 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7028 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7029 // TODO: Check alignment of src and dest ptrs.
7030 unsigned DstAS
= LHS
->getType()->getPointerAddressSpace();
7031 unsigned SrcAS
= RHS
->getType()->getPointerAddressSpace();
7032 if (!TLI
.isTypeLegal(LVT
) ||
7033 !TLI
.allowsMisalignedMemoryAccesses(LVT
, SrcAS
) ||
7034 !TLI
.allowsMisalignedMemoryAccesses(LVT
, DstAS
))
7035 LVT
= MVT::INVALID_SIMPLE_VALUE_TYPE
;
7041 // This turns into unaligned loads. We only do this if the target natively
7042 // supports the MVT we'll be loading or if it is small enough (<= 4) that
7043 // we'll only produce a small number of byte loads.
7045 unsigned NumBitsToCompare
= CSize
->getZExtValue() * 8;
7046 switch (NumBitsToCompare
) {
7058 LoadVT
= hasFastLoadsAndCompare(NumBitsToCompare
);
7062 if (LoadVT
== MVT::INVALID_SIMPLE_VALUE_TYPE
)
7065 SDValue LoadL
= getMemCmpLoad(LHS
, LoadVT
, *this);
7066 SDValue LoadR
= getMemCmpLoad(RHS
, LoadVT
, *this);
7068 // Bitcast to a wide integer type if the loads are vectors.
7069 if (LoadVT
.isVector()) {
7070 EVT CmpVT
= EVT::getIntegerVT(LHS
->getContext(), LoadVT
.getSizeInBits());
7071 LoadL
= DAG
.getBitcast(CmpVT
, LoadL
);
7072 LoadR
= DAG
.getBitcast(CmpVT
, LoadR
);
7075 SDValue Cmp
= DAG
.getSetCC(getCurSDLoc(), MVT::i1
, LoadL
, LoadR
, ISD::SETNE
);
7076 processIntegerCallValue(I
, Cmp
, false);
7080 /// See if we can lower a memchr call into an optimized form. If so, return
7081 /// true and lower it. Otherwise return false, and it will be lowered like a
7083 /// The caller already checked that \p I calls the appropriate LibFunc with a
7084 /// correct prototype.
7085 bool SelectionDAGBuilder::visitMemChrCall(const CallInst
&I
) {
7086 const Value
*Src
= I
.getArgOperand(0);
7087 const Value
*Char
= I
.getArgOperand(1);
7088 const Value
*Length
= I
.getArgOperand(2);
7090 const SelectionDAGTargetInfo
&TSI
= DAG
.getSelectionDAGInfo();
7091 std::pair
<SDValue
, SDValue
> Res
=
7092 TSI
.EmitTargetCodeForMemchr(DAG
, getCurSDLoc(), DAG
.getRoot(),
7093 getValue(Src
), getValue(Char
), getValue(Length
),
7094 MachinePointerInfo(Src
));
7095 if (Res
.first
.getNode()) {
7096 setValue(&I
, Res
.first
);
7097 PendingLoads
.push_back(Res
.second
);
7104 /// See if we can lower a mempcpy call into an optimized form. If so, return
7105 /// true and lower it. Otherwise return false, and it will be lowered like a
7107 /// The caller already checked that \p I calls the appropriate LibFunc with a
7108 /// correct prototype.
7109 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst
&I
) {
7110 SDValue Dst
= getValue(I
.getArgOperand(0));
7111 SDValue Src
= getValue(I
.getArgOperand(1));
7112 SDValue Size
= getValue(I
.getArgOperand(2));
7114 unsigned DstAlign
= DAG
.InferPtrAlignment(Dst
);
7115 unsigned SrcAlign
= DAG
.InferPtrAlignment(Src
);
7116 unsigned Align
= std::min(DstAlign
, SrcAlign
);
7117 if (Align
== 0) // Alignment of one or both could not be inferred.
7118 Align
= 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7121 SDLoc sdl
= getCurSDLoc();
7123 // In the mempcpy context we need to pass in a false value for isTailCall
7124 // because the return pointer needs to be adjusted by the size of
7125 // the copied memory.
7126 SDValue MC
= DAG
.getMemcpy(getRoot(), sdl
, Dst
, Src
, Size
, Align
, isVol
,
7127 false, /*isTailCall=*/false,
7128 MachinePointerInfo(I
.getArgOperand(0)),
7129 MachinePointerInfo(I
.getArgOperand(1)));
7130 assert(MC
.getNode() != nullptr &&
7131 "** memcpy should not be lowered as TailCall in mempcpy context **");
7134 // Check if Size needs to be truncated or extended.
7135 Size
= DAG
.getSExtOrTrunc(Size
, sdl
, Dst
.getValueType());
7137 // Adjust return pointer to point just past the last dst byte.
7138 SDValue DstPlusSize
= DAG
.getNode(ISD::ADD
, sdl
, Dst
.getValueType(),
7140 setValue(&I
, DstPlusSize
);
7144 /// See if we can lower a strcpy call into an optimized form. If so, return
7145 /// true and lower it, otherwise return false and it will be lowered like a
7147 /// The caller already checked that \p I calls the appropriate LibFunc with a
7148 /// correct prototype.
7149 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst
&I
, bool isStpcpy
) {
7150 const Value
*Arg0
= I
.getArgOperand(0), *Arg1
= I
.getArgOperand(1);
7152 const SelectionDAGTargetInfo
&TSI
= DAG
.getSelectionDAGInfo();
7153 std::pair
<SDValue
, SDValue
> Res
=
7154 TSI
.EmitTargetCodeForStrcpy(DAG
, getCurSDLoc(), getRoot(),
7155 getValue(Arg0
), getValue(Arg1
),
7156 MachinePointerInfo(Arg0
),
7157 MachinePointerInfo(Arg1
), isStpcpy
);
7158 if (Res
.first
.getNode()) {
7159 setValue(&I
, Res
.first
);
7160 DAG
.setRoot(Res
.second
);
7167 /// See if we can lower a strcmp call into an optimized form. If so, return
7168 /// true and lower it, otherwise return false and it will be lowered like a
7170 /// The caller already checked that \p I calls the appropriate LibFunc with a
7171 /// correct prototype.
7172 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst
&I
) {
7173 const Value
*Arg0
= I
.getArgOperand(0), *Arg1
= I
.getArgOperand(1);
7175 const SelectionDAGTargetInfo
&TSI
= DAG
.getSelectionDAGInfo();
7176 std::pair
<SDValue
, SDValue
> Res
=
7177 TSI
.EmitTargetCodeForStrcmp(DAG
, getCurSDLoc(), DAG
.getRoot(),
7178 getValue(Arg0
), getValue(Arg1
),
7179 MachinePointerInfo(Arg0
),
7180 MachinePointerInfo(Arg1
));
7181 if (Res
.first
.getNode()) {
7182 processIntegerCallValue(I
, Res
.first
, true);
7183 PendingLoads
.push_back(Res
.second
);
7190 /// See if we can lower a strlen call into an optimized form. If so, return
7191 /// true and lower it, otherwise return false and it will be lowered like a
7193 /// The caller already checked that \p I calls the appropriate LibFunc with a
7194 /// correct prototype.
7195 bool SelectionDAGBuilder::visitStrLenCall(const CallInst
&I
) {
7196 const Value
*Arg0
= I
.getArgOperand(0);
7198 const SelectionDAGTargetInfo
&TSI
= DAG
.getSelectionDAGInfo();
7199 std::pair
<SDValue
, SDValue
> Res
=
7200 TSI
.EmitTargetCodeForStrlen(DAG
, getCurSDLoc(), DAG
.getRoot(),
7201 getValue(Arg0
), MachinePointerInfo(Arg0
));
7202 if (Res
.first
.getNode()) {
7203 processIntegerCallValue(I
, Res
.first
, false);
7204 PendingLoads
.push_back(Res
.second
);
7211 /// See if we can lower a strnlen call into an optimized form. If so, return
7212 /// true and lower it, otherwise return false and it will be lowered like a
7214 /// The caller already checked that \p I calls the appropriate LibFunc with a
7215 /// correct prototype.
7216 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst
&I
) {
7217 const Value
*Arg0
= I
.getArgOperand(0), *Arg1
= I
.getArgOperand(1);
7219 const SelectionDAGTargetInfo
&TSI
= DAG
.getSelectionDAGInfo();
7220 std::pair
<SDValue
, SDValue
> Res
=
7221 TSI
.EmitTargetCodeForStrnlen(DAG
, getCurSDLoc(), DAG
.getRoot(),
7222 getValue(Arg0
), getValue(Arg1
),
7223 MachinePointerInfo(Arg0
));
7224 if (Res
.first
.getNode()) {
7225 processIntegerCallValue(I
, Res
.first
, false);
7226 PendingLoads
.push_back(Res
.second
);
7233 /// See if we can lower a unary floating-point operation into an SDNode with
7234 /// the specified Opcode. If so, return true and lower it, otherwise return
7235 /// false and it will be lowered like a normal call.
7236 /// The caller already checked that \p I calls the appropriate LibFunc with a
7237 /// correct prototype.
7238 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst
&I
,
7240 // We already checked this call's prototype; verify it doesn't modify errno.
7241 if (!I
.onlyReadsMemory())
7244 SDValue Tmp
= getValue(I
.getArgOperand(0));
7245 setValue(&I
, DAG
.getNode(Opcode
, getCurSDLoc(), Tmp
.getValueType(), Tmp
));
7249 /// See if we can lower a binary floating-point operation into an SDNode with
7250 /// the specified Opcode. If so, return true and lower it. Otherwise return
7251 /// false, and it will be lowered like a normal call.
7252 /// The caller already checked that \p I calls the appropriate LibFunc with a
7253 /// correct prototype.
7254 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst
&I
,
7256 // We already checked this call's prototype; verify it doesn't modify errno.
7257 if (!I
.onlyReadsMemory())
7260 SDValue Tmp0
= getValue(I
.getArgOperand(0));
7261 SDValue Tmp1
= getValue(I
.getArgOperand(1));
7262 EVT VT
= Tmp0
.getValueType();
7263 setValue(&I
, DAG
.getNode(Opcode
, getCurSDLoc(), VT
, Tmp0
, Tmp1
));
7267 void SelectionDAGBuilder::visitCall(const CallInst
&I
) {
7268 // Handle inline assembly differently.
7269 if (isa
<InlineAsm
>(I
.getCalledValue())) {
7274 const char *RenameFn
= nullptr;
7275 if (Function
*F
= I
.getCalledFunction()) {
7276 if (F
->isDeclaration()) {
7277 // Is this an LLVM intrinsic or a target-specific intrinsic?
7278 unsigned IID
= F
->getIntrinsicID();
7280 if (const TargetIntrinsicInfo
*II
= TM
.getIntrinsicInfo())
7281 IID
= II
->getIntrinsicID(F
);
7284 RenameFn
= visitIntrinsicCall(I
, IID
);
7290 // Check for well-known libc/libm calls. If the function is internal, it
7291 // can't be a library call. Don't do the check if marked as nobuiltin for
7292 // some reason or the call site requires strict floating point semantics.
7294 if (!I
.isNoBuiltin() && !I
.isStrictFP() && !F
->hasLocalLinkage() &&
7295 F
->hasName() && LibInfo
->getLibFunc(*F
, Func
) &&
7296 LibInfo
->hasOptimizedCodeGen(Func
)) {
7299 case LibFunc_copysign
:
7300 case LibFunc_copysignf
:
7301 case LibFunc_copysignl
:
7302 // We already checked this call's prototype; verify it doesn't modify
7304 if (I
.onlyReadsMemory()) {
7305 SDValue LHS
= getValue(I
.getArgOperand(0));
7306 SDValue RHS
= getValue(I
.getArgOperand(1));
7307 setValue(&I
, DAG
.getNode(ISD::FCOPYSIGN
, getCurSDLoc(),
7308 LHS
.getValueType(), LHS
, RHS
));
7315 if (visitUnaryFloatCall(I
, ISD::FABS
))
7321 if (visitBinaryFloatCall(I
, ISD::FMINNUM
))
7327 if (visitBinaryFloatCall(I
, ISD::FMAXNUM
))
7333 if (visitUnaryFloatCall(I
, ISD::FSIN
))
7339 if (visitUnaryFloatCall(I
, ISD::FCOS
))
7345 case LibFunc_sqrt_finite
:
7346 case LibFunc_sqrtf_finite
:
7347 case LibFunc_sqrtl_finite
:
7348 if (visitUnaryFloatCall(I
, ISD::FSQRT
))
7352 case LibFunc_floorf
:
7353 case LibFunc_floorl
:
7354 if (visitUnaryFloatCall(I
, ISD::FFLOOR
))
7357 case LibFunc_nearbyint
:
7358 case LibFunc_nearbyintf
:
7359 case LibFunc_nearbyintl
:
7360 if (visitUnaryFloatCall(I
, ISD::FNEARBYINT
))
7366 if (visitUnaryFloatCall(I
, ISD::FCEIL
))
7372 if (visitUnaryFloatCall(I
, ISD::FRINT
))
7376 case LibFunc_roundf
:
7377 case LibFunc_roundl
:
7378 if (visitUnaryFloatCall(I
, ISD::FROUND
))
7382 case LibFunc_truncf
:
7383 case LibFunc_truncl
:
7384 if (visitUnaryFloatCall(I
, ISD::FTRUNC
))
7390 if (visitUnaryFloatCall(I
, ISD::FLOG2
))
7396 if (visitUnaryFloatCall(I
, ISD::FEXP2
))
7399 case LibFunc_memcmp
:
7400 if (visitMemCmpCall(I
))
7403 case LibFunc_mempcpy
:
7404 if (visitMemPCpyCall(I
))
7407 case LibFunc_memchr
:
7408 if (visitMemChrCall(I
))
7411 case LibFunc_strcpy
:
7412 if (visitStrCpyCall(I
, false))
7415 case LibFunc_stpcpy
:
7416 if (visitStrCpyCall(I
, true))
7419 case LibFunc_strcmp
:
7420 if (visitStrCmpCall(I
))
7423 case LibFunc_strlen
:
7424 if (visitStrLenCall(I
))
7427 case LibFunc_strnlen
:
7428 if (visitStrNLenCall(I
))
7437 Callee
= getValue(I
.getCalledValue());
7439 Callee
= DAG
.getExternalSymbol(
7441 DAG
.getTargetLoweringInfo().getPointerTy(DAG
.getDataLayout()));
7443 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7444 // have to do anything here to lower funclet bundles.
7445 assert(!I
.hasOperandBundlesOtherThan(
7446 {LLVMContext::OB_deopt
, LLVMContext::OB_funclet
}) &&
7447 "Cannot lower calls with arbitrary operand bundles!");
7449 if (I
.countOperandBundlesOfType(LLVMContext::OB_deopt
))
7450 LowerCallSiteWithDeoptBundle(&I
, Callee
, nullptr);
7452 // Check if we can potentially perform a tail call. More detailed checking
7453 // is be done within LowerCallTo, after more information about the call is
7455 LowerCallTo(&I
, Callee
, I
.isTailCall());
7460 /// AsmOperandInfo - This contains information for each constraint that we are
7462 class SDISelAsmOperandInfo
: public TargetLowering::AsmOperandInfo
{
7464 /// CallOperand - If this is the result output operand or a clobber
7465 /// this is null, otherwise it is the incoming operand to the CallInst.
7466 /// This gets modified as the asm is processed.
7467 SDValue CallOperand
;
7469 /// AssignedRegs - If this is a register or register class operand, this
7470 /// contains the set of register corresponding to the operand.
7471 RegsForValue AssignedRegs
;
7473 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo
&info
)
7474 : TargetLowering::AsmOperandInfo(info
), CallOperand(nullptr, 0) {
7477 /// Whether or not this operand accesses memory
7478 bool hasMemory(const TargetLowering
&TLI
) const {
7479 // Indirect operand accesses access memory.
7483 for (const auto &Code
: Codes
)
7484 if (TLI
.getConstraintType(Code
) == TargetLowering::C_Memory
)
7490 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7491 /// corresponds to. If there is no Value* for this operand, it returns
7493 EVT
getCallOperandValEVT(LLVMContext
&Context
, const TargetLowering
&TLI
,
7494 const DataLayout
&DL
) const {
7495 if (!CallOperandVal
) return MVT::Other
;
7497 if (isa
<BasicBlock
>(CallOperandVal
))
7498 return TLI
.getPointerTy(DL
);
7500 llvm::Type
*OpTy
= CallOperandVal
->getType();
7502 // FIXME: code duplicated from TargetLowering::ParseConstraints().
7503 // If this is an indirect operand, the operand is a pointer to the
7506 PointerType
*PtrTy
= dyn_cast
<PointerType
>(OpTy
);
7508 report_fatal_error("Indirect operand for inline asm not a pointer!");
7509 OpTy
= PtrTy
->getElementType();
7512 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7513 if (StructType
*STy
= dyn_cast
<StructType
>(OpTy
))
7514 if (STy
->getNumElements() == 1)
7515 OpTy
= STy
->getElementType(0);
7517 // If OpTy is not a single value, it may be a struct/union that we
7518 // can tile with integers.
7519 if (!OpTy
->isSingleValueType() && OpTy
->isSized()) {
7520 unsigned BitSize
= DL
.getTypeSizeInBits(OpTy
);
7529 OpTy
= IntegerType::get(Context
, BitSize
);
7534 return TLI
.getValueType(DL
, OpTy
, true);
7538 using SDISelAsmOperandInfoVector
= SmallVector
<SDISelAsmOperandInfo
, 16>;
7540 } // end anonymous namespace
7542 /// Make sure that the output operand \p OpInfo and its corresponding input
7543 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7545 static void patchMatchingInput(const SDISelAsmOperandInfo
&OpInfo
,
7546 SDISelAsmOperandInfo
&MatchingOpInfo
,
7547 SelectionDAG
&DAG
) {
7548 if (OpInfo
.ConstraintVT
== MatchingOpInfo
.ConstraintVT
)
7551 const TargetRegisterInfo
*TRI
= DAG
.getSubtarget().getRegisterInfo();
7552 const auto &TLI
= DAG
.getTargetLoweringInfo();
7554 std::pair
<unsigned, const TargetRegisterClass
*> MatchRC
=
7555 TLI
.getRegForInlineAsmConstraint(TRI
, OpInfo
.ConstraintCode
,
7556 OpInfo
.ConstraintVT
);
7557 std::pair
<unsigned, const TargetRegisterClass
*> InputRC
=
7558 TLI
.getRegForInlineAsmConstraint(TRI
, MatchingOpInfo
.ConstraintCode
,
7559 MatchingOpInfo
.ConstraintVT
);
7560 if ((OpInfo
.ConstraintVT
.isInteger() !=
7561 MatchingOpInfo
.ConstraintVT
.isInteger()) ||
7562 (MatchRC
.second
!= InputRC
.second
)) {
7563 // FIXME: error out in a more elegant fashion
7564 report_fatal_error("Unsupported asm: input constraint"
7565 " with a matching output constraint of"
7566 " incompatible type!");
7568 MatchingOpInfo
.ConstraintVT
= OpInfo
.ConstraintVT
;
7571 /// Get a direct memory input to behave well as an indirect operand.
7572 /// This may introduce stores, hence the need for a \p Chain.
7573 /// \return The (possibly updated) chain.
7574 static SDValue
getAddressForMemoryInput(SDValue Chain
, const SDLoc
&Location
,
7575 SDISelAsmOperandInfo
&OpInfo
,
7576 SelectionDAG
&DAG
) {
7577 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
7579 // If we don't have an indirect input, put it in the constpool if we can,
7580 // otherwise spill it to a stack slot.
7581 // TODO: This isn't quite right. We need to handle these according to
7582 // the addressing mode that the constraint wants. Also, this may take
7583 // an additional register for the computation and we don't want that
7586 // If the operand is a float, integer, or vector constant, spill to a
7587 // constant pool entry to get its address.
7588 const Value
*OpVal
= OpInfo
.CallOperandVal
;
7589 if (isa
<ConstantFP
>(OpVal
) || isa
<ConstantInt
>(OpVal
) ||
7590 isa
<ConstantVector
>(OpVal
) || isa
<ConstantDataVector
>(OpVal
)) {
7591 OpInfo
.CallOperand
= DAG
.getConstantPool(
7592 cast
<Constant
>(OpVal
), TLI
.getPointerTy(DAG
.getDataLayout()));
7596 // Otherwise, create a stack slot and emit a store to it before the asm.
7597 Type
*Ty
= OpVal
->getType();
7598 auto &DL
= DAG
.getDataLayout();
7599 uint64_t TySize
= DL
.getTypeAllocSize(Ty
);
7600 unsigned Align
= DL
.getPrefTypeAlignment(Ty
);
7601 MachineFunction
&MF
= DAG
.getMachineFunction();
7602 int SSFI
= MF
.getFrameInfo().CreateStackObject(TySize
, Align
, false);
7603 SDValue StackSlot
= DAG
.getFrameIndex(SSFI
, TLI
.getFrameIndexTy(DL
));
7604 Chain
= DAG
.getStore(Chain
, Location
, OpInfo
.CallOperand
, StackSlot
,
7605 MachinePointerInfo::getFixedStack(MF
, SSFI
));
7606 OpInfo
.CallOperand
= StackSlot
;
7611 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7612 /// specified operand. We prefer to assign virtual registers, to allow the
7613 /// register allocator to handle the assignment process. However, if the asm
7614 /// uses features that we can't model on machineinstrs, we have SDISel do the
7615 /// allocation. This produces generally horrible, but correct, code.
7617 /// OpInfo describes the operand
7618 /// RefOpInfo describes the matching operand if any, the operand otherwise
7619 static void GetRegistersForValue(SelectionDAG
&DAG
, const SDLoc
&DL
,
7620 SDISelAsmOperandInfo
&OpInfo
,
7621 SDISelAsmOperandInfo
&RefOpInfo
) {
7622 LLVMContext
&Context
= *DAG
.getContext();
7623 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
7625 MachineFunction
&MF
= DAG
.getMachineFunction();
7626 SmallVector
<unsigned, 4> Regs
;
7627 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
7629 // No work to do for memory operations.
7630 if (OpInfo
.ConstraintType
== TargetLowering::C_Memory
)
7633 // If this is a constraint for a single physreg, or a constraint for a
7634 // register class, find it.
7635 unsigned AssignedReg
;
7636 const TargetRegisterClass
*RC
;
7637 std::tie(AssignedReg
, RC
) = TLI
.getRegForInlineAsmConstraint(
7638 &TRI
, RefOpInfo
.ConstraintCode
, RefOpInfo
.ConstraintVT
);
7639 // RC is unset only on failure. Return immediately.
7643 // Get the actual register value type. This is important, because the user
7644 // may have asked for (e.g.) the AX register in i32 type. We need to
7645 // remember that AX is actually i16 to get the right extension.
7646 const MVT RegVT
= *TRI
.legalclasstypes_begin(*RC
);
7648 if (OpInfo
.ConstraintVT
!= MVT::Other
) {
7649 // If this is an FP operand in an integer register (or visa versa), or more
7650 // generally if the operand value disagrees with the register class we plan
7651 // to stick it in, fix the operand type.
7653 // If this is an input value, the bitcast to the new type is done now.
7654 // Bitcast for output value is done at the end of visitInlineAsm().
7655 if ((OpInfo
.Type
== InlineAsm::isOutput
||
7656 OpInfo
.Type
== InlineAsm::isInput
) &&
7657 !TRI
.isTypeLegalForClass(*RC
, OpInfo
.ConstraintVT
)) {
7658 // Try to convert to the first EVT that the reg class contains. If the
7659 // types are identical size, use a bitcast to convert (e.g. two differing
7660 // vector types). Note: output bitcast is done at the end of
7661 // visitInlineAsm().
7662 if (RegVT
.getSizeInBits() == OpInfo
.ConstraintVT
.getSizeInBits()) {
7663 // Exclude indirect inputs while they are unsupported because the code
7664 // to perform the load is missing and thus OpInfo.CallOperand still
7665 // refers to the input address rather than the pointed-to value.
7666 if (OpInfo
.Type
== InlineAsm::isInput
&& !OpInfo
.isIndirect
)
7667 OpInfo
.CallOperand
=
7668 DAG
.getNode(ISD::BITCAST
, DL
, RegVT
, OpInfo
.CallOperand
);
7669 OpInfo
.ConstraintVT
= RegVT
;
7670 // If the operand is an FP value and we want it in integer registers,
7671 // use the corresponding integer type. This turns an f64 value into
7672 // i64, which can be passed with two i32 values on a 32-bit machine.
7673 } else if (RegVT
.isInteger() && OpInfo
.ConstraintVT
.isFloatingPoint()) {
7674 MVT VT
= MVT::getIntegerVT(OpInfo
.ConstraintVT
.getSizeInBits());
7675 if (OpInfo
.Type
== InlineAsm::isInput
)
7676 OpInfo
.CallOperand
=
7677 DAG
.getNode(ISD::BITCAST
, DL
, VT
, OpInfo
.CallOperand
);
7678 OpInfo
.ConstraintVT
= VT
;
7683 // No need to allocate a matching input constraint since the constraint it's
7684 // matching to has already been allocated.
7685 if (OpInfo
.isMatchingInputConstraint())
7688 EVT ValueVT
= OpInfo
.ConstraintVT
;
7689 if (OpInfo
.ConstraintVT
== MVT::Other
)
7692 // Initialize NumRegs.
7693 unsigned NumRegs
= 1;
7694 if (OpInfo
.ConstraintVT
!= MVT::Other
)
7695 NumRegs
= TLI
.getNumRegisters(Context
, OpInfo
.ConstraintVT
);
7697 // If this is a constraint for a specific physical register, like {r17},
7700 // If this associated to a specific register, initialize iterator to correct
7701 // place. If virtual, make sure we have enough registers
7703 // Initialize iterator if necessary
7704 TargetRegisterClass::iterator I
= RC
->begin();
7705 MachineRegisterInfo
&RegInfo
= MF
.getRegInfo();
7707 // Do not check for single registers.
7709 for (; *I
!= AssignedReg
; ++I
)
7710 assert(I
!= RC
->end() && "AssignedReg should be member of RC");
7713 for (; NumRegs
; --NumRegs
, ++I
) {
7714 assert(I
!= RC
->end() && "Ran out of registers to allocate!");
7715 auto R
= (AssignedReg
) ? *I
: RegInfo
.createVirtualRegister(RC
);
7719 OpInfo
.AssignedRegs
= RegsForValue(Regs
, RegVT
, ValueVT
);
7723 findMatchingInlineAsmOperand(unsigned OperandNo
,
7724 const std::vector
<SDValue
> &AsmNodeOperands
) {
7725 // Scan until we find the definition we already emitted of this operand.
7726 unsigned CurOp
= InlineAsm::Op_FirstOperand
;
7727 for (; OperandNo
; --OperandNo
) {
7728 // Advance to the next operand.
7730 cast
<ConstantSDNode
>(AsmNodeOperands
[CurOp
])->getZExtValue();
7731 assert((InlineAsm::isRegDefKind(OpFlag
) ||
7732 InlineAsm::isRegDefEarlyClobberKind(OpFlag
) ||
7733 InlineAsm::isMemKind(OpFlag
)) &&
7734 "Skipped past definitions?");
7735 CurOp
+= InlineAsm::getNumOperandRegisters(OpFlag
) + 1;
7746 explicit ExtraFlags(ImmutableCallSite CS
) {
7747 const InlineAsm
*IA
= cast
<InlineAsm
>(CS
.getCalledValue());
7748 if (IA
->hasSideEffects())
7749 Flags
|= InlineAsm::Extra_HasSideEffects
;
7750 if (IA
->isAlignStack())
7751 Flags
|= InlineAsm::Extra_IsAlignStack
;
7752 if (CS
.isConvergent())
7753 Flags
|= InlineAsm::Extra_IsConvergent
;
7754 Flags
|= IA
->getDialect() * InlineAsm::Extra_AsmDialect
;
7757 void update(const TargetLowering::AsmOperandInfo
&OpInfo
) {
7758 // Ideally, we would only check against memory constraints. However, the
7759 // meaning of an Other constraint can be target-specific and we can't easily
7760 // reason about it. Therefore, be conservative and set MayLoad/MayStore
7761 // for Other constraints as well.
7762 if (OpInfo
.ConstraintType
== TargetLowering::C_Memory
||
7763 OpInfo
.ConstraintType
== TargetLowering::C_Other
) {
7764 if (OpInfo
.Type
== InlineAsm::isInput
)
7765 Flags
|= InlineAsm::Extra_MayLoad
;
7766 else if (OpInfo
.Type
== InlineAsm::isOutput
)
7767 Flags
|= InlineAsm::Extra_MayStore
;
7768 else if (OpInfo
.Type
== InlineAsm::isClobber
)
7769 Flags
|= (InlineAsm::Extra_MayLoad
| InlineAsm::Extra_MayStore
);
7773 unsigned get() const { return Flags
; }
7776 } // end anonymous namespace
7778 /// visitInlineAsm - Handle a call to an InlineAsm object.
7779 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS
) {
7780 const InlineAsm
*IA
= cast
<InlineAsm
>(CS
.getCalledValue());
7782 /// ConstraintOperands - Information about all of the constraints.
7783 SDISelAsmOperandInfoVector ConstraintOperands
;
7785 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
7786 TargetLowering::AsmOperandInfoVector TargetConstraints
= TLI
.ParseConstraints(
7787 DAG
.getDataLayout(), DAG
.getSubtarget().getRegisterInfo(), CS
);
7789 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7790 // AsmDialect, MayLoad, MayStore).
7791 bool HasSideEffect
= IA
->hasSideEffects();
7792 ExtraFlags
ExtraInfo(CS
);
7794 unsigned ArgNo
= 0; // ArgNo - The argument of the CallInst.
7795 unsigned ResNo
= 0; // ResNo - The result number of the next output.
7796 for (auto &T
: TargetConstraints
) {
7797 ConstraintOperands
.push_back(SDISelAsmOperandInfo(T
));
7798 SDISelAsmOperandInfo
&OpInfo
= ConstraintOperands
.back();
7800 // Compute the value type for each operand.
7801 if (OpInfo
.Type
== InlineAsm::isInput
||
7802 (OpInfo
.Type
== InlineAsm::isOutput
&& OpInfo
.isIndirect
)) {
7803 OpInfo
.CallOperandVal
= const_cast<Value
*>(CS
.getArgument(ArgNo
++));
7805 // Process the call argument. BasicBlocks are labels, currently appearing
7807 const Instruction
*I
= CS
.getInstruction();
7808 if (isa
<CallBrInst
>(I
) &&
7809 (ArgNo
- 1) >= (cast
<CallBrInst
>(I
)->getNumArgOperands() -
7810 cast
<CallBrInst
>(I
)->getNumIndirectDests())) {
7811 const auto *BA
= cast
<BlockAddress
>(OpInfo
.CallOperandVal
);
7812 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), BA
->getType(), true);
7813 OpInfo
.CallOperand
= DAG
.getTargetBlockAddress(BA
, VT
);
7814 } else if (const auto *BB
= dyn_cast
<BasicBlock
>(OpInfo
.CallOperandVal
)) {
7815 OpInfo
.CallOperand
= DAG
.getBasicBlock(FuncInfo
.MBBMap
[BB
]);
7817 OpInfo
.CallOperand
= getValue(OpInfo
.CallOperandVal
);
7820 OpInfo
.ConstraintVT
=
7822 .getCallOperandValEVT(*DAG
.getContext(), TLI
, DAG
.getDataLayout())
7824 } else if (OpInfo
.Type
== InlineAsm::isOutput
&& !OpInfo
.isIndirect
) {
7825 // The return value of the call is this value. As such, there is no
7826 // corresponding argument.
7827 assert(!CS
.getType()->isVoidTy() && "Bad inline asm!");
7828 if (StructType
*STy
= dyn_cast
<StructType
>(CS
.getType())) {
7829 OpInfo
.ConstraintVT
= TLI
.getSimpleValueType(
7830 DAG
.getDataLayout(), STy
->getElementType(ResNo
));
7832 assert(ResNo
== 0 && "Asm only has one result!");
7833 OpInfo
.ConstraintVT
=
7834 TLI
.getSimpleValueType(DAG
.getDataLayout(), CS
.getType());
7838 OpInfo
.ConstraintVT
= MVT::Other
;
7842 HasSideEffect
= OpInfo
.hasMemory(TLI
);
7844 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7845 // FIXME: Could we compute this on OpInfo rather than T?
7847 // Compute the constraint code and ConstraintType to use.
7848 TLI
.ComputeConstraintToUse(T
, SDValue());
7850 ExtraInfo
.update(T
);
7853 // We won't need to flush pending loads if this asm doesn't touch
7854 // memory and is nonvolatile.
7855 SDValue Flag
, Chain
= (HasSideEffect
) ? getRoot() : DAG
.getRoot();
7857 // Second pass over the constraints: compute which constraint option to use.
7858 for (SDISelAsmOperandInfo
&OpInfo
: ConstraintOperands
) {
7859 // If this is an output operand with a matching input operand, look up the
7860 // matching input. If their types mismatch, e.g. one is an integer, the
7861 // other is floating point, or their sizes are different, flag it as an
7863 if (OpInfo
.hasMatchingInput()) {
7864 SDISelAsmOperandInfo
&Input
= ConstraintOperands
[OpInfo
.MatchingInput
];
7865 patchMatchingInput(OpInfo
, Input
, DAG
);
7868 // Compute the constraint code and ConstraintType to use.
7869 TLI
.ComputeConstraintToUse(OpInfo
, OpInfo
.CallOperand
, &DAG
);
7871 if (OpInfo
.ConstraintType
== TargetLowering::C_Memory
&&
7872 OpInfo
.Type
== InlineAsm::isClobber
)
7875 // If this is a memory input, and if the operand is not indirect, do what we
7876 // need to provide an address for the memory input.
7877 if (OpInfo
.ConstraintType
== TargetLowering::C_Memory
&&
7878 !OpInfo
.isIndirect
) {
7879 assert((OpInfo
.isMultipleAlternative
||
7880 (OpInfo
.Type
== InlineAsm::isInput
)) &&
7881 "Can only indirectify direct input operands!");
7883 // Memory operands really want the address of the value.
7884 Chain
= getAddressForMemoryInput(Chain
, getCurSDLoc(), OpInfo
, DAG
);
7886 // There is no longer a Value* corresponding to this operand.
7887 OpInfo
.CallOperandVal
= nullptr;
7889 // It is now an indirect operand.
7890 OpInfo
.isIndirect
= true;
7895 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7896 std::vector
<SDValue
> AsmNodeOperands
;
7897 AsmNodeOperands
.push_back(SDValue()); // reserve space for input chain
7898 AsmNodeOperands
.push_back(DAG
.getTargetExternalSymbol(
7899 IA
->getAsmString().c_str(), TLI
.getPointerTy(DAG
.getDataLayout())));
7901 // If we have a !srcloc metadata node associated with it, we want to attach
7902 // this to the ultimately generated inline asm machineinstr. To do this, we
7903 // pass in the third operand as this (potentially null) inline asm MDNode.
7904 const MDNode
*SrcLoc
= CS
.getInstruction()->getMetadata("srcloc");
7905 AsmNodeOperands
.push_back(DAG
.getMDNode(SrcLoc
));
7907 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7908 // bits as operand 3.
7909 AsmNodeOperands
.push_back(DAG
.getTargetConstant(
7910 ExtraInfo
.get(), getCurSDLoc(), TLI
.getPointerTy(DAG
.getDataLayout())));
7912 // Third pass: Loop over operands to prepare DAG-level operands.. As part of
7913 // this, assign virtual and physical registers for inputs and otput.
7914 for (SDISelAsmOperandInfo
&OpInfo
: ConstraintOperands
) {
7915 // Assign Registers.
7916 SDISelAsmOperandInfo
&RefOpInfo
=
7917 OpInfo
.isMatchingInputConstraint()
7918 ? ConstraintOperands
[OpInfo
.getMatchedOperand()]
7920 GetRegistersForValue(DAG
, getCurSDLoc(), OpInfo
, RefOpInfo
);
7922 switch (OpInfo
.Type
) {
7923 case InlineAsm::isOutput
:
7924 if (OpInfo
.ConstraintType
== TargetLowering::C_Memory
||
7925 (OpInfo
.ConstraintType
== TargetLowering::C_Other
&&
7926 OpInfo
.isIndirect
)) {
7927 unsigned ConstraintID
=
7928 TLI
.getInlineAsmMemConstraint(OpInfo
.ConstraintCode
);
7929 assert(ConstraintID
!= InlineAsm::Constraint_Unknown
&&
7930 "Failed to convert memory constraint code to constraint id.");
7932 // Add information to the INLINEASM node to know about this output.
7933 unsigned OpFlags
= InlineAsm::getFlagWord(InlineAsm::Kind_Mem
, 1);
7934 OpFlags
= InlineAsm::getFlagWordForMem(OpFlags
, ConstraintID
);
7935 AsmNodeOperands
.push_back(DAG
.getTargetConstant(OpFlags
, getCurSDLoc(),
7937 AsmNodeOperands
.push_back(OpInfo
.CallOperand
);
7939 } else if ((OpInfo
.ConstraintType
== TargetLowering::C_Other
&&
7940 !OpInfo
.isIndirect
) ||
7941 OpInfo
.ConstraintType
== TargetLowering::C_Register
||
7942 OpInfo
.ConstraintType
== TargetLowering::C_RegisterClass
) {
7943 // Otherwise, this outputs to a register (directly for C_Register /
7944 // C_RegisterClass, and a target-defined fashion for C_Other). Find a
7945 // register that we can use.
7946 if (OpInfo
.AssignedRegs
.Regs
.empty()) {
7948 CS
, "couldn't allocate output register for constraint '" +
7949 Twine(OpInfo
.ConstraintCode
) + "'");
7953 // Add information to the INLINEASM node to know that this register is
7955 OpInfo
.AssignedRegs
.AddInlineAsmOperands(
7956 OpInfo
.isEarlyClobber
? InlineAsm::Kind_RegDefEarlyClobber
7957 : InlineAsm::Kind_RegDef
,
7958 false, 0, getCurSDLoc(), DAG
, AsmNodeOperands
);
7962 case InlineAsm::isInput
: {
7963 SDValue InOperandVal
= OpInfo
.CallOperand
;
7965 if (OpInfo
.isMatchingInputConstraint()) {
7966 // If this is required to match an output register we have already set,
7967 // just use its register.
7968 auto CurOp
= findMatchingInlineAsmOperand(OpInfo
.getMatchedOperand(),
7971 cast
<ConstantSDNode
>(AsmNodeOperands
[CurOp
])->getZExtValue();
7972 if (InlineAsm::isRegDefKind(OpFlag
) ||
7973 InlineAsm::isRegDefEarlyClobberKind(OpFlag
)) {
7974 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7975 if (OpInfo
.isIndirect
) {
7976 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7977 emitInlineAsmError(CS
, "inline asm not supported yet:"
7978 " don't know how to handle tied "
7979 "indirect register inputs");
7983 MVT RegVT
= AsmNodeOperands
[CurOp
+1].getSimpleValueType();
7984 SmallVector
<unsigned, 4> Regs
;
7986 if (const TargetRegisterClass
*RC
= TLI
.getRegClassFor(RegVT
)) {
7987 unsigned NumRegs
= InlineAsm::getNumOperandRegisters(OpFlag
);
7988 MachineRegisterInfo
&RegInfo
=
7989 DAG
.getMachineFunction().getRegInfo();
7990 for (unsigned i
= 0; i
!= NumRegs
; ++i
)
7991 Regs
.push_back(RegInfo
.createVirtualRegister(RC
));
7993 emitInlineAsmError(CS
, "inline asm error: This value type register "
7994 "class is not natively supported!");
7998 RegsForValue
MatchedRegs(Regs
, RegVT
, InOperandVal
.getValueType());
8000 SDLoc dl
= getCurSDLoc();
8001 // Use the produced MatchedRegs object to
8002 MatchedRegs
.getCopyToRegs(InOperandVal
, DAG
, dl
, Chain
, &Flag
,
8003 CS
.getInstruction());
8004 MatchedRegs
.AddInlineAsmOperands(InlineAsm::Kind_RegUse
,
8005 true, OpInfo
.getMatchedOperand(), dl
,
8006 DAG
, AsmNodeOperands
);
8010 assert(InlineAsm::isMemKind(OpFlag
) && "Unknown matching constraint!");
8011 assert(InlineAsm::getNumOperandRegisters(OpFlag
) == 1 &&
8012 "Unexpected number of operands");
8013 // Add information to the INLINEASM node to know about this input.
8014 // See InlineAsm.h isUseOperandTiedToDef.
8015 OpFlag
= InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag
);
8016 OpFlag
= InlineAsm::getFlagWordForMatchingOp(OpFlag
,
8017 OpInfo
.getMatchedOperand());
8018 AsmNodeOperands
.push_back(DAG
.getTargetConstant(
8019 OpFlag
, getCurSDLoc(), TLI
.getPointerTy(DAG
.getDataLayout())));
8020 AsmNodeOperands
.push_back(AsmNodeOperands
[CurOp
+1]);
8024 // Treat indirect 'X' constraint as memory.
8025 if (OpInfo
.ConstraintType
== TargetLowering::C_Other
&&
8027 OpInfo
.ConstraintType
= TargetLowering::C_Memory
;
8029 if (OpInfo
.ConstraintType
== TargetLowering::C_Other
) {
8030 std::vector
<SDValue
> Ops
;
8031 TLI
.LowerAsmOperandForConstraint(InOperandVal
, OpInfo
.ConstraintCode
,
8034 emitInlineAsmError(CS
, "invalid operand for inline asm constraint '" +
8035 Twine(OpInfo
.ConstraintCode
) + "'");
8039 // Add information to the INLINEASM node to know about this input.
8040 unsigned ResOpType
=
8041 InlineAsm::getFlagWord(InlineAsm::Kind_Imm
, Ops
.size());
8042 AsmNodeOperands
.push_back(DAG
.getTargetConstant(
8043 ResOpType
, getCurSDLoc(), TLI
.getPointerTy(DAG
.getDataLayout())));
8044 AsmNodeOperands
.insert(AsmNodeOperands
.end(), Ops
.begin(), Ops
.end());
8048 if (OpInfo
.ConstraintType
== TargetLowering::C_Memory
) {
8049 assert(OpInfo
.isIndirect
&& "Operand must be indirect to be a mem!");
8050 assert(InOperandVal
.getValueType() ==
8051 TLI
.getPointerTy(DAG
.getDataLayout()) &&
8052 "Memory operands expect pointer values");
8054 unsigned ConstraintID
=
8055 TLI
.getInlineAsmMemConstraint(OpInfo
.ConstraintCode
);
8056 assert(ConstraintID
!= InlineAsm::Constraint_Unknown
&&
8057 "Failed to convert memory constraint code to constraint id.");
8059 // Add information to the INLINEASM node to know about this input.
8060 unsigned ResOpType
= InlineAsm::getFlagWord(InlineAsm::Kind_Mem
, 1);
8061 ResOpType
= InlineAsm::getFlagWordForMem(ResOpType
, ConstraintID
);
8062 AsmNodeOperands
.push_back(DAG
.getTargetConstant(ResOpType
,
8065 AsmNodeOperands
.push_back(InOperandVal
);
8069 assert((OpInfo
.ConstraintType
== TargetLowering::C_RegisterClass
||
8070 OpInfo
.ConstraintType
== TargetLowering::C_Register
) &&
8071 "Unknown constraint type!");
8073 // TODO: Support this.
8074 if (OpInfo
.isIndirect
) {
8076 CS
, "Don't know how to handle indirect register inputs yet "
8077 "for constraint '" +
8078 Twine(OpInfo
.ConstraintCode
) + "'");
8082 // Copy the input into the appropriate registers.
8083 if (OpInfo
.AssignedRegs
.Regs
.empty()) {
8084 emitInlineAsmError(CS
, "couldn't allocate input reg for constraint '" +
8085 Twine(OpInfo
.ConstraintCode
) + "'");
8089 SDLoc dl
= getCurSDLoc();
8091 OpInfo
.AssignedRegs
.getCopyToRegs(InOperandVal
, DAG
, dl
,
8092 Chain
, &Flag
, CS
.getInstruction());
8094 OpInfo
.AssignedRegs
.AddInlineAsmOperands(InlineAsm::Kind_RegUse
, false, 0,
8095 dl
, DAG
, AsmNodeOperands
);
8098 case InlineAsm::isClobber
:
8099 // Add the clobbered value to the operand list, so that the register
8100 // allocator is aware that the physreg got clobbered.
8101 if (!OpInfo
.AssignedRegs
.Regs
.empty())
8102 OpInfo
.AssignedRegs
.AddInlineAsmOperands(InlineAsm::Kind_Clobber
,
8103 false, 0, getCurSDLoc(), DAG
,
8109 // Finish up input operands. Set the input chain and add the flag last.
8110 AsmNodeOperands
[InlineAsm::Op_InputChain
] = Chain
;
8111 if (Flag
.getNode()) AsmNodeOperands
.push_back(Flag
);
8113 unsigned ISDOpc
= isa
<CallBrInst
>(CS
.getInstruction()) ? ISD::INLINEASM_BR
: ISD::INLINEASM
;
8114 Chain
= DAG
.getNode(ISDOpc
, getCurSDLoc(),
8115 DAG
.getVTList(MVT::Other
, MVT::Glue
), AsmNodeOperands
);
8116 Flag
= Chain
.getValue(1);
8118 // Do additional work to generate outputs.
8120 SmallVector
<EVT
, 1> ResultVTs
;
8121 SmallVector
<SDValue
, 1> ResultValues
;
8122 SmallVector
<SDValue
, 8> OutChains
;
8124 llvm::Type
*CSResultType
= CS
.getType();
8125 ArrayRef
<Type
*> ResultTypes
;
8126 if (StructType
*StructResult
= dyn_cast
<StructType
>(CSResultType
))
8127 ResultTypes
= StructResult
->elements();
8128 else if (!CSResultType
->isVoidTy())
8129 ResultTypes
= makeArrayRef(CSResultType
);
8131 auto CurResultType
= ResultTypes
.begin();
8132 auto handleRegAssign
= [&](SDValue V
) {
8133 assert(CurResultType
!= ResultTypes
.end() && "Unexpected value");
8134 assert((*CurResultType
)->isSized() && "Unexpected unsized type");
8135 EVT ResultVT
= TLI
.getValueType(DAG
.getDataLayout(), *CurResultType
);
8137 // If the type of the inline asm call site return value is different but has
8138 // same size as the type of the asm output bitcast it. One example of this
8139 // is for vectors with different width / number of elements. This can
8140 // happen for register classes that can contain multiple different value
8141 // types. The preg or vreg allocated may not have the same VT as was
8144 // This can also happen for a return value that disagrees with the register
8145 // class it is put in, eg. a double in a general-purpose register on a
8147 if (ResultVT
!= V
.getValueType() &&
8148 ResultVT
.getSizeInBits() == V
.getValueSizeInBits())
8149 V
= DAG
.getNode(ISD::BITCAST
, getCurSDLoc(), ResultVT
, V
);
8150 else if (ResultVT
!= V
.getValueType() && ResultVT
.isInteger() &&
8151 V
.getValueType().isInteger()) {
8152 // If a result value was tied to an input value, the computed result
8153 // may have a wider width than the expected result. Extract the
8154 // relevant portion.
8155 V
= DAG
.getNode(ISD::TRUNCATE
, getCurSDLoc(), ResultVT
, V
);
8157 assert(ResultVT
== V
.getValueType() && "Asm result value mismatch!");
8158 ResultVTs
.push_back(ResultVT
);
8159 ResultValues
.push_back(V
);
8162 // Deal with output operands.
8163 for (SDISelAsmOperandInfo
&OpInfo
: ConstraintOperands
) {
8164 if (OpInfo
.Type
== InlineAsm::isOutput
) {
8166 // Skip trivial output operands.
8167 if (OpInfo
.AssignedRegs
.Regs
.empty())
8170 switch (OpInfo
.ConstraintType
) {
8171 case TargetLowering::C_Register
:
8172 case TargetLowering::C_RegisterClass
:
8173 Val
= OpInfo
.AssignedRegs
.getCopyFromRegs(
8174 DAG
, FuncInfo
, getCurSDLoc(), Chain
, &Flag
, CS
.getInstruction());
8176 case TargetLowering::C_Other
:
8177 Val
= TLI
.LowerAsmOutputForConstraint(Chain
, Flag
, getCurSDLoc(),
8180 case TargetLowering::C_Memory
:
8181 break; // Already handled.
8182 case TargetLowering::C_Unknown
:
8183 assert(false && "Unexpected unknown constraint");
8186 // Indirect output manifest as stores. Record output chains.
8187 if (OpInfo
.isIndirect
) {
8188 const Value
*Ptr
= OpInfo
.CallOperandVal
;
8189 assert(Ptr
&& "Expected value CallOperandVal for indirect asm operand");
8190 SDValue Store
= DAG
.getStore(Chain
, getCurSDLoc(), Val
, getValue(Ptr
),
8191 MachinePointerInfo(Ptr
));
8192 OutChains
.push_back(Store
);
8194 // generate CopyFromRegs to associated registers.
8195 assert(!CS
.getType()->isVoidTy() && "Bad inline asm!");
8196 if (Val
.getOpcode() == ISD::MERGE_VALUES
) {
8197 for (const SDValue
&V
: Val
->op_values())
8200 handleRegAssign(Val
);
8206 if (!ResultValues
.empty()) {
8207 assert(CurResultType
== ResultTypes
.end() &&
8208 "Mismatch in number of ResultTypes");
8209 assert(ResultValues
.size() == ResultTypes
.size() &&
8210 "Mismatch in number of output operands in asm result");
8212 SDValue V
= DAG
.getNode(ISD::MERGE_VALUES
, getCurSDLoc(),
8213 DAG
.getVTList(ResultVTs
), ResultValues
);
8214 setValue(CS
.getInstruction(), V
);
8217 // Collect store chains.
8218 if (!OutChains
.empty())
8219 Chain
= DAG
.getNode(ISD::TokenFactor
, getCurSDLoc(), MVT::Other
, OutChains
);
8221 // Only Update Root if inline assembly has a memory effect.
8222 if (ResultValues
.empty() || HasSideEffect
|| !OutChains
.empty())
8226 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS
,
8227 const Twine
&Message
) {
8228 LLVMContext
&Ctx
= *DAG
.getContext();
8229 Ctx
.emitError(CS
.getInstruction(), Message
);
8231 // Make sure we leave the DAG in a valid state
8232 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
8233 SmallVector
<EVT
, 1> ValueVTs
;
8234 ComputeValueVTs(TLI
, DAG
.getDataLayout(), CS
->getType(), ValueVTs
);
8236 if (ValueVTs
.empty())
8239 SmallVector
<SDValue
, 1> Ops
;
8240 for (unsigned i
= 0, e
= ValueVTs
.size(); i
!= e
; ++i
)
8241 Ops
.push_back(DAG
.getUNDEF(ValueVTs
[i
]));
8243 setValue(CS
.getInstruction(), DAG
.getMergeValues(Ops
, getCurSDLoc()));
8246 void SelectionDAGBuilder::visitVAStart(const CallInst
&I
) {
8247 DAG
.setRoot(DAG
.getNode(ISD::VASTART
, getCurSDLoc(),
8248 MVT::Other
, getRoot(),
8249 getValue(I
.getArgOperand(0)),
8250 DAG
.getSrcValue(I
.getArgOperand(0))));
8253 void SelectionDAGBuilder::visitVAArg(const VAArgInst
&I
) {
8254 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
8255 const DataLayout
&DL
= DAG
.getDataLayout();
8256 SDValue V
= DAG
.getVAArg(TLI
.getValueType(DAG
.getDataLayout(), I
.getType()),
8257 getCurSDLoc(), getRoot(), getValue(I
.getOperand(0)),
8258 DAG
.getSrcValue(I
.getOperand(0)),
8259 DL
.getABITypeAlignment(I
.getType()));
8261 DAG
.setRoot(V
.getValue(1));
8264 void SelectionDAGBuilder::visitVAEnd(const CallInst
&I
) {
8265 DAG
.setRoot(DAG
.getNode(ISD::VAEND
, getCurSDLoc(),
8266 MVT::Other
, getRoot(),
8267 getValue(I
.getArgOperand(0)),
8268 DAG
.getSrcValue(I
.getArgOperand(0))));
8271 void SelectionDAGBuilder::visitVACopy(const CallInst
&I
) {
8272 DAG
.setRoot(DAG
.getNode(ISD::VACOPY
, getCurSDLoc(),
8273 MVT::Other
, getRoot(),
8274 getValue(I
.getArgOperand(0)),
8275 getValue(I
.getArgOperand(1)),
8276 DAG
.getSrcValue(I
.getArgOperand(0)),
8277 DAG
.getSrcValue(I
.getArgOperand(1))));
8280 SDValue
SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG
&DAG
,
8281 const Instruction
&I
,
8283 const MDNode
*Range
= I
.getMetadata(LLVMContext::MD_range
);
8287 ConstantRange CR
= getConstantRangeFromMetadata(*Range
);
8288 if (CR
.isFullSet() || CR
.isEmptySet() || CR
.isWrappedSet())
8291 APInt Lo
= CR
.getUnsignedMin();
8292 if (!Lo
.isMinValue())
8295 APInt Hi
= CR
.getUnsignedMax();
8296 unsigned Bits
= std::max(Hi
.getActiveBits(),
8297 static_cast<unsigned>(IntegerType::MIN_INT_BITS
));
8299 EVT SmallVT
= EVT::getIntegerVT(*DAG
.getContext(), Bits
);
8301 SDLoc SL
= getCurSDLoc();
8303 SDValue ZExt
= DAG
.getNode(ISD::AssertZext
, SL
, Op
.getValueType(), Op
,
8304 DAG
.getValueType(SmallVT
));
8305 unsigned NumVals
= Op
.getNode()->getNumValues();
8309 SmallVector
<SDValue
, 4> Ops
;
8311 Ops
.push_back(ZExt
);
8312 for (unsigned I
= 1; I
!= NumVals
; ++I
)
8313 Ops
.push_back(Op
.getValue(I
));
8315 return DAG
.getMergeValues(Ops
, SL
);
8318 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8319 /// the call being lowered.
8321 /// This is a helper for lowering intrinsics that follow a target calling
8322 /// convention or require stack pointer adjustment. Only a subset of the
8323 /// intrinsic's operands need to participate in the calling convention.
8324 void SelectionDAGBuilder::populateCallLoweringInfo(
8325 TargetLowering::CallLoweringInfo
&CLI
, const CallBase
*Call
,
8326 unsigned ArgIdx
, unsigned NumArgs
, SDValue Callee
, Type
*ReturnTy
,
8327 bool IsPatchPoint
) {
8328 TargetLowering::ArgListTy Args
;
8329 Args
.reserve(NumArgs
);
8331 // Populate the argument list.
8332 // Attributes for args start at offset 1, after the return attribute.
8333 for (unsigned ArgI
= ArgIdx
, ArgE
= ArgIdx
+ NumArgs
;
8334 ArgI
!= ArgE
; ++ArgI
) {
8335 const Value
*V
= Call
->getOperand(ArgI
);
8337 assert(!V
->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8339 TargetLowering::ArgListEntry Entry
;
8340 Entry
.Node
= getValue(V
);
8341 Entry
.Ty
= V
->getType();
8342 Entry
.setAttributes(Call
, ArgI
);
8343 Args
.push_back(Entry
);
8346 CLI
.setDebugLoc(getCurSDLoc())
8347 .setChain(getRoot())
8348 .setCallee(Call
->getCallingConv(), ReturnTy
, Callee
, std::move(Args
))
8349 .setDiscardResult(Call
->use_empty())
8350 .setIsPatchPoint(IsPatchPoint
);
8353 /// Add a stack map intrinsic call's live variable operands to a stackmap
8354 /// or patchpoint target node's operand list.
8356 /// Constants are converted to TargetConstants purely as an optimization to
8357 /// avoid constant materialization and register allocation.
8359 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8360 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8361 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8362 /// address materialization and register allocation, but may also be required
8363 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8364 /// alloca in the entry block, then the runtime may assume that the alloca's
8365 /// StackMap location can be read immediately after compilation and that the
8366 /// location is valid at any point during execution (this is similar to the
8367 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8368 /// only available in a register, then the runtime would need to trap when
8369 /// execution reaches the StackMap in order to read the alloca's location.
8370 static void addStackMapLiveVars(ImmutableCallSite CS
, unsigned StartIdx
,
8371 const SDLoc
&DL
, SmallVectorImpl
<SDValue
> &Ops
,
8372 SelectionDAGBuilder
&Builder
) {
8373 for (unsigned i
= StartIdx
, e
= CS
.arg_size(); i
!= e
; ++i
) {
8374 SDValue OpVal
= Builder
.getValue(CS
.getArgument(i
));
8375 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(OpVal
)) {
8377 Builder
.DAG
.getTargetConstant(StackMaps::ConstantOp
, DL
, MVT::i64
));
8379 Builder
.DAG
.getTargetConstant(C
->getSExtValue(), DL
, MVT::i64
));
8380 } else if (FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(OpVal
)) {
8381 const TargetLowering
&TLI
= Builder
.DAG
.getTargetLoweringInfo();
8382 Ops
.push_back(Builder
.DAG
.getTargetFrameIndex(
8383 FI
->getIndex(), TLI
.getFrameIndexTy(Builder
.DAG
.getDataLayout())));
8385 Ops
.push_back(OpVal
);
8389 /// Lower llvm.experimental.stackmap directly to its target opcode.
8390 void SelectionDAGBuilder::visitStackmap(const CallInst
&CI
) {
8391 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8392 // [live variables...])
8394 assert(CI
.getType()->isVoidTy() && "Stackmap cannot return a value.");
8396 SDValue Chain
, InFlag
, Callee
, NullPtr
;
8397 SmallVector
<SDValue
, 32> Ops
;
8399 SDLoc DL
= getCurSDLoc();
8400 Callee
= getValue(CI
.getCalledValue());
8401 NullPtr
= DAG
.getIntPtrConstant(0, DL
, true);
8403 // The stackmap intrinsic only records the live variables (the arguemnts
8404 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8405 // intrinsic, this won't be lowered to a function call. This means we don't
8406 // have to worry about calling conventions and target specific lowering code.
8407 // Instead we perform the call lowering right here.
8409 // chain, flag = CALLSEQ_START(chain, 0, 0)
8410 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8411 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8413 Chain
= DAG
.getCALLSEQ_START(getRoot(), 0, 0, DL
);
8414 InFlag
= Chain
.getValue(1);
8416 // Add the <id> and <numBytes> constants.
8417 SDValue IDVal
= getValue(CI
.getOperand(PatchPointOpers::IDPos
));
8418 Ops
.push_back(DAG
.getTargetConstant(
8419 cast
<ConstantSDNode
>(IDVal
)->getZExtValue(), DL
, MVT::i64
));
8420 SDValue NBytesVal
= getValue(CI
.getOperand(PatchPointOpers::NBytesPos
));
8421 Ops
.push_back(DAG
.getTargetConstant(
8422 cast
<ConstantSDNode
>(NBytesVal
)->getZExtValue(), DL
,
8425 // Push live variables for the stack map.
8426 addStackMapLiveVars(&CI
, 2, DL
, Ops
, *this);
8428 // We are not pushing any register mask info here on the operands list,
8429 // because the stackmap doesn't clobber anything.
8431 // Push the chain and the glue flag.
8432 Ops
.push_back(Chain
);
8433 Ops
.push_back(InFlag
);
8435 // Create the STACKMAP node.
8436 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
8437 SDNode
*SM
= DAG
.getMachineNode(TargetOpcode::STACKMAP
, DL
, NodeTys
, Ops
);
8438 Chain
= SDValue(SM
, 0);
8439 InFlag
= Chain
.getValue(1);
8441 Chain
= DAG
.getCALLSEQ_END(Chain
, NullPtr
, NullPtr
, InFlag
, DL
);
8443 // Stackmaps don't generate values, so nothing goes into the NodeMap.
8445 // Set the root to the target-lowered call chain.
8448 // Inform the Frame Information that we have a stackmap in this function.
8449 FuncInfo
.MF
->getFrameInfo().setHasStackMap();
8452 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8453 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS
,
8454 const BasicBlock
*EHPadBB
) {
8455 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8460 // [live variables...])
8462 CallingConv::ID CC
= CS
.getCallingConv();
8463 bool IsAnyRegCC
= CC
== CallingConv::AnyReg
;
8464 bool HasDef
= !CS
->getType()->isVoidTy();
8465 SDLoc dl
= getCurSDLoc();
8466 SDValue Callee
= getValue(CS
->getOperand(PatchPointOpers::TargetPos
));
8468 // Handle immediate and symbolic callees.
8469 if (auto* ConstCallee
= dyn_cast
<ConstantSDNode
>(Callee
))
8470 Callee
= DAG
.getIntPtrConstant(ConstCallee
->getZExtValue(), dl
,
8472 else if (auto* SymbolicCallee
= dyn_cast
<GlobalAddressSDNode
>(Callee
))
8473 Callee
= DAG
.getTargetGlobalAddress(SymbolicCallee
->getGlobal(),
8474 SDLoc(SymbolicCallee
),
8475 SymbolicCallee
->getValueType(0));
8477 // Get the real number of arguments participating in the call <numArgs>
8478 SDValue NArgVal
= getValue(CS
.getArgument(PatchPointOpers::NArgPos
));
8479 unsigned NumArgs
= cast
<ConstantSDNode
>(NArgVal
)->getZExtValue();
8481 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8482 // Intrinsics include all meta-operands up to but not including CC.
8483 unsigned NumMetaOpers
= PatchPointOpers::CCPos
;
8484 assert(CS
.arg_size() >= NumMetaOpers
+ NumArgs
&&
8485 "Not enough arguments provided to the patchpoint intrinsic");
8487 // For AnyRegCC the arguments are lowered later on manually.
8488 unsigned NumCallArgs
= IsAnyRegCC
? 0 : NumArgs
;
8490 IsAnyRegCC
? Type::getVoidTy(*DAG
.getContext()) : CS
->getType();
8492 TargetLowering::CallLoweringInfo
CLI(DAG
);
8493 populateCallLoweringInfo(CLI
, cast
<CallBase
>(CS
.getInstruction()),
8494 NumMetaOpers
, NumCallArgs
, Callee
, ReturnTy
, true);
8495 std::pair
<SDValue
, SDValue
> Result
= lowerInvokable(CLI
, EHPadBB
);
8497 SDNode
*CallEnd
= Result
.second
.getNode();
8498 if (HasDef
&& (CallEnd
->getOpcode() == ISD::CopyFromReg
))
8499 CallEnd
= CallEnd
->getOperand(0).getNode();
8501 /// Get a call instruction from the call sequence chain.
8502 /// Tail calls are not allowed.
8503 assert(CallEnd
->getOpcode() == ISD::CALLSEQ_END
&&
8504 "Expected a callseq node.");
8505 SDNode
*Call
= CallEnd
->getOperand(0).getNode();
8506 bool HasGlue
= Call
->getGluedNode();
8508 // Replace the target specific call node with the patchable intrinsic.
8509 SmallVector
<SDValue
, 8> Ops
;
8511 // Add the <id> and <numBytes> constants.
8512 SDValue IDVal
= getValue(CS
->getOperand(PatchPointOpers::IDPos
));
8513 Ops
.push_back(DAG
.getTargetConstant(
8514 cast
<ConstantSDNode
>(IDVal
)->getZExtValue(), dl
, MVT::i64
));
8515 SDValue NBytesVal
= getValue(CS
->getOperand(PatchPointOpers::NBytesPos
));
8516 Ops
.push_back(DAG
.getTargetConstant(
8517 cast
<ConstantSDNode
>(NBytesVal
)->getZExtValue(), dl
,
8521 Ops
.push_back(Callee
);
8523 // Adjust <numArgs> to account for any arguments that have been passed on the
8525 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8526 unsigned NumCallRegArgs
= Call
->getNumOperands() - (HasGlue
? 4 : 3);
8527 NumCallRegArgs
= IsAnyRegCC
? NumArgs
: NumCallRegArgs
;
8528 Ops
.push_back(DAG
.getTargetConstant(NumCallRegArgs
, dl
, MVT::i32
));
8530 // Add the calling convention
8531 Ops
.push_back(DAG
.getTargetConstant((unsigned)CC
, dl
, MVT::i32
));
8533 // Add the arguments we omitted previously. The register allocator should
8534 // place these in any free register.
8536 for (unsigned i
= NumMetaOpers
, e
= NumMetaOpers
+ NumArgs
; i
!= e
; ++i
)
8537 Ops
.push_back(getValue(CS
.getArgument(i
)));
8539 // Push the arguments from the call instruction up to the register mask.
8540 SDNode::op_iterator e
= HasGlue
? Call
->op_end()-2 : Call
->op_end()-1;
8541 Ops
.append(Call
->op_begin() + 2, e
);
8543 // Push live variables for the stack map.
8544 addStackMapLiveVars(CS
, NumMetaOpers
+ NumArgs
, dl
, Ops
, *this);
8546 // Push the register mask info.
8548 Ops
.push_back(*(Call
->op_end()-2));
8550 Ops
.push_back(*(Call
->op_end()-1));
8552 // Push the chain (this is originally the first operand of the call, but
8553 // becomes now the last or second to last operand).
8554 Ops
.push_back(*(Call
->op_begin()));
8556 // Push the glue flag (last operand).
8558 Ops
.push_back(*(Call
->op_end()-1));
8561 if (IsAnyRegCC
&& HasDef
) {
8562 // Create the return types based on the intrinsic definition
8563 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
8564 SmallVector
<EVT
, 3> ValueVTs
;
8565 ComputeValueVTs(TLI
, DAG
.getDataLayout(), CS
->getType(), ValueVTs
);
8566 assert(ValueVTs
.size() == 1 && "Expected only one return value type.");
8568 // There is always a chain and a glue type at the end
8569 ValueVTs
.push_back(MVT::Other
);
8570 ValueVTs
.push_back(MVT::Glue
);
8571 NodeTys
= DAG
.getVTList(ValueVTs
);
8573 NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
8575 // Replace the target specific call node with a PATCHPOINT node.
8576 MachineSDNode
*MN
= DAG
.getMachineNode(TargetOpcode::PATCHPOINT
,
8579 // Update the NodeMap.
8582 setValue(CS
.getInstruction(), SDValue(MN
, 0));
8584 setValue(CS
.getInstruction(), Result
.first
);
8587 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8588 // call sequence. Furthermore the location of the chain and glue can change
8589 // when the AnyReg calling convention is used and the intrinsic returns a
8591 if (IsAnyRegCC
&& HasDef
) {
8592 SDValue From
[] = {SDValue(Call
, 0), SDValue(Call
, 1)};
8593 SDValue To
[] = {SDValue(MN
, 1), SDValue(MN
, 2)};
8594 DAG
.ReplaceAllUsesOfValuesWith(From
, To
, 2);
8596 DAG
.ReplaceAllUsesWith(Call
, MN
);
8597 DAG
.DeleteNode(Call
);
8599 // Inform the Frame Information that we have a patchpoint in this function.
8600 FuncInfo
.MF
->getFrameInfo().setHasPatchPoint();
8603 void SelectionDAGBuilder::visitVectorReduce(const CallInst
&I
,
8604 unsigned Intrinsic
) {
8605 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
8606 SDValue Op1
= getValue(I
.getArgOperand(0));
8608 if (I
.getNumArgOperands() > 1)
8609 Op2
= getValue(I
.getArgOperand(1));
8610 SDLoc dl
= getCurSDLoc();
8611 EVT VT
= TLI
.getValueType(DAG
.getDataLayout(), I
.getType());
8614 if (isa
<FPMathOperator
>(I
))
8615 FMF
= I
.getFastMathFlags();
8617 switch (Intrinsic
) {
8618 case Intrinsic::experimental_vector_reduce_fadd
:
8620 Res
= DAG
.getNode(ISD::VECREDUCE_FADD
, dl
, VT
, Op2
);
8622 Res
= DAG
.getNode(ISD::VECREDUCE_STRICT_FADD
, dl
, VT
, Op1
, Op2
);
8624 case Intrinsic::experimental_vector_reduce_fmul
:
8626 Res
= DAG
.getNode(ISD::VECREDUCE_FMUL
, dl
, VT
, Op2
);
8628 Res
= DAG
.getNode(ISD::VECREDUCE_STRICT_FMUL
, dl
, VT
, Op1
, Op2
);
8630 case Intrinsic::experimental_vector_reduce_add
:
8631 Res
= DAG
.getNode(ISD::VECREDUCE_ADD
, dl
, VT
, Op1
);
8633 case Intrinsic::experimental_vector_reduce_mul
:
8634 Res
= DAG
.getNode(ISD::VECREDUCE_MUL
, dl
, VT
, Op1
);
8636 case Intrinsic::experimental_vector_reduce_and
:
8637 Res
= DAG
.getNode(ISD::VECREDUCE_AND
, dl
, VT
, Op1
);
8639 case Intrinsic::experimental_vector_reduce_or
:
8640 Res
= DAG
.getNode(ISD::VECREDUCE_OR
, dl
, VT
, Op1
);
8642 case Intrinsic::experimental_vector_reduce_xor
:
8643 Res
= DAG
.getNode(ISD::VECREDUCE_XOR
, dl
, VT
, Op1
);
8645 case Intrinsic::experimental_vector_reduce_smax
:
8646 Res
= DAG
.getNode(ISD::VECREDUCE_SMAX
, dl
, VT
, Op1
);
8648 case Intrinsic::experimental_vector_reduce_smin
:
8649 Res
= DAG
.getNode(ISD::VECREDUCE_SMIN
, dl
, VT
, Op1
);
8651 case Intrinsic::experimental_vector_reduce_umax
:
8652 Res
= DAG
.getNode(ISD::VECREDUCE_UMAX
, dl
, VT
, Op1
);
8654 case Intrinsic::experimental_vector_reduce_umin
:
8655 Res
= DAG
.getNode(ISD::VECREDUCE_UMIN
, dl
, VT
, Op1
);
8657 case Intrinsic::experimental_vector_reduce_fmax
:
8658 Res
= DAG
.getNode(ISD::VECREDUCE_FMAX
, dl
, VT
, Op1
);
8660 case Intrinsic::experimental_vector_reduce_fmin
:
8661 Res
= DAG
.getNode(ISD::VECREDUCE_FMIN
, dl
, VT
, Op1
);
8664 llvm_unreachable("Unhandled vector reduce intrinsic");
8669 /// Returns an AttributeList representing the attributes applied to the return
8670 /// value of the given call.
8671 static AttributeList
getReturnAttrs(TargetLowering::CallLoweringInfo
&CLI
) {
8672 SmallVector
<Attribute::AttrKind
, 2> Attrs
;
8674 Attrs
.push_back(Attribute::SExt
);
8676 Attrs
.push_back(Attribute::ZExt
);
8678 Attrs
.push_back(Attribute::InReg
);
8680 return AttributeList::get(CLI
.RetTy
->getContext(), AttributeList::ReturnIndex
,
8684 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8685 /// implementation, which just calls LowerCall.
8686 /// FIXME: When all targets are
8687 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8688 std::pair
<SDValue
, SDValue
>
8689 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo
&CLI
) const {
8690 // Handle the incoming return values from the call.
8692 Type
*OrigRetTy
= CLI
.RetTy
;
8693 SmallVector
<EVT
, 4> RetTys
;
8694 SmallVector
<uint64_t, 4> Offsets
;
8695 auto &DL
= CLI
.DAG
.getDataLayout();
8696 ComputeValueVTs(*this, DL
, CLI
.RetTy
, RetTys
, &Offsets
);
8698 if (CLI
.IsPostTypeLegalization
) {
8699 // If we are lowering a libcall after legalization, split the return type.
8700 SmallVector
<EVT
, 4> OldRetTys
= std::move(RetTys
);
8701 SmallVector
<uint64_t, 4> OldOffsets
= std::move(Offsets
);
8702 for (size_t i
= 0, e
= OldRetTys
.size(); i
!= e
; ++i
) {
8703 EVT RetVT
= OldRetTys
[i
];
8704 uint64_t Offset
= OldOffsets
[i
];
8705 MVT RegisterVT
= getRegisterType(CLI
.RetTy
->getContext(), RetVT
);
8706 unsigned NumRegs
= getNumRegisters(CLI
.RetTy
->getContext(), RetVT
);
8707 unsigned RegisterVTByteSZ
= RegisterVT
.getSizeInBits() / 8;
8708 RetTys
.append(NumRegs
, RegisterVT
);
8709 for (unsigned j
= 0; j
!= NumRegs
; ++j
)
8710 Offsets
.push_back(Offset
+ j
* RegisterVTByteSZ
);
8714 SmallVector
<ISD::OutputArg
, 4> Outs
;
8715 GetReturnInfo(CLI
.CallConv
, CLI
.RetTy
, getReturnAttrs(CLI
), Outs
, *this, DL
);
8717 bool CanLowerReturn
=
8718 this->CanLowerReturn(CLI
.CallConv
, CLI
.DAG
.getMachineFunction(),
8719 CLI
.IsVarArg
, Outs
, CLI
.RetTy
->getContext());
8721 SDValue DemoteStackSlot
;
8722 int DemoteStackIdx
= -100;
8723 if (!CanLowerReturn
) {
8724 // FIXME: equivalent assert?
8725 // assert(!CS.hasInAllocaArgument() &&
8726 // "sret demotion is incompatible with inalloca");
8727 uint64_t TySize
= DL
.getTypeAllocSize(CLI
.RetTy
);
8728 unsigned Align
= DL
.getPrefTypeAlignment(CLI
.RetTy
);
8729 MachineFunction
&MF
= CLI
.DAG
.getMachineFunction();
8730 DemoteStackIdx
= MF
.getFrameInfo().CreateStackObject(TySize
, Align
, false);
8731 Type
*StackSlotPtrType
= PointerType::get(CLI
.RetTy
,
8732 DL
.getAllocaAddrSpace());
8734 DemoteStackSlot
= CLI
.DAG
.getFrameIndex(DemoteStackIdx
, getFrameIndexTy(DL
));
8736 Entry
.Node
= DemoteStackSlot
;
8737 Entry
.Ty
= StackSlotPtrType
;
8738 Entry
.IsSExt
= false;
8739 Entry
.IsZExt
= false;
8740 Entry
.IsInReg
= false;
8741 Entry
.IsSRet
= true;
8742 Entry
.IsNest
= false;
8743 Entry
.IsByVal
= false;
8744 Entry
.IsReturned
= false;
8745 Entry
.IsSwiftSelf
= false;
8746 Entry
.IsSwiftError
= false;
8747 Entry
.Alignment
= Align
;
8748 CLI
.getArgs().insert(CLI
.getArgs().begin(), Entry
);
8749 CLI
.NumFixedArgs
+= 1;
8750 CLI
.RetTy
= Type::getVoidTy(CLI
.RetTy
->getContext());
8752 // sret demotion isn't compatible with tail-calls, since the sret argument
8753 // points into the callers stack frame.
8754 CLI
.IsTailCall
= false;
8756 for (unsigned I
= 0, E
= RetTys
.size(); I
!= E
; ++I
) {
8758 MVT RegisterVT
= getRegisterTypeForCallingConv(CLI
.RetTy
->getContext(),
8760 unsigned NumRegs
= getNumRegistersForCallingConv(CLI
.RetTy
->getContext(),
8762 for (unsigned i
= 0; i
!= NumRegs
; ++i
) {
8763 ISD::InputArg MyFlags
;
8764 MyFlags
.VT
= RegisterVT
;
8766 MyFlags
.Used
= CLI
.IsReturnValueUsed
;
8768 MyFlags
.Flags
.setSExt();
8770 MyFlags
.Flags
.setZExt();
8772 MyFlags
.Flags
.setInReg();
8773 CLI
.Ins
.push_back(MyFlags
);
8778 // We push in swifterror return as the last element of CLI.Ins.
8779 ArgListTy
&Args
= CLI
.getArgs();
8780 if (supportSwiftError()) {
8781 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
8782 if (Args
[i
].IsSwiftError
) {
8783 ISD::InputArg MyFlags
;
8784 MyFlags
.VT
= getPointerTy(DL
);
8785 MyFlags
.ArgVT
= EVT(getPointerTy(DL
));
8786 MyFlags
.Flags
.setSwiftError();
8787 CLI
.Ins
.push_back(MyFlags
);
8792 // Handle all of the outgoing arguments.
8794 CLI
.OutVals
.clear();
8795 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
8796 SmallVector
<EVT
, 4> ValueVTs
;
8797 ComputeValueVTs(*this, DL
, Args
[i
].Ty
, ValueVTs
);
8798 // FIXME: Split arguments if CLI.IsPostTypeLegalization
8799 Type
*FinalType
= Args
[i
].Ty
;
8800 if (Args
[i
].IsByVal
)
8801 FinalType
= cast
<PointerType
>(Args
[i
].Ty
)->getElementType();
8802 bool NeedsRegBlock
= functionArgumentNeedsConsecutiveRegisters(
8803 FinalType
, CLI
.CallConv
, CLI
.IsVarArg
);
8804 for (unsigned Value
= 0, NumValues
= ValueVTs
.size(); Value
!= NumValues
;
8806 EVT VT
= ValueVTs
[Value
];
8807 Type
*ArgTy
= VT
.getTypeForEVT(CLI
.RetTy
->getContext());
8808 SDValue Op
= SDValue(Args
[i
].Node
.getNode(),
8809 Args
[i
].Node
.getResNo() + Value
);
8810 ISD::ArgFlagsTy Flags
;
8812 // Certain targets (such as MIPS), may have a different ABI alignment
8813 // for a type depending on the context. Give the target a chance to
8814 // specify the alignment it wants.
8815 unsigned OriginalAlignment
= getABIAlignmentForCallingConv(ArgTy
, DL
);
8821 if (Args
[i
].IsInReg
) {
8822 // If we are using vectorcall calling convention, a structure that is
8823 // passed InReg - is surely an HVA
8824 if (CLI
.CallConv
== CallingConv::X86_VectorCall
&&
8825 isa
<StructType
>(FinalType
)) {
8826 // The first value of a structure is marked
8828 Flags
.setHvaStart();
8836 if (Args
[i
].IsSwiftSelf
)
8837 Flags
.setSwiftSelf();
8838 if (Args
[i
].IsSwiftError
)
8839 Flags
.setSwiftError();
8840 if (Args
[i
].IsByVal
)
8842 if (Args
[i
].IsInAlloca
) {
8843 Flags
.setInAlloca();
8844 // Set the byval flag for CCAssignFn callbacks that don't know about
8845 // inalloca. This way we can know how many bytes we should've allocated
8846 // and how many bytes a callee cleanup function will pop. If we port
8847 // inalloca to more targets, we'll have to add custom inalloca handling
8848 // in the various CC lowering callbacks.
8851 if (Args
[i
].IsByVal
|| Args
[i
].IsInAlloca
) {
8852 PointerType
*Ty
= cast
<PointerType
>(Args
[i
].Ty
);
8853 Type
*ElementTy
= Ty
->getElementType();
8854 Flags
.setByValSize(DL
.getTypeAllocSize(ElementTy
));
8855 // For ByVal, alignment should come from FE. BE will guess if this
8856 // info is not there but there are cases it cannot get right.
8857 unsigned FrameAlign
;
8858 if (Args
[i
].Alignment
)
8859 FrameAlign
= Args
[i
].Alignment
;
8861 FrameAlign
= getByValTypeAlignment(ElementTy
, DL
);
8862 Flags
.setByValAlign(FrameAlign
);
8867 Flags
.setInConsecutiveRegs();
8868 Flags
.setOrigAlign(OriginalAlignment
);
8870 MVT PartVT
= getRegisterTypeForCallingConv(CLI
.RetTy
->getContext(),
8872 unsigned NumParts
= getNumRegistersForCallingConv(CLI
.RetTy
->getContext(),
8874 SmallVector
<SDValue
, 4> Parts(NumParts
);
8875 ISD::NodeType ExtendKind
= ISD::ANY_EXTEND
;
8878 ExtendKind
= ISD::SIGN_EXTEND
;
8879 else if (Args
[i
].IsZExt
)
8880 ExtendKind
= ISD::ZERO_EXTEND
;
8882 // Conservatively only handle 'returned' on non-vectors that can be lowered,
8884 if (Args
[i
].IsReturned
&& !Op
.getValueType().isVector() &&
8886 assert(CLI
.RetTy
== Args
[i
].Ty
&& RetTys
.size() == NumValues
&&
8887 "unexpected use of 'returned'");
8888 // Before passing 'returned' to the target lowering code, ensure that
8889 // either the register MVT and the actual EVT are the same size or that
8890 // the return value and argument are extended in the same way; in these
8891 // cases it's safe to pass the argument register value unchanged as the
8892 // return register value (although it's at the target's option whether
8894 // TODO: allow code generation to take advantage of partially preserved
8895 // registers rather than clobbering the entire register when the
8896 // parameter extension method is not compatible with the return
8898 if ((NumParts
* PartVT
.getSizeInBits() == VT
.getSizeInBits()) ||
8899 (ExtendKind
!= ISD::ANY_EXTEND
&& CLI
.RetSExt
== Args
[i
].IsSExt
&&
8900 CLI
.RetZExt
== Args
[i
].IsZExt
))
8901 Flags
.setReturned();
8904 getCopyToParts(CLI
.DAG
, CLI
.DL
, Op
, &Parts
[0], NumParts
, PartVT
,
8905 CLI
.CS
.getInstruction(), CLI
.CallConv
, ExtendKind
);
8907 for (unsigned j
= 0; j
!= NumParts
; ++j
) {
8908 // if it isn't first piece, alignment must be 1
8909 ISD::OutputArg
MyFlags(Flags
, Parts
[j
].getValueType(), VT
,
8910 i
< CLI
.NumFixedArgs
,
8911 i
, j
*Parts
[j
].getValueType().getStoreSize());
8912 if (NumParts
> 1 && j
== 0)
8913 MyFlags
.Flags
.setSplit();
8915 MyFlags
.Flags
.setOrigAlign(1);
8916 if (j
== NumParts
- 1)
8917 MyFlags
.Flags
.setSplitEnd();
8920 CLI
.Outs
.push_back(MyFlags
);
8921 CLI
.OutVals
.push_back(Parts
[j
]);
8924 if (NeedsRegBlock
&& Value
== NumValues
- 1)
8925 CLI
.Outs
[CLI
.Outs
.size() - 1].Flags
.setInConsecutiveRegsLast();
8929 SmallVector
<SDValue
, 4> InVals
;
8930 CLI
.Chain
= LowerCall(CLI
, InVals
);
8932 // Update CLI.InVals to use outside of this function.
8933 CLI
.InVals
= InVals
;
8935 // Verify that the target's LowerCall behaved as expected.
8936 assert(CLI
.Chain
.getNode() && CLI
.Chain
.getValueType() == MVT::Other
&&
8937 "LowerCall didn't return a valid chain!");
8938 assert((!CLI
.IsTailCall
|| InVals
.empty()) &&
8939 "LowerCall emitted a return value for a tail call!");
8940 assert((CLI
.IsTailCall
|| InVals
.size() == CLI
.Ins
.size()) &&
8941 "LowerCall didn't emit the correct number of values!");
8943 // For a tail call, the return value is merely live-out and there aren't
8944 // any nodes in the DAG representing it. Return a special value to
8945 // indicate that a tail call has been emitted and no more Instructions
8946 // should be processed in the current block.
8947 if (CLI
.IsTailCall
) {
8948 CLI
.DAG
.setRoot(CLI
.Chain
);
8949 return std::make_pair(SDValue(), SDValue());
8953 for (unsigned i
= 0, e
= CLI
.Ins
.size(); i
!= e
; ++i
) {
8954 assert(InVals
[i
].getNode() && "LowerCall emitted a null value!");
8955 assert(EVT(CLI
.Ins
[i
].VT
) == InVals
[i
].getValueType() &&
8956 "LowerCall emitted a value with the wrong type!");
8960 SmallVector
<SDValue
, 4> ReturnValues
;
8961 if (!CanLowerReturn
) {
8962 // The instruction result is the result of loading from the
8963 // hidden sret parameter.
8964 SmallVector
<EVT
, 1> PVTs
;
8965 Type
*PtrRetTy
= OrigRetTy
->getPointerTo(DL
.getAllocaAddrSpace());
8967 ComputeValueVTs(*this, DL
, PtrRetTy
, PVTs
);
8968 assert(PVTs
.size() == 1 && "Pointers should fit in one register");
8969 EVT PtrVT
= PVTs
[0];
8971 unsigned NumValues
= RetTys
.size();
8972 ReturnValues
.resize(NumValues
);
8973 SmallVector
<SDValue
, 4> Chains(NumValues
);
8975 // An aggregate return value cannot wrap around the address space, so
8976 // offsets to its parts don't wrap either.
8978 Flags
.setNoUnsignedWrap(true);
8980 for (unsigned i
= 0; i
< NumValues
; ++i
) {
8981 SDValue Add
= CLI
.DAG
.getNode(ISD::ADD
, CLI
.DL
, PtrVT
, DemoteStackSlot
,
8982 CLI
.DAG
.getConstant(Offsets
[i
], CLI
.DL
,
8984 SDValue L
= CLI
.DAG
.getLoad(
8985 RetTys
[i
], CLI
.DL
, CLI
.Chain
, Add
,
8986 MachinePointerInfo::getFixedStack(CLI
.DAG
.getMachineFunction(),
8987 DemoteStackIdx
, Offsets
[i
]),
8988 /* Alignment = */ 1);
8989 ReturnValues
[i
] = L
;
8990 Chains
[i
] = L
.getValue(1);
8993 CLI
.Chain
= CLI
.DAG
.getNode(ISD::TokenFactor
, CLI
.DL
, MVT::Other
, Chains
);
8995 // Collect the legal value parts into potentially illegal values
8996 // that correspond to the original function's return values.
8997 Optional
<ISD::NodeType
> AssertOp
;
8999 AssertOp
= ISD::AssertSext
;
9000 else if (CLI
.RetZExt
)
9001 AssertOp
= ISD::AssertZext
;
9002 unsigned CurReg
= 0;
9003 for (unsigned I
= 0, E
= RetTys
.size(); I
!= E
; ++I
) {
9005 MVT RegisterVT
= getRegisterTypeForCallingConv(CLI
.RetTy
->getContext(),
9007 unsigned NumRegs
= getNumRegistersForCallingConv(CLI
.RetTy
->getContext(),
9010 ReturnValues
.push_back(getCopyFromParts(CLI
.DAG
, CLI
.DL
, &InVals
[CurReg
],
9011 NumRegs
, RegisterVT
, VT
, nullptr,
9012 CLI
.CallConv
, AssertOp
));
9016 // For a function returning void, there is no return value. We can't create
9017 // such a node, so we just return a null return value in that case. In
9018 // that case, nothing will actually look at the value.
9019 if (ReturnValues
.empty())
9020 return std::make_pair(SDValue(), CLI
.Chain
);
9023 SDValue Res
= CLI
.DAG
.getNode(ISD::MERGE_VALUES
, CLI
.DL
,
9024 CLI
.DAG
.getVTList(RetTys
), ReturnValues
);
9025 return std::make_pair(Res
, CLI
.Chain
);
9028 void TargetLowering::LowerOperationWrapper(SDNode
*N
,
9029 SmallVectorImpl
<SDValue
> &Results
,
9030 SelectionDAG
&DAG
) const {
9031 if (SDValue Res
= LowerOperation(SDValue(N
, 0), DAG
))
9032 Results
.push_back(Res
);
9035 SDValue
TargetLowering::LowerOperation(SDValue Op
, SelectionDAG
&DAG
) const {
9036 llvm_unreachable("LowerOperation not implemented for this target!");
9040 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value
*V
, unsigned Reg
) {
9041 SDValue Op
= getNonRegisterValue(V
);
9042 assert((Op
.getOpcode() != ISD::CopyFromReg
||
9043 cast
<RegisterSDNode
>(Op
.getOperand(1))->getReg() != Reg
) &&
9044 "Copy from a reg to the same reg!");
9045 assert(!TargetRegisterInfo::isPhysicalRegister(Reg
) && "Is a physreg");
9047 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
9048 // If this is an InlineAsm we have to match the registers required, not the
9049 // notional registers required by the type.
9051 RegsForValue
RFV(V
->getContext(), TLI
, DAG
.getDataLayout(), Reg
, V
->getType(),
9052 None
); // This is not an ABI copy.
9053 SDValue Chain
= DAG
.getEntryNode();
9055 ISD::NodeType ExtendType
= (FuncInfo
.PreferredExtendType
.find(V
) ==
9056 FuncInfo
.PreferredExtendType
.end())
9058 : FuncInfo
.PreferredExtendType
[V
];
9059 RFV
.getCopyToRegs(Op
, DAG
, getCurSDLoc(), Chain
, nullptr, V
, ExtendType
);
9060 PendingExports
.push_back(Chain
);
9063 #include "llvm/CodeGen/SelectionDAGISel.h"
9065 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9066 /// entry block, return true. This includes arguments used by switches, since
9067 /// the switch may expand into multiple basic blocks.
9068 static bool isOnlyUsedInEntryBlock(const Argument
*A
, bool FastISel
) {
9069 // With FastISel active, we may be splitting blocks, so force creation
9070 // of virtual registers for all non-dead arguments.
9072 return A
->use_empty();
9074 const BasicBlock
&Entry
= A
->getParent()->front();
9075 for (const User
*U
: A
->users())
9076 if (cast
<Instruction
>(U
)->getParent() != &Entry
|| isa
<SwitchInst
>(U
))
9077 return false; // Use not in entry block.
9082 using ArgCopyElisionMapTy
=
9083 DenseMap
<const Argument
*,
9084 std::pair
<const AllocaInst
*, const StoreInst
*>>;
9086 /// Scan the entry block of the function in FuncInfo for arguments that look
9087 /// like copies into a local alloca. Record any copied arguments in
9088 /// ArgCopyElisionCandidates.
9090 findArgumentCopyElisionCandidates(const DataLayout
&DL
,
9091 FunctionLoweringInfo
*FuncInfo
,
9092 ArgCopyElisionMapTy
&ArgCopyElisionCandidates
) {
9093 // Record the state of every static alloca used in the entry block. Argument
9094 // allocas are all used in the entry block, so we need approximately as many
9095 // entries as we have arguments.
9096 enum StaticAllocaInfo
{ Unknown
, Clobbered
, Elidable
};
9097 SmallDenseMap
<const AllocaInst
*, StaticAllocaInfo
, 8> StaticAllocas
;
9098 unsigned NumArgs
= FuncInfo
->Fn
->arg_size();
9099 StaticAllocas
.reserve(NumArgs
* 2);
9101 auto GetInfoIfStaticAlloca
= [&](const Value
*V
) -> StaticAllocaInfo
* {
9104 V
= V
->stripPointerCasts();
9105 const auto *AI
= dyn_cast
<AllocaInst
>(V
);
9106 if (!AI
|| !AI
->isStaticAlloca() || !FuncInfo
->StaticAllocaMap
.count(AI
))
9108 auto Iter
= StaticAllocas
.insert({AI
, Unknown
});
9109 return &Iter
.first
->second
;
9112 // Look for stores of arguments to static allocas. Look through bitcasts and
9113 // GEPs to handle type coercions, as long as the alloca is fully initialized
9114 // by the store. Any non-store use of an alloca escapes it and any subsequent
9115 // unanalyzed store might write it.
9116 // FIXME: Handle structs initialized with multiple stores.
9117 for (const Instruction
&I
: FuncInfo
->Fn
->getEntryBlock()) {
9118 // Look for stores, and handle non-store uses conservatively.
9119 const auto *SI
= dyn_cast
<StoreInst
>(&I
);
9121 // We will look through cast uses, so ignore them completely.
9124 // Ignore debug info intrinsics, they don't escape or store to allocas.
9125 if (isa
<DbgInfoIntrinsic
>(I
))
9127 // This is an unknown instruction. Assume it escapes or writes to all
9128 // static alloca operands.
9129 for (const Use
&U
: I
.operands()) {
9130 if (StaticAllocaInfo
*Info
= GetInfoIfStaticAlloca(U
))
9131 *Info
= StaticAllocaInfo::Clobbered
;
9136 // If the stored value is a static alloca, mark it as escaped.
9137 if (StaticAllocaInfo
*Info
= GetInfoIfStaticAlloca(SI
->getValueOperand()))
9138 *Info
= StaticAllocaInfo::Clobbered
;
9140 // Check if the destination is a static alloca.
9141 const Value
*Dst
= SI
->getPointerOperand()->stripPointerCasts();
9142 StaticAllocaInfo
*Info
= GetInfoIfStaticAlloca(Dst
);
9145 const AllocaInst
*AI
= cast
<AllocaInst
>(Dst
);
9147 // Skip allocas that have been initialized or clobbered.
9148 if (*Info
!= StaticAllocaInfo::Unknown
)
9151 // Check if the stored value is an argument, and that this store fully
9152 // initializes the alloca. Don't elide copies from the same argument twice.
9153 const Value
*Val
= SI
->getValueOperand()->stripPointerCasts();
9154 const auto *Arg
= dyn_cast
<Argument
>(Val
);
9155 if (!Arg
|| Arg
->hasInAllocaAttr() || Arg
->hasByValAttr() ||
9156 Arg
->getType()->isEmptyTy() ||
9157 DL
.getTypeStoreSize(Arg
->getType()) !=
9158 DL
.getTypeAllocSize(AI
->getAllocatedType()) ||
9159 ArgCopyElisionCandidates
.count(Arg
)) {
9160 *Info
= StaticAllocaInfo::Clobbered
;
9164 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9167 // Mark this alloca and store for argument copy elision.
9168 *Info
= StaticAllocaInfo::Elidable
;
9169 ArgCopyElisionCandidates
.insert({Arg
, {AI
, SI
}});
9171 // Stop scanning if we've seen all arguments. This will happen early in -O0
9172 // builds, which is useful, because -O0 builds have large entry blocks and
9174 if (ArgCopyElisionCandidates
.size() == NumArgs
)
9179 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9180 /// ArgVal is a load from a suitable fixed stack object.
9181 static void tryToElideArgumentCopy(
9182 FunctionLoweringInfo
*FuncInfo
, SmallVectorImpl
<SDValue
> &Chains
,
9183 DenseMap
<int, int> &ArgCopyElisionFrameIndexMap
,
9184 SmallPtrSetImpl
<const Instruction
*> &ElidedArgCopyInstrs
,
9185 ArgCopyElisionMapTy
&ArgCopyElisionCandidates
, const Argument
&Arg
,
9186 SDValue ArgVal
, bool &ArgHasUses
) {
9187 // Check if this is a load from a fixed stack object.
9188 auto *LNode
= dyn_cast
<LoadSDNode
>(ArgVal
);
9191 auto *FINode
= dyn_cast
<FrameIndexSDNode
>(LNode
->getBasePtr().getNode());
9195 // Check that the fixed stack object is the right size and alignment.
9196 // Look at the alignment that the user wrote on the alloca instead of looking
9197 // at the stack object.
9198 auto ArgCopyIter
= ArgCopyElisionCandidates
.find(&Arg
);
9199 assert(ArgCopyIter
!= ArgCopyElisionCandidates
.end());
9200 const AllocaInst
*AI
= ArgCopyIter
->second
.first
;
9201 int FixedIndex
= FINode
->getIndex();
9202 int &AllocaIndex
= FuncInfo
->StaticAllocaMap
[AI
];
9203 int OldIndex
= AllocaIndex
;
9204 MachineFrameInfo
&MFI
= FuncInfo
->MF
->getFrameInfo();
9205 if (MFI
.getObjectSize(FixedIndex
) != MFI
.getObjectSize(OldIndex
)) {
9207 dbgs() << " argument copy elision failed due to bad fixed stack "
9211 unsigned RequiredAlignment
= AI
->getAlignment();
9212 if (!RequiredAlignment
) {
9213 RequiredAlignment
= FuncInfo
->MF
->getDataLayout().getABITypeAlignment(
9214 AI
->getAllocatedType());
9216 if (MFI
.getObjectAlignment(FixedIndex
) < RequiredAlignment
) {
9217 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
9218 "greater than stack argument alignment ("
9219 << RequiredAlignment
<< " vs "
9220 << MFI
.getObjectAlignment(FixedIndex
) << ")\n");
9224 // Perform the elision. Delete the old stack object and replace its only use
9225 // in the variable info map. Mark the stack object as mutable.
9227 dbgs() << "Eliding argument copy from " << Arg
<< " to " << *AI
<< '\n'
9228 << " Replacing frame index " << OldIndex
<< " with " << FixedIndex
9231 MFI
.RemoveStackObject(OldIndex
);
9232 MFI
.setIsImmutableObjectIndex(FixedIndex
, false);
9233 AllocaIndex
= FixedIndex
;
9234 ArgCopyElisionFrameIndexMap
.insert({OldIndex
, FixedIndex
});
9235 Chains
.push_back(ArgVal
.getValue(1));
9237 // Avoid emitting code for the store implementing the copy.
9238 const StoreInst
*SI
= ArgCopyIter
->second
.second
;
9239 ElidedArgCopyInstrs
.insert(SI
);
9241 // Check for uses of the argument again so that we can avoid exporting ArgVal
9242 // if it is't used by anything other than the store.
9243 for (const Value
*U
: Arg
.users()) {
9251 void SelectionDAGISel::LowerArguments(const Function
&F
) {
9252 SelectionDAG
&DAG
= SDB
->DAG
;
9253 SDLoc dl
= SDB
->getCurSDLoc();
9254 const DataLayout
&DL
= DAG
.getDataLayout();
9255 SmallVector
<ISD::InputArg
, 16> Ins
;
9257 if (!FuncInfo
->CanLowerReturn
) {
9258 // Put in an sret pointer parameter before all the other parameters.
9259 SmallVector
<EVT
, 1> ValueVTs
;
9260 ComputeValueVTs(*TLI
, DAG
.getDataLayout(),
9261 F
.getReturnType()->getPointerTo(
9262 DAG
.getDataLayout().getAllocaAddrSpace()),
9265 // NOTE: Assuming that a pointer will never break down to more than one VT
9267 ISD::ArgFlagsTy Flags
;
9269 MVT RegisterVT
= TLI
->getRegisterType(*DAG
.getContext(), ValueVTs
[0]);
9270 ISD::InputArg
RetArg(Flags
, RegisterVT
, ValueVTs
[0], true,
9271 ISD::InputArg::NoArgIndex
, 0);
9272 Ins
.push_back(RetArg
);
9275 // Look for stores of arguments to static allocas. Mark such arguments with a
9276 // flag to ask the target to give us the memory location of that argument if
9278 ArgCopyElisionMapTy ArgCopyElisionCandidates
;
9279 findArgumentCopyElisionCandidates(DL
, FuncInfo
, ArgCopyElisionCandidates
);
9281 // Set up the incoming argument description vector.
9282 for (const Argument
&Arg
: F
.args()) {
9283 unsigned ArgNo
= Arg
.getArgNo();
9284 SmallVector
<EVT
, 4> ValueVTs
;
9285 ComputeValueVTs(*TLI
, DAG
.getDataLayout(), Arg
.getType(), ValueVTs
);
9286 bool isArgValueUsed
= !Arg
.use_empty();
9287 unsigned PartBase
= 0;
9288 Type
*FinalType
= Arg
.getType();
9289 if (Arg
.hasAttribute(Attribute::ByVal
))
9290 FinalType
= cast
<PointerType
>(FinalType
)->getElementType();
9291 bool NeedsRegBlock
= TLI
->functionArgumentNeedsConsecutiveRegisters(
9292 FinalType
, F
.getCallingConv(), F
.isVarArg());
9293 for (unsigned Value
= 0, NumValues
= ValueVTs
.size();
9294 Value
!= NumValues
; ++Value
) {
9295 EVT VT
= ValueVTs
[Value
];
9296 Type
*ArgTy
= VT
.getTypeForEVT(*DAG
.getContext());
9297 ISD::ArgFlagsTy Flags
;
9299 // Certain targets (such as MIPS), may have a different ABI alignment
9300 // for a type depending on the context. Give the target a chance to
9301 // specify the alignment it wants.
9302 unsigned OriginalAlignment
=
9303 TLI
->getABIAlignmentForCallingConv(ArgTy
, DL
);
9305 if (Arg
.hasAttribute(Attribute::ZExt
))
9307 if (Arg
.hasAttribute(Attribute::SExt
))
9309 if (Arg
.hasAttribute(Attribute::InReg
)) {
9310 // If we are using vectorcall calling convention, a structure that is
9311 // passed InReg - is surely an HVA
9312 if (F
.getCallingConv() == CallingConv::X86_VectorCall
&&
9313 isa
<StructType
>(Arg
.getType())) {
9314 // The first value of a structure is marked
9316 Flags
.setHvaStart();
9322 if (Arg
.hasAttribute(Attribute::StructRet
))
9324 if (Arg
.hasAttribute(Attribute::SwiftSelf
))
9325 Flags
.setSwiftSelf();
9326 if (Arg
.hasAttribute(Attribute::SwiftError
))
9327 Flags
.setSwiftError();
9328 if (Arg
.hasAttribute(Attribute::ByVal
))
9330 if (Arg
.hasAttribute(Attribute::InAlloca
)) {
9331 Flags
.setInAlloca();
9332 // Set the byval flag for CCAssignFn callbacks that don't know about
9333 // inalloca. This way we can know how many bytes we should've allocated
9334 // and how many bytes a callee cleanup function will pop. If we port
9335 // inalloca to more targets, we'll have to add custom inalloca handling
9336 // in the various CC lowering callbacks.
9339 if (F
.getCallingConv() == CallingConv::X86_INTR
) {
9340 // IA Interrupt passes frame (1st parameter) by value in the stack.
9344 if (Flags
.isByVal() || Flags
.isInAlloca()) {
9345 PointerType
*Ty
= cast
<PointerType
>(Arg
.getType());
9346 Type
*ElementTy
= Ty
->getElementType();
9347 Flags
.setByValSize(DL
.getTypeAllocSize(ElementTy
));
9348 // For ByVal, alignment should be passed from FE. BE will guess if
9349 // this info is not there but there are cases it cannot get right.
9350 unsigned FrameAlign
;
9351 if (Arg
.getParamAlignment())
9352 FrameAlign
= Arg
.getParamAlignment();
9354 FrameAlign
= TLI
->getByValTypeAlignment(ElementTy
, DL
);
9355 Flags
.setByValAlign(FrameAlign
);
9357 if (Arg
.hasAttribute(Attribute::Nest
))
9360 Flags
.setInConsecutiveRegs();
9361 Flags
.setOrigAlign(OriginalAlignment
);
9362 if (ArgCopyElisionCandidates
.count(&Arg
))
9363 Flags
.setCopyElisionCandidate();
9365 MVT RegisterVT
= TLI
->getRegisterTypeForCallingConv(
9366 *CurDAG
->getContext(), F
.getCallingConv(), VT
);
9367 unsigned NumRegs
= TLI
->getNumRegistersForCallingConv(
9368 *CurDAG
->getContext(), F
.getCallingConv(), VT
);
9369 for (unsigned i
= 0; i
!= NumRegs
; ++i
) {
9370 ISD::InputArg
MyFlags(Flags
, RegisterVT
, VT
, isArgValueUsed
,
9371 ArgNo
, PartBase
+i
*RegisterVT
.getStoreSize());
9372 if (NumRegs
> 1 && i
== 0)
9373 MyFlags
.Flags
.setSplit();
9374 // if it isn't first piece, alignment must be 1
9376 MyFlags
.Flags
.setOrigAlign(1);
9377 if (i
== NumRegs
- 1)
9378 MyFlags
.Flags
.setSplitEnd();
9380 Ins
.push_back(MyFlags
);
9382 if (NeedsRegBlock
&& Value
== NumValues
- 1)
9383 Ins
[Ins
.size() - 1].Flags
.setInConsecutiveRegsLast();
9384 PartBase
+= VT
.getStoreSize();
9388 // Call the target to set up the argument values.
9389 SmallVector
<SDValue
, 8> InVals
;
9390 SDValue NewRoot
= TLI
->LowerFormalArguments(
9391 DAG
.getRoot(), F
.getCallingConv(), F
.isVarArg(), Ins
, dl
, DAG
, InVals
);
9393 // Verify that the target's LowerFormalArguments behaved as expected.
9394 assert(NewRoot
.getNode() && NewRoot
.getValueType() == MVT::Other
&&
9395 "LowerFormalArguments didn't return a valid chain!");
9396 assert(InVals
.size() == Ins
.size() &&
9397 "LowerFormalArguments didn't emit the correct number of values!");
9399 for (unsigned i
= 0, e
= Ins
.size(); i
!= e
; ++i
) {
9400 assert(InVals
[i
].getNode() &&
9401 "LowerFormalArguments emitted a null value!");
9402 assert(EVT(Ins
[i
].VT
) == InVals
[i
].getValueType() &&
9403 "LowerFormalArguments emitted a value with the wrong type!");
9407 // Update the DAG with the new chain value resulting from argument lowering.
9408 DAG
.setRoot(NewRoot
);
9410 // Set up the argument values.
9412 if (!FuncInfo
->CanLowerReturn
) {
9413 // Create a virtual register for the sret pointer, and put in a copy
9414 // from the sret argument into it.
9415 SmallVector
<EVT
, 1> ValueVTs
;
9416 ComputeValueVTs(*TLI
, DAG
.getDataLayout(),
9417 F
.getReturnType()->getPointerTo(
9418 DAG
.getDataLayout().getAllocaAddrSpace()),
9420 MVT VT
= ValueVTs
[0].getSimpleVT();
9421 MVT RegVT
= TLI
->getRegisterType(*CurDAG
->getContext(), VT
);
9422 Optional
<ISD::NodeType
> AssertOp
= None
;
9423 SDValue ArgValue
= getCopyFromParts(DAG
, dl
, &InVals
[0], 1, RegVT
, VT
,
9424 nullptr, F
.getCallingConv(), AssertOp
);
9426 MachineFunction
& MF
= SDB
->DAG
.getMachineFunction();
9427 MachineRegisterInfo
& RegInfo
= MF
.getRegInfo();
9428 unsigned SRetReg
= RegInfo
.createVirtualRegister(TLI
->getRegClassFor(RegVT
));
9429 FuncInfo
->DemoteRegister
= SRetReg
;
9431 SDB
->DAG
.getCopyToReg(NewRoot
, SDB
->getCurSDLoc(), SRetReg
, ArgValue
);
9432 DAG
.setRoot(NewRoot
);
9434 // i indexes lowered arguments. Bump it past the hidden sret argument.
9438 SmallVector
<SDValue
, 4> Chains
;
9439 DenseMap
<int, int> ArgCopyElisionFrameIndexMap
;
9440 for (const Argument
&Arg
: F
.args()) {
9441 SmallVector
<SDValue
, 4> ArgValues
;
9442 SmallVector
<EVT
, 4> ValueVTs
;
9443 ComputeValueVTs(*TLI
, DAG
.getDataLayout(), Arg
.getType(), ValueVTs
);
9444 unsigned NumValues
= ValueVTs
.size();
9448 bool ArgHasUses
= !Arg
.use_empty();
9450 // Elide the copying store if the target loaded this argument from a
9451 // suitable fixed stack object.
9452 if (Ins
[i
].Flags
.isCopyElisionCandidate()) {
9453 tryToElideArgumentCopy(FuncInfo
, Chains
, ArgCopyElisionFrameIndexMap
,
9454 ElidedArgCopyInstrs
, ArgCopyElisionCandidates
, Arg
,
9455 InVals
[i
], ArgHasUses
);
9458 // If this argument is unused then remember its value. It is used to generate
9459 // debugging information.
9460 bool isSwiftErrorArg
=
9461 TLI
->supportSwiftError() &&
9462 Arg
.hasAttribute(Attribute::SwiftError
);
9463 if (!ArgHasUses
&& !isSwiftErrorArg
) {
9464 SDB
->setUnusedArgValue(&Arg
, InVals
[i
]);
9466 // Also remember any frame index for use in FastISel.
9467 if (FrameIndexSDNode
*FI
=
9468 dyn_cast
<FrameIndexSDNode
>(InVals
[i
].getNode()))
9469 FuncInfo
->setArgumentFrameIndex(&Arg
, FI
->getIndex());
9472 for (unsigned Val
= 0; Val
!= NumValues
; ++Val
) {
9473 EVT VT
= ValueVTs
[Val
];
9474 MVT PartVT
= TLI
->getRegisterTypeForCallingConv(*CurDAG
->getContext(),
9475 F
.getCallingConv(), VT
);
9476 unsigned NumParts
= TLI
->getNumRegistersForCallingConv(
9477 *CurDAG
->getContext(), F
.getCallingConv(), VT
);
9479 // Even an apparant 'unused' swifterror argument needs to be returned. So
9480 // we do generate a copy for it that can be used on return from the
9482 if (ArgHasUses
|| isSwiftErrorArg
) {
9483 Optional
<ISD::NodeType
> AssertOp
;
9484 if (Arg
.hasAttribute(Attribute::SExt
))
9485 AssertOp
= ISD::AssertSext
;
9486 else if (Arg
.hasAttribute(Attribute::ZExt
))
9487 AssertOp
= ISD::AssertZext
;
9489 ArgValues
.push_back(getCopyFromParts(DAG
, dl
, &InVals
[i
], NumParts
,
9490 PartVT
, VT
, nullptr,
9491 F
.getCallingConv(), AssertOp
));
9497 // We don't need to do anything else for unused arguments.
9498 if (ArgValues
.empty())
9501 // Note down frame index.
9502 if (FrameIndexSDNode
*FI
=
9503 dyn_cast
<FrameIndexSDNode
>(ArgValues
[0].getNode()))
9504 FuncInfo
->setArgumentFrameIndex(&Arg
, FI
->getIndex());
9506 SDValue Res
= DAG
.getMergeValues(makeArrayRef(ArgValues
.data(), NumValues
),
9507 SDB
->getCurSDLoc());
9509 SDB
->setValue(&Arg
, Res
);
9510 if (!TM
.Options
.EnableFastISel
&& Res
.getOpcode() == ISD::BUILD_PAIR
) {
9511 // We want to associate the argument with the frame index, among
9512 // involved operands, that correspond to the lowest address. The
9513 // getCopyFromParts function, called earlier, is swapping the order of
9514 // the operands to BUILD_PAIR depending on endianness. The result of
9515 // that swapping is that the least significant bits of the argument will
9516 // be in the first operand of the BUILD_PAIR node, and the most
9517 // significant bits will be in the second operand.
9518 unsigned LowAddressOp
= DAG
.getDataLayout().isBigEndian() ? 1 : 0;
9519 if (LoadSDNode
*LNode
=
9520 dyn_cast
<LoadSDNode
>(Res
.getOperand(LowAddressOp
).getNode()))
9521 if (FrameIndexSDNode
*FI
=
9522 dyn_cast
<FrameIndexSDNode
>(LNode
->getBasePtr().getNode()))
9523 FuncInfo
->setArgumentFrameIndex(&Arg
, FI
->getIndex());
9526 // Update the SwiftErrorVRegDefMap.
9527 if (Res
.getOpcode() == ISD::CopyFromReg
&& isSwiftErrorArg
) {
9528 unsigned Reg
= cast
<RegisterSDNode
>(Res
.getOperand(1))->getReg();
9529 if (TargetRegisterInfo::isVirtualRegister(Reg
))
9530 FuncInfo
->setCurrentSwiftErrorVReg(FuncInfo
->MBB
,
9531 FuncInfo
->SwiftErrorArg
, Reg
);
9534 // If this argument is live outside of the entry block, insert a copy from
9535 // wherever we got it to the vreg that other BB's will reference it as.
9536 if (!TM
.Options
.EnableFastISel
&& Res
.getOpcode() == ISD::CopyFromReg
) {
9537 // If we can, though, try to skip creating an unnecessary vreg.
9538 // FIXME: This isn't very clean... it would be nice to make this more
9539 // general. It's also subtly incompatible with the hacks FastISel
9541 unsigned Reg
= cast
<RegisterSDNode
>(Res
.getOperand(1))->getReg();
9542 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
9543 FuncInfo
->ValueMap
[&Arg
] = Reg
;
9547 if (!isOnlyUsedInEntryBlock(&Arg
, TM
.Options
.EnableFastISel
)) {
9548 FuncInfo
->InitializeRegForValue(&Arg
);
9549 SDB
->CopyToExportRegsIfNeeded(&Arg
);
9553 if (!Chains
.empty()) {
9554 Chains
.push_back(NewRoot
);
9555 NewRoot
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Chains
);
9558 DAG
.setRoot(NewRoot
);
9560 assert(i
== InVals
.size() && "Argument register count mismatch!");
9562 // If any argument copy elisions occurred and we have debug info, update the
9563 // stale frame indices used in the dbg.declare variable info table.
9564 MachineFunction::VariableDbgInfoMapTy
&DbgDeclareInfo
= MF
->getVariableDbgInfo();
9565 if (!DbgDeclareInfo
.empty() && !ArgCopyElisionFrameIndexMap
.empty()) {
9566 for (MachineFunction::VariableDbgInfo
&VI
: DbgDeclareInfo
) {
9567 auto I
= ArgCopyElisionFrameIndexMap
.find(VI
.Slot
);
9568 if (I
!= ArgCopyElisionFrameIndexMap
.end())
9569 VI
.Slot
= I
->second
;
9573 // Finally, if the target has anything special to do, allow it to do so.
9574 EmitFunctionEntryCode();
9577 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
9578 /// ensure constants are generated when needed. Remember the virtual registers
9579 /// that need to be added to the Machine PHI nodes as input. We cannot just
9580 /// directly add them, because expansion might result in multiple MBB's for one
9581 /// BB. As such, the start of the BB might correspond to a different MBB than
9584 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock
*LLVMBB
) {
9585 const Instruction
*TI
= LLVMBB
->getTerminator();
9587 SmallPtrSet
<MachineBasicBlock
*, 4> SuccsHandled
;
9589 // Check PHI nodes in successors that expect a value to be available from this
9591 for (unsigned succ
= 0, e
= TI
->getNumSuccessors(); succ
!= e
; ++succ
) {
9592 const BasicBlock
*SuccBB
= TI
->getSuccessor(succ
);
9593 if (!isa
<PHINode
>(SuccBB
->begin())) continue;
9594 MachineBasicBlock
*SuccMBB
= FuncInfo
.MBBMap
[SuccBB
];
9596 // If this terminator has multiple identical successors (common for
9597 // switches), only handle each succ once.
9598 if (!SuccsHandled
.insert(SuccMBB
).second
)
9601 MachineBasicBlock::iterator MBBI
= SuccMBB
->begin();
9603 // At this point we know that there is a 1-1 correspondence between LLVM PHI
9604 // nodes and Machine PHI nodes, but the incoming operands have not been
9606 for (const PHINode
&PN
: SuccBB
->phis()) {
9607 // Ignore dead phi's.
9612 if (PN
.getType()->isEmptyTy())
9616 const Value
*PHIOp
= PN
.getIncomingValueForBlock(LLVMBB
);
9618 if (const Constant
*C
= dyn_cast
<Constant
>(PHIOp
)) {
9619 unsigned &RegOut
= ConstantsOut
[C
];
9621 RegOut
= FuncInfo
.CreateRegs(C
->getType());
9622 CopyValueToVirtualRegister(C
, RegOut
);
9626 DenseMap
<const Value
*, unsigned>::iterator I
=
9627 FuncInfo
.ValueMap
.find(PHIOp
);
9628 if (I
!= FuncInfo
.ValueMap
.end())
9631 assert(isa
<AllocaInst
>(PHIOp
) &&
9632 FuncInfo
.StaticAllocaMap
.count(cast
<AllocaInst
>(PHIOp
)) &&
9633 "Didn't codegen value into a register!??");
9634 Reg
= FuncInfo
.CreateRegs(PHIOp
->getType());
9635 CopyValueToVirtualRegister(PHIOp
, Reg
);
9639 // Remember that this register needs to added to the machine PHI node as
9640 // the input for this MBB.
9641 SmallVector
<EVT
, 4> ValueVTs
;
9642 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
9643 ComputeValueVTs(TLI
, DAG
.getDataLayout(), PN
.getType(), ValueVTs
);
9644 for (unsigned vti
= 0, vte
= ValueVTs
.size(); vti
!= vte
; ++vti
) {
9645 EVT VT
= ValueVTs
[vti
];
9646 unsigned NumRegisters
= TLI
.getNumRegisters(*DAG
.getContext(), VT
);
9647 for (unsigned i
= 0, e
= NumRegisters
; i
!= e
; ++i
)
9648 FuncInfo
.PHINodesToUpdate
.push_back(
9649 std::make_pair(&*MBBI
++, Reg
+ i
));
9650 Reg
+= NumRegisters
;
9655 ConstantsOut
.clear();
9658 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9661 SelectionDAGBuilder::StackProtectorDescriptor::
9662 AddSuccessorMBB(const BasicBlock
*BB
,
9663 MachineBasicBlock
*ParentMBB
,
9665 MachineBasicBlock
*SuccMBB
) {
9666 // If SuccBB has not been created yet, create it.
9668 MachineFunction
*MF
= ParentMBB
->getParent();
9669 MachineFunction::iterator
BBI(ParentMBB
);
9670 SuccMBB
= MF
->CreateMachineBasicBlock(BB
);
9671 MF
->insert(++BBI
, SuccMBB
);
9673 // Add it as a successor of ParentMBB.
9674 ParentMBB
->addSuccessor(
9675 SuccMBB
, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely
));
9679 MachineBasicBlock
*SelectionDAGBuilder::NextBlock(MachineBasicBlock
*MBB
) {
9680 MachineFunction::iterator
I(MBB
);
9681 if (++I
== FuncInfo
.MF
->end())
9686 /// During lowering new call nodes can be created (such as memset, etc.).
9687 /// Those will become new roots of the current DAG, but complications arise
9688 /// when they are tail calls. In such cases, the call lowering will update
9689 /// the root, but the builder still needs to know that a tail call has been
9690 /// lowered in order to avoid generating an additional return.
9691 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC
) {
9692 // If the node is null, we do have a tail call.
9693 if (MaybeTC
.getNode() != nullptr)
9694 DAG
.setRoot(MaybeTC
);
9700 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector
&Clusters
,
9701 unsigned First
, unsigned Last
) const {
9702 assert(Last
>= First
);
9703 const APInt
&LowCase
= Clusters
[First
].Low
->getValue();
9704 const APInt
&HighCase
= Clusters
[Last
].High
->getValue();
9705 assert(LowCase
.getBitWidth() == HighCase
.getBitWidth());
9707 // FIXME: A range of consecutive cases has 100% density, but only requires one
9708 // comparison to lower. We should discriminate against such consecutive ranges
9711 return (HighCase
- LowCase
).getLimitedValue((UINT64_MAX
- 1) / 100) + 1;
9714 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9715 const SmallVectorImpl
<unsigned> &TotalCases
, unsigned First
,
9716 unsigned Last
) const {
9717 assert(Last
>= First
);
9718 assert(TotalCases
[Last
] >= TotalCases
[First
]);
9720 TotalCases
[Last
] - (First
== 0 ? 0 : TotalCases
[First
- 1]);
9724 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector
&Clusters
,
9725 unsigned First
, unsigned Last
,
9726 const SwitchInst
*SI
,
9727 MachineBasicBlock
*DefaultMBB
,
9728 CaseCluster
&JTCluster
) {
9729 assert(First
<= Last
);
9731 auto Prob
= BranchProbability::getZero();
9732 unsigned NumCmps
= 0;
9733 std::vector
<MachineBasicBlock
*> Table
;
9734 DenseMap
<MachineBasicBlock
*, BranchProbability
> JTProbs
;
9736 // Initialize probabilities in JTProbs.
9737 for (unsigned I
= First
; I
<= Last
; ++I
)
9738 JTProbs
[Clusters
[I
].MBB
] = BranchProbability::getZero();
9740 for (unsigned I
= First
; I
<= Last
; ++I
) {
9741 assert(Clusters
[I
].Kind
== CC_Range
);
9742 Prob
+= Clusters
[I
].Prob
;
9743 const APInt
&Low
= Clusters
[I
].Low
->getValue();
9744 const APInt
&High
= Clusters
[I
].High
->getValue();
9745 NumCmps
+= (Low
== High
) ? 1 : 2;
9747 // Fill the gap between this and the previous cluster.
9748 const APInt
&PreviousHigh
= Clusters
[I
- 1].High
->getValue();
9749 assert(PreviousHigh
.slt(Low
));
9750 uint64_t Gap
= (Low
- PreviousHigh
).getLimitedValue() - 1;
9751 for (uint64_t J
= 0; J
< Gap
; J
++)
9752 Table
.push_back(DefaultMBB
);
9754 uint64_t ClusterSize
= (High
- Low
).getLimitedValue() + 1;
9755 for (uint64_t J
= 0; J
< ClusterSize
; ++J
)
9756 Table
.push_back(Clusters
[I
].MBB
);
9757 JTProbs
[Clusters
[I
].MBB
] += Clusters
[I
].Prob
;
9760 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
9761 unsigned NumDests
= JTProbs
.size();
9762 if (TLI
.isSuitableForBitTests(
9763 NumDests
, NumCmps
, Clusters
[First
].Low
->getValue(),
9764 Clusters
[Last
].High
->getValue(), DAG
.getDataLayout())) {
9765 // Clusters[First..Last] should be lowered as bit tests instead.
9769 // Create the MBB that will load from and jump through the table.
9770 // Note: We create it here, but it's not inserted into the function yet.
9771 MachineFunction
*CurMF
= FuncInfo
.MF
;
9772 MachineBasicBlock
*JumpTableMBB
=
9773 CurMF
->CreateMachineBasicBlock(SI
->getParent());
9775 // Add successors. Note: use table order for determinism.
9776 SmallPtrSet
<MachineBasicBlock
*, 8> Done
;
9777 for (MachineBasicBlock
*Succ
: Table
) {
9778 if (Done
.count(Succ
))
9780 addSuccessorWithProb(JumpTableMBB
, Succ
, JTProbs
[Succ
]);
9783 JumpTableMBB
->normalizeSuccProbs();
9785 unsigned JTI
= CurMF
->getOrCreateJumpTableInfo(TLI
.getJumpTableEncoding())
9786 ->createJumpTableIndex(Table
);
9788 // Set up the jump table info.
9789 JumpTable
JT(-1U, JTI
, JumpTableMBB
, nullptr);
9790 JumpTableHeader
JTH(Clusters
[First
].Low
->getValue(),
9791 Clusters
[Last
].High
->getValue(), SI
->getCondition(),
9793 JTCases
.emplace_back(std::move(JTH
), std::move(JT
));
9795 JTCluster
= CaseCluster::jumpTable(Clusters
[First
].Low
, Clusters
[Last
].High
,
9796 JTCases
.size() - 1, Prob
);
9800 void SelectionDAGBuilder::findJumpTables(CaseClusterVector
&Clusters
,
9801 const SwitchInst
*SI
,
9802 MachineBasicBlock
*DefaultMBB
) {
9804 // Clusters must be non-empty, sorted, and only contain Range clusters.
9805 assert(!Clusters
.empty());
9806 for (CaseCluster
&C
: Clusters
)
9807 assert(C
.Kind
== CC_Range
);
9808 for (unsigned i
= 1, e
= Clusters
.size(); i
< e
; ++i
)
9809 assert(Clusters
[i
- 1].High
->getValue().slt(Clusters
[i
].Low
->getValue()));
9812 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
9813 if (!TLI
.areJTsAllowed(SI
->getParent()->getParent()))
9816 const int64_t N
= Clusters
.size();
9817 const unsigned MinJumpTableEntries
= TLI
.getMinimumJumpTableEntries();
9818 const unsigned SmallNumberOfEntries
= MinJumpTableEntries
/ 2;
9820 if (N
< 2 || N
< MinJumpTableEntries
)
9823 // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9824 SmallVector
<unsigned, 8> TotalCases(N
);
9825 for (unsigned i
= 0; i
< N
; ++i
) {
9826 const APInt
&Hi
= Clusters
[i
].High
->getValue();
9827 const APInt
&Lo
= Clusters
[i
].Low
->getValue();
9828 TotalCases
[i
] = (Hi
- Lo
).getLimitedValue() + 1;
9830 TotalCases
[i
] += TotalCases
[i
- 1];
9833 // Cheap case: the whole range may be suitable for jump table.
9834 uint64_t Range
= getJumpTableRange(Clusters
,0, N
- 1);
9835 uint64_t NumCases
= getJumpTableNumCases(TotalCases
, 0, N
- 1);
9836 assert(NumCases
< UINT64_MAX
/ 100);
9837 assert(Range
>= NumCases
);
9838 if (TLI
.isSuitableForJumpTable(SI
, NumCases
, Range
)) {
9839 CaseCluster JTCluster
;
9840 if (buildJumpTable(Clusters
, 0, N
- 1, SI
, DefaultMBB
, JTCluster
)) {
9841 Clusters
[0] = JTCluster
;
9847 // The algorithm below is not suitable for -O0.
9848 if (TM
.getOptLevel() == CodeGenOpt::None
)
9851 // Split Clusters into minimum number of dense partitions. The algorithm uses
9852 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9853 // for the Case Statement'" (1994), but builds the MinPartitions array in
9854 // reverse order to make it easier to reconstruct the partitions in ascending
9855 // order. In the choice between two optimal partitionings, it picks the one
9856 // which yields more jump tables.
9858 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9859 SmallVector
<unsigned, 8> MinPartitions(N
);
9860 // LastElement[i] is the last element of the partition starting at i.
9861 SmallVector
<unsigned, 8> LastElement(N
);
9862 // PartitionsScore[i] is used to break ties when choosing between two
9863 // partitionings resulting in the same number of partitions.
9864 SmallVector
<unsigned, 8> PartitionsScore(N
);
9865 // For PartitionsScore, a small number of comparisons is considered as good as
9866 // a jump table and a single comparison is considered better than a jump
9868 enum PartitionScores
: unsigned {
9875 // Base case: There is only one way to partition Clusters[N-1].
9876 MinPartitions
[N
- 1] = 1;
9877 LastElement
[N
- 1] = N
- 1;
9878 PartitionsScore
[N
- 1] = PartitionScores::SingleCase
;
9880 // Note: loop indexes are signed to avoid underflow.
9881 for (int64_t i
= N
- 2; i
>= 0; i
--) {
9882 // Find optimal partitioning of Clusters[i..N-1].
9883 // Baseline: Put Clusters[i] into a partition on its own.
9884 MinPartitions
[i
] = MinPartitions
[i
+ 1] + 1;
9886 PartitionsScore
[i
] = PartitionsScore
[i
+ 1] + PartitionScores::SingleCase
;
9888 // Search for a solution that results in fewer partitions.
9889 for (int64_t j
= N
- 1; j
> i
; j
--) {
9890 // Try building a partition from Clusters[i..j].
9891 uint64_t Range
= getJumpTableRange(Clusters
, i
, j
);
9892 uint64_t NumCases
= getJumpTableNumCases(TotalCases
, i
, j
);
9893 assert(NumCases
< UINT64_MAX
/ 100);
9894 assert(Range
>= NumCases
);
9895 if (TLI
.isSuitableForJumpTable(SI
, NumCases
, Range
)) {
9896 unsigned NumPartitions
= 1 + (j
== N
- 1 ? 0 : MinPartitions
[j
+ 1]);
9897 unsigned Score
= j
== N
- 1 ? 0 : PartitionsScore
[j
+ 1];
9898 int64_t NumEntries
= j
- i
+ 1;
9900 if (NumEntries
== 1)
9901 Score
+= PartitionScores::SingleCase
;
9902 else if (NumEntries
<= SmallNumberOfEntries
)
9903 Score
+= PartitionScores::FewCases
;
9904 else if (NumEntries
>= MinJumpTableEntries
)
9905 Score
+= PartitionScores::Table
;
9907 // If this leads to fewer partitions, or to the same number of
9908 // partitions with better score, it is a better partitioning.
9909 if (NumPartitions
< MinPartitions
[i
] ||
9910 (NumPartitions
== MinPartitions
[i
] && Score
> PartitionsScore
[i
])) {
9911 MinPartitions
[i
] = NumPartitions
;
9913 PartitionsScore
[i
] = Score
;
9919 // Iterate over the partitions, replacing some with jump tables in-place.
9920 unsigned DstIndex
= 0;
9921 for (unsigned First
= 0, Last
; First
< N
; First
= Last
+ 1) {
9922 Last
= LastElement
[First
];
9923 assert(Last
>= First
);
9924 assert(DstIndex
<= First
);
9925 unsigned NumClusters
= Last
- First
+ 1;
9927 CaseCluster JTCluster
;
9928 if (NumClusters
>= MinJumpTableEntries
&&
9929 buildJumpTable(Clusters
, First
, Last
, SI
, DefaultMBB
, JTCluster
)) {
9930 Clusters
[DstIndex
++] = JTCluster
;
9932 for (unsigned I
= First
; I
<= Last
; ++I
)
9933 std::memmove(&Clusters
[DstIndex
++], &Clusters
[I
], sizeof(Clusters
[I
]));
9936 Clusters
.resize(DstIndex
);
9939 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector
&Clusters
,
9940 unsigned First
, unsigned Last
,
9941 const SwitchInst
*SI
,
9942 CaseCluster
&BTCluster
) {
9943 assert(First
<= Last
);
9947 BitVector
Dests(FuncInfo
.MF
->getNumBlockIDs());
9948 unsigned NumCmps
= 0;
9949 for (int64_t I
= First
; I
<= Last
; ++I
) {
9950 assert(Clusters
[I
].Kind
== CC_Range
);
9951 Dests
.set(Clusters
[I
].MBB
->getNumber());
9952 NumCmps
+= (Clusters
[I
].Low
== Clusters
[I
].High
) ? 1 : 2;
9954 unsigned NumDests
= Dests
.count();
9956 APInt Low
= Clusters
[First
].Low
->getValue();
9957 APInt High
= Clusters
[Last
].High
->getValue();
9958 assert(Low
.slt(High
));
9960 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
9961 const DataLayout
&DL
= DAG
.getDataLayout();
9962 if (!TLI
.isSuitableForBitTests(NumDests
, NumCmps
, Low
, High
, DL
))
9968 const int BitWidth
= TLI
.getPointerTy(DL
).getSizeInBits();
9969 assert(TLI
.rangeFitsInWord(Low
, High
, DL
) &&
9970 "Case range must fit in bit mask!");
9972 // Check if the clusters cover a contiguous range such that no value in the
9973 // range will jump to the default statement.
9974 bool ContiguousRange
= true;
9975 for (int64_t I
= First
+ 1; I
<= Last
; ++I
) {
9976 if (Clusters
[I
].Low
->getValue() != Clusters
[I
- 1].High
->getValue() + 1) {
9977 ContiguousRange
= false;
9982 if (Low
.isStrictlyPositive() && High
.slt(BitWidth
)) {
9983 // Optimize the case where all the case values fit in a word without having
9984 // to subtract minValue. In this case, we can optimize away the subtraction.
9985 LowBound
= APInt::getNullValue(Low
.getBitWidth());
9987 ContiguousRange
= false;
9990 CmpRange
= High
- Low
;
9994 auto TotalProb
= BranchProbability::getZero();
9995 for (unsigned i
= First
; i
<= Last
; ++i
) {
9996 // Find the CaseBits for this destination.
9998 for (j
= 0; j
< CBV
.size(); ++j
)
9999 if (CBV
[j
].BB
== Clusters
[i
].MBB
)
10001 if (j
== CBV
.size())
10003 CaseBits(0, Clusters
[i
].MBB
, 0, BranchProbability::getZero()));
10004 CaseBits
*CB
= &CBV
[j
];
10006 // Update Mask, Bits and ExtraProb.
10007 uint64_t Lo
= (Clusters
[i
].Low
->getValue() - LowBound
).getZExtValue();
10008 uint64_t Hi
= (Clusters
[i
].High
->getValue() - LowBound
).getZExtValue();
10009 assert(Hi
>= Lo
&& Hi
< 64 && "Invalid bit case!");
10010 CB
->Mask
|= (-1ULL >> (63 - (Hi
- Lo
))) << Lo
;
10011 CB
->Bits
+= Hi
- Lo
+ 1;
10012 CB
->ExtraProb
+= Clusters
[i
].Prob
;
10013 TotalProb
+= Clusters
[i
].Prob
;
10017 llvm::sort(CBV
, [](const CaseBits
&a
, const CaseBits
&b
) {
10018 // Sort by probability first, number of bits second, bit mask third.
10019 if (a
.ExtraProb
!= b
.ExtraProb
)
10020 return a
.ExtraProb
> b
.ExtraProb
;
10021 if (a
.Bits
!= b
.Bits
)
10022 return a
.Bits
> b
.Bits
;
10023 return a
.Mask
< b
.Mask
;
10026 for (auto &CB
: CBV
) {
10027 MachineBasicBlock
*BitTestBB
=
10028 FuncInfo
.MF
->CreateMachineBasicBlock(SI
->getParent());
10029 BTI
.push_back(BitTestCase(CB
.Mask
, BitTestBB
, CB
.BB
, CB
.ExtraProb
));
10031 BitTestCases
.emplace_back(std::move(LowBound
), std::move(CmpRange
),
10032 SI
->getCondition(), -1U, MVT::Other
, false,
10033 ContiguousRange
, nullptr, nullptr, std::move(BTI
),
10036 BTCluster
= CaseCluster::bitTests(Clusters
[First
].Low
, Clusters
[Last
].High
,
10037 BitTestCases
.size() - 1, TotalProb
);
10041 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector
&Clusters
,
10042 const SwitchInst
*SI
) {
10043 // Partition Clusters into as few subsets as possible, where each subset has a
10044 // range that fits in a machine word and has <= 3 unique destinations.
10047 // Clusters must be sorted and contain Range or JumpTable clusters.
10048 assert(!Clusters
.empty());
10049 assert(Clusters
[0].Kind
== CC_Range
|| Clusters
[0].Kind
== CC_JumpTable
);
10050 for (const CaseCluster
&C
: Clusters
)
10051 assert(C
.Kind
== CC_Range
|| C
.Kind
== CC_JumpTable
);
10052 for (unsigned i
= 1; i
< Clusters
.size(); ++i
)
10053 assert(Clusters
[i
-1].High
->getValue().slt(Clusters
[i
].Low
->getValue()));
10056 // The algorithm below is not suitable for -O0.
10057 if (TM
.getOptLevel() == CodeGenOpt::None
)
10060 // If target does not have legal shift left, do not emit bit tests at all.
10061 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
10062 const DataLayout
&DL
= DAG
.getDataLayout();
10064 EVT PTy
= TLI
.getPointerTy(DL
);
10065 if (!TLI
.isOperationLegal(ISD::SHL
, PTy
))
10068 int BitWidth
= PTy
.getSizeInBits();
10069 const int64_t N
= Clusters
.size();
10071 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
10072 SmallVector
<unsigned, 8> MinPartitions(N
);
10073 // LastElement[i] is the last element of the partition starting at i.
10074 SmallVector
<unsigned, 8> LastElement(N
);
10076 // FIXME: This might not be the best algorithm for finding bit test clusters.
10078 // Base case: There is only one way to partition Clusters[N-1].
10079 MinPartitions
[N
- 1] = 1;
10080 LastElement
[N
- 1] = N
- 1;
10082 // Note: loop indexes are signed to avoid underflow.
10083 for (int64_t i
= N
- 2; i
>= 0; --i
) {
10084 // Find optimal partitioning of Clusters[i..N-1].
10085 // Baseline: Put Clusters[i] into a partition on its own.
10086 MinPartitions
[i
] = MinPartitions
[i
+ 1] + 1;
10087 LastElement
[i
] = i
;
10089 // Search for a solution that results in fewer partitions.
10090 // Note: the search is limited by BitWidth, reducing time complexity.
10091 for (int64_t j
= std::min(N
- 1, i
+ BitWidth
- 1); j
> i
; --j
) {
10092 // Try building a partition from Clusters[i..j].
10094 // Check the range.
10095 if (!TLI
.rangeFitsInWord(Clusters
[i
].Low
->getValue(),
10096 Clusters
[j
].High
->getValue(), DL
))
10099 // Check nbr of destinations and cluster types.
10100 // FIXME: This works, but doesn't seem very efficient.
10101 bool RangesOnly
= true;
10102 BitVector
Dests(FuncInfo
.MF
->getNumBlockIDs());
10103 for (int64_t k
= i
; k
<= j
; k
++) {
10104 if (Clusters
[k
].Kind
!= CC_Range
) {
10105 RangesOnly
= false;
10108 Dests
.set(Clusters
[k
].MBB
->getNumber());
10110 if (!RangesOnly
|| Dests
.count() > 3)
10113 // Check if it's a better partition.
10114 unsigned NumPartitions
= 1 + (j
== N
- 1 ? 0 : MinPartitions
[j
+ 1]);
10115 if (NumPartitions
< MinPartitions
[i
]) {
10116 // Found a better partition.
10117 MinPartitions
[i
] = NumPartitions
;
10118 LastElement
[i
] = j
;
10123 // Iterate over the partitions, replacing with bit-test clusters in-place.
10124 unsigned DstIndex
= 0;
10125 for (unsigned First
= 0, Last
; First
< N
; First
= Last
+ 1) {
10126 Last
= LastElement
[First
];
10127 assert(First
<= Last
);
10128 assert(DstIndex
<= First
);
10130 CaseCluster BitTestCluster
;
10131 if (buildBitTests(Clusters
, First
, Last
, SI
, BitTestCluster
)) {
10132 Clusters
[DstIndex
++] = BitTestCluster
;
10134 size_t NumClusters
= Last
- First
+ 1;
10135 std::memmove(&Clusters
[DstIndex
], &Clusters
[First
],
10136 sizeof(Clusters
[0]) * NumClusters
);
10137 DstIndex
+= NumClusters
;
10140 Clusters
.resize(DstIndex
);
10143 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W
, Value
*Cond
,
10144 MachineBasicBlock
*SwitchMBB
,
10145 MachineBasicBlock
*DefaultMBB
) {
10146 MachineFunction
*CurMF
= FuncInfo
.MF
;
10147 MachineBasicBlock
*NextMBB
= nullptr;
10148 MachineFunction::iterator
BBI(W
.MBB
);
10149 if (++BBI
!= FuncInfo
.MF
->end())
10152 unsigned Size
= W
.LastCluster
- W
.FirstCluster
+ 1;
10154 BranchProbabilityInfo
*BPI
= FuncInfo
.BPI
;
10156 if (Size
== 2 && W
.MBB
== SwitchMBB
) {
10157 // If any two of the cases has the same destination, and if one value
10158 // is the same as the other, but has one bit unset that the other has set,
10159 // use bit manipulation to do two compares at once. For example:
10160 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10161 // TODO: This could be extended to merge any 2 cases in switches with 3
10163 // TODO: Handle cases where W.CaseBB != SwitchBB.
10164 CaseCluster
&Small
= *W
.FirstCluster
;
10165 CaseCluster
&Big
= *W
.LastCluster
;
10167 if (Small
.Low
== Small
.High
&& Big
.Low
== Big
.High
&&
10168 Small
.MBB
== Big
.MBB
) {
10169 const APInt
&SmallValue
= Small
.Low
->getValue();
10170 const APInt
&BigValue
= Big
.Low
->getValue();
10172 // Check that there is only one bit different.
10173 APInt CommonBit
= BigValue
^ SmallValue
;
10174 if (CommonBit
.isPowerOf2()) {
10175 SDValue CondLHS
= getValue(Cond
);
10176 EVT VT
= CondLHS
.getValueType();
10177 SDLoc DL
= getCurSDLoc();
10179 SDValue Or
= DAG
.getNode(ISD::OR
, DL
, VT
, CondLHS
,
10180 DAG
.getConstant(CommonBit
, DL
, VT
));
10181 SDValue Cond
= DAG
.getSetCC(
10182 DL
, MVT::i1
, Or
, DAG
.getConstant(BigValue
| SmallValue
, DL
, VT
),
10185 // Update successor info.
10186 // Both Small and Big will jump to Small.BB, so we sum up the
10188 addSuccessorWithProb(SwitchMBB
, Small
.MBB
, Small
.Prob
+ Big
.Prob
);
10190 addSuccessorWithProb(
10191 SwitchMBB
, DefaultMBB
,
10192 // The default destination is the first successor in IR.
10193 BPI
->getEdgeProbability(SwitchMBB
->getBasicBlock(), (unsigned)0));
10195 addSuccessorWithProb(SwitchMBB
, DefaultMBB
);
10197 // Insert the true branch.
10199 DAG
.getNode(ISD::BRCOND
, DL
, MVT::Other
, getControlRoot(), Cond
,
10200 DAG
.getBasicBlock(Small
.MBB
));
10201 // Insert the false branch.
10202 BrCond
= DAG
.getNode(ISD::BR
, DL
, MVT::Other
, BrCond
,
10203 DAG
.getBasicBlock(DefaultMBB
));
10205 DAG
.setRoot(BrCond
);
10211 if (TM
.getOptLevel() != CodeGenOpt::None
) {
10212 // Here, we order cases by probability so the most likely case will be
10213 // checked first. However, two clusters can have the same probability in
10214 // which case their relative ordering is non-deterministic. So we use Low
10215 // as a tie-breaker as clusters are guaranteed to never overlap.
10216 llvm::sort(W
.FirstCluster
, W
.LastCluster
+ 1,
10217 [](const CaseCluster
&a
, const CaseCluster
&b
) {
10218 return a
.Prob
!= b
.Prob
?
10220 a
.Low
->getValue().slt(b
.Low
->getValue());
10223 // Rearrange the case blocks so that the last one falls through if possible
10224 // without changing the order of probabilities.
10225 for (CaseClusterIt I
= W
.LastCluster
; I
> W
.FirstCluster
; ) {
10227 if (I
->Prob
> W
.LastCluster
->Prob
)
10229 if (I
->Kind
== CC_Range
&& I
->MBB
== NextMBB
) {
10230 std::swap(*I
, *W
.LastCluster
);
10236 // Compute total probability.
10237 BranchProbability DefaultProb
= W
.DefaultProb
;
10238 BranchProbability UnhandledProbs
= DefaultProb
;
10239 for (CaseClusterIt I
= W
.FirstCluster
; I
<= W
.LastCluster
; ++I
)
10240 UnhandledProbs
+= I
->Prob
;
10242 MachineBasicBlock
*CurMBB
= W
.MBB
;
10243 for (CaseClusterIt I
= W
.FirstCluster
, E
= W
.LastCluster
; I
<= E
; ++I
) {
10244 MachineBasicBlock
*Fallthrough
;
10245 if (I
== W
.LastCluster
) {
10246 // For the last cluster, fall through to the default destination.
10247 Fallthrough
= DefaultMBB
;
10249 Fallthrough
= CurMF
->CreateMachineBasicBlock(CurMBB
->getBasicBlock());
10250 CurMF
->insert(BBI
, Fallthrough
);
10251 // Put Cond in a virtual register to make it available from the new blocks.
10252 ExportFromCurrentBlock(Cond
);
10254 UnhandledProbs
-= I
->Prob
;
10257 case CC_JumpTable
: {
10258 // FIXME: Optimize away range check based on pivot comparisons.
10259 JumpTableHeader
*JTH
= &JTCases
[I
->JTCasesIndex
].first
;
10260 JumpTable
*JT
= &JTCases
[I
->JTCasesIndex
].second
;
10262 // The jump block hasn't been inserted yet; insert it here.
10263 MachineBasicBlock
*JumpMBB
= JT
->MBB
;
10264 CurMF
->insert(BBI
, JumpMBB
);
10266 auto JumpProb
= I
->Prob
;
10267 auto FallthroughProb
= UnhandledProbs
;
10269 // If the default statement is a target of the jump table, we evenly
10270 // distribute the default probability to successors of CurMBB. Also
10271 // update the probability on the edge from JumpMBB to Fallthrough.
10272 for (MachineBasicBlock::succ_iterator SI
= JumpMBB
->succ_begin(),
10273 SE
= JumpMBB
->succ_end();
10275 if (*SI
== DefaultMBB
) {
10276 JumpProb
+= DefaultProb
/ 2;
10277 FallthroughProb
-= DefaultProb
/ 2;
10278 JumpMBB
->setSuccProbability(SI
, DefaultProb
/ 2);
10279 JumpMBB
->normalizeSuccProbs();
10284 addSuccessorWithProb(CurMBB
, Fallthrough
, FallthroughProb
);
10285 addSuccessorWithProb(CurMBB
, JumpMBB
, JumpProb
);
10286 CurMBB
->normalizeSuccProbs();
10288 // The jump table header will be inserted in our current block, do the
10289 // range check, and fall through to our fallthrough block.
10290 JTH
->HeaderBB
= CurMBB
;
10291 JT
->Default
= Fallthrough
; // FIXME: Move Default to JumpTableHeader.
10293 // If we're in the right place, emit the jump table header right now.
10294 if (CurMBB
== SwitchMBB
) {
10295 visitJumpTableHeader(*JT
, *JTH
, SwitchMBB
);
10296 JTH
->Emitted
= true;
10300 case CC_BitTests
: {
10301 // FIXME: Optimize away range check based on pivot comparisons.
10302 BitTestBlock
*BTB
= &BitTestCases
[I
->BTCasesIndex
];
10304 // The bit test blocks haven't been inserted yet; insert them here.
10305 for (BitTestCase
&BTC
: BTB
->Cases
)
10306 CurMF
->insert(BBI
, BTC
.ThisBB
);
10308 // Fill in fields of the BitTestBlock.
10309 BTB
->Parent
= CurMBB
;
10310 BTB
->Default
= Fallthrough
;
10312 BTB
->DefaultProb
= UnhandledProbs
;
10313 // If the cases in bit test don't form a contiguous range, we evenly
10314 // distribute the probability on the edge to Fallthrough to two
10315 // successors of CurMBB.
10316 if (!BTB
->ContiguousRange
) {
10317 BTB
->Prob
+= DefaultProb
/ 2;
10318 BTB
->DefaultProb
-= DefaultProb
/ 2;
10321 // If we're in the right place, emit the bit test header right now.
10322 if (CurMBB
== SwitchMBB
) {
10323 visitBitTestHeader(*BTB
, SwitchMBB
);
10324 BTB
->Emitted
= true;
10329 const Value
*RHS
, *LHS
, *MHS
;
10331 if (I
->Low
== I
->High
) {
10332 // Check Cond == I->Low.
10338 // Check I->Low <= Cond <= I->High.
10345 // The false probability is the sum of all unhandled cases.
10346 CaseBlock
CB(CC
, LHS
, RHS
, MHS
, I
->MBB
, Fallthrough
, CurMBB
,
10347 getCurSDLoc(), I
->Prob
, UnhandledProbs
);
10349 if (CurMBB
== SwitchMBB
)
10350 visitSwitchCase(CB
, SwitchMBB
);
10352 SwitchCases
.push_back(CB
);
10357 CurMBB
= Fallthrough
;
10361 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster
&CC
,
10362 CaseClusterIt First
,
10363 CaseClusterIt Last
) {
10364 return std::count_if(First
, Last
+ 1, [&](const CaseCluster
&X
) {
10365 if (X
.Prob
!= CC
.Prob
)
10366 return X
.Prob
> CC
.Prob
;
10368 // Ties are broken by comparing the case value.
10369 return X
.Low
->getValue().slt(CC
.Low
->getValue());
10373 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList
&WorkList
,
10374 const SwitchWorkListItem
&W
,
10376 MachineBasicBlock
*SwitchMBB
) {
10377 assert(W
.FirstCluster
->Low
->getValue().slt(W
.LastCluster
->Low
->getValue()) &&
10378 "Clusters not sorted?");
10380 assert(W
.LastCluster
- W
.FirstCluster
+ 1 >= 2 && "Too small to split!");
10382 // Balance the tree based on branch probabilities to create a near-optimal (in
10383 // terms of search time given key frequency) binary search tree. See e.g. Kurt
10384 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10385 CaseClusterIt LastLeft
= W
.FirstCluster
;
10386 CaseClusterIt FirstRight
= W
.LastCluster
;
10387 auto LeftProb
= LastLeft
->Prob
+ W
.DefaultProb
/ 2;
10388 auto RightProb
= FirstRight
->Prob
+ W
.DefaultProb
/ 2;
10390 // Move LastLeft and FirstRight towards each other from opposite directions to
10391 // find a partitioning of the clusters which balances the probability on both
10392 // sides. If LeftProb and RightProb are equal, alternate which side is
10393 // taken to ensure 0-probability nodes are distributed evenly.
10395 while (LastLeft
+ 1 < FirstRight
) {
10396 if (LeftProb
< RightProb
|| (LeftProb
== RightProb
&& (I
& 1)))
10397 LeftProb
+= (++LastLeft
)->Prob
;
10399 RightProb
+= (--FirstRight
)->Prob
;
10404 // Our binary search tree differs from a typical BST in that ours can have up
10405 // to three values in each leaf. The pivot selection above doesn't take that
10406 // into account, which means the tree might require more nodes and be less
10407 // efficient. We compensate for this here.
10409 unsigned NumLeft
= LastLeft
- W
.FirstCluster
+ 1;
10410 unsigned NumRight
= W
.LastCluster
- FirstRight
+ 1;
10412 if (std::min(NumLeft
, NumRight
) < 3 && std::max(NumLeft
, NumRight
) > 3) {
10413 // If one side has less than 3 clusters, and the other has more than 3,
10414 // consider taking a cluster from the other side.
10416 if (NumLeft
< NumRight
) {
10417 // Consider moving the first cluster on the right to the left side.
10418 CaseCluster
&CC
= *FirstRight
;
10419 unsigned RightSideRank
= caseClusterRank(CC
, FirstRight
, W
.LastCluster
);
10420 unsigned LeftSideRank
= caseClusterRank(CC
, W
.FirstCluster
, LastLeft
);
10421 if (LeftSideRank
<= RightSideRank
) {
10422 // Moving the cluster to the left does not demote it.
10428 assert(NumRight
< NumLeft
);
10429 // Consider moving the last element on the left to the right side.
10430 CaseCluster
&CC
= *LastLeft
;
10431 unsigned LeftSideRank
= caseClusterRank(CC
, W
.FirstCluster
, LastLeft
);
10432 unsigned RightSideRank
= caseClusterRank(CC
, FirstRight
, W
.LastCluster
);
10433 if (RightSideRank
<= LeftSideRank
) {
10434 // Moving the cluster to the right does not demot it.
10444 assert(LastLeft
+ 1 == FirstRight
);
10445 assert(LastLeft
>= W
.FirstCluster
);
10446 assert(FirstRight
<= W
.LastCluster
);
10448 // Use the first element on the right as pivot since we will make less-than
10449 // comparisons against it.
10450 CaseClusterIt PivotCluster
= FirstRight
;
10451 assert(PivotCluster
> W
.FirstCluster
);
10452 assert(PivotCluster
<= W
.LastCluster
);
10454 CaseClusterIt FirstLeft
= W
.FirstCluster
;
10455 CaseClusterIt LastRight
= W
.LastCluster
;
10457 const ConstantInt
*Pivot
= PivotCluster
->Low
;
10459 // New blocks will be inserted immediately after the current one.
10460 MachineFunction::iterator
BBI(W
.MBB
);
10463 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10464 // we can branch to its destination directly if it's squeezed exactly in
10465 // between the known lower bound and Pivot - 1.
10466 MachineBasicBlock
*LeftMBB
;
10467 if (FirstLeft
== LastLeft
&& FirstLeft
->Kind
== CC_Range
&&
10468 FirstLeft
->Low
== W
.GE
&&
10469 (FirstLeft
->High
->getValue() + 1LL) == Pivot
->getValue()) {
10470 LeftMBB
= FirstLeft
->MBB
;
10472 LeftMBB
= FuncInfo
.MF
->CreateMachineBasicBlock(W
.MBB
->getBasicBlock());
10473 FuncInfo
.MF
->insert(BBI
, LeftMBB
);
10474 WorkList
.push_back(
10475 {LeftMBB
, FirstLeft
, LastLeft
, W
.GE
, Pivot
, W
.DefaultProb
/ 2});
10476 // Put Cond in a virtual register to make it available from the new blocks.
10477 ExportFromCurrentBlock(Cond
);
10480 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10481 // single cluster, RHS.Low == Pivot, and we can branch to its destination
10482 // directly if RHS.High equals the current upper bound.
10483 MachineBasicBlock
*RightMBB
;
10484 if (FirstRight
== LastRight
&& FirstRight
->Kind
== CC_Range
&&
10485 W
.LT
&& (FirstRight
->High
->getValue() + 1ULL) == W
.LT
->getValue()) {
10486 RightMBB
= FirstRight
->MBB
;
10488 RightMBB
= FuncInfo
.MF
->CreateMachineBasicBlock(W
.MBB
->getBasicBlock());
10489 FuncInfo
.MF
->insert(BBI
, RightMBB
);
10490 WorkList
.push_back(
10491 {RightMBB
, FirstRight
, LastRight
, Pivot
, W
.LT
, W
.DefaultProb
/ 2});
10492 // Put Cond in a virtual register to make it available from the new blocks.
10493 ExportFromCurrentBlock(Cond
);
10496 // Create the CaseBlock record that will be used to lower the branch.
10497 CaseBlock
CB(ISD::SETLT
, Cond
, Pivot
, nullptr, LeftMBB
, RightMBB
, W
.MBB
,
10498 getCurSDLoc(), LeftProb
, RightProb
);
10500 if (W
.MBB
== SwitchMBB
)
10501 visitSwitchCase(CB
, SwitchMBB
);
10503 SwitchCases
.push_back(CB
);
10506 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10507 // from the swith statement.
10508 static BranchProbability
scaleCaseProbality(BranchProbability CaseProb
,
10509 BranchProbability PeeledCaseProb
) {
10510 if (PeeledCaseProb
== BranchProbability::getOne())
10511 return BranchProbability::getZero();
10512 BranchProbability SwitchProb
= PeeledCaseProb
.getCompl();
10514 uint32_t Numerator
= CaseProb
.getNumerator();
10515 uint32_t Denominator
= SwitchProb
.scale(CaseProb
.getDenominator());
10516 return BranchProbability(Numerator
, std::max(Numerator
, Denominator
));
10519 // Try to peel the top probability case if it exceeds the threshold.
10520 // Return current MachineBasicBlock for the switch statement if the peeling
10522 // If the peeling is performed, return the newly created MachineBasicBlock
10523 // for the peeled switch statement. Also update Clusters to remove the peeled
10524 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10525 MachineBasicBlock
*SelectionDAGBuilder::peelDominantCaseCluster(
10526 const SwitchInst
&SI
, CaseClusterVector
&Clusters
,
10527 BranchProbability
&PeeledCaseProb
) {
10528 MachineBasicBlock
*SwitchMBB
= FuncInfo
.MBB
;
10529 // Don't perform if there is only one cluster or optimizing for size.
10530 if (SwitchPeelThreshold
> 100 || !FuncInfo
.BPI
|| Clusters
.size() < 2 ||
10531 TM
.getOptLevel() == CodeGenOpt::None
||
10532 SwitchMBB
->getParent()->getFunction().optForMinSize())
10535 BranchProbability TopCaseProb
= BranchProbability(SwitchPeelThreshold
, 100);
10536 unsigned PeeledCaseIndex
= 0;
10537 bool SwitchPeeled
= false;
10538 for (unsigned Index
= 0; Index
< Clusters
.size(); ++Index
) {
10539 CaseCluster
&CC
= Clusters
[Index
];
10540 if (CC
.Prob
< TopCaseProb
)
10542 TopCaseProb
= CC
.Prob
;
10543 PeeledCaseIndex
= Index
;
10544 SwitchPeeled
= true;
10549 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10550 << TopCaseProb
<< "\n");
10552 // Record the MBB for the peeled switch statement.
10553 MachineFunction::iterator
BBI(SwitchMBB
);
10555 MachineBasicBlock
*PeeledSwitchMBB
=
10556 FuncInfo
.MF
->CreateMachineBasicBlock(SwitchMBB
->getBasicBlock());
10557 FuncInfo
.MF
->insert(BBI
, PeeledSwitchMBB
);
10559 ExportFromCurrentBlock(SI
.getCondition());
10560 auto PeeledCaseIt
= Clusters
.begin() + PeeledCaseIndex
;
10561 SwitchWorkListItem W
= {SwitchMBB
, PeeledCaseIt
, PeeledCaseIt
,
10562 nullptr, nullptr, TopCaseProb
.getCompl()};
10563 lowerWorkItem(W
, SI
.getCondition(), SwitchMBB
, PeeledSwitchMBB
);
10565 Clusters
.erase(PeeledCaseIt
);
10566 for (CaseCluster
&CC
: Clusters
) {
10568 dbgs() << "Scale the probablity for one cluster, before scaling: "
10569 << CC
.Prob
<< "\n");
10570 CC
.Prob
= scaleCaseProbality(CC
.Prob
, TopCaseProb
);
10571 LLVM_DEBUG(dbgs() << "After scaling: " << CC
.Prob
<< "\n");
10573 PeeledCaseProb
= TopCaseProb
;
10574 return PeeledSwitchMBB
;
10577 void SelectionDAGBuilder::visitSwitch(const SwitchInst
&SI
) {
10578 // Extract cases from the switch.
10579 BranchProbabilityInfo
*BPI
= FuncInfo
.BPI
;
10580 CaseClusterVector Clusters
;
10581 Clusters
.reserve(SI
.getNumCases());
10582 for (auto I
: SI
.cases()) {
10583 MachineBasicBlock
*Succ
= FuncInfo
.MBBMap
[I
.getCaseSuccessor()];
10584 const ConstantInt
*CaseVal
= I
.getCaseValue();
10585 BranchProbability Prob
=
10586 BPI
? BPI
->getEdgeProbability(SI
.getParent(), I
.getSuccessorIndex())
10587 : BranchProbability(1, SI
.getNumCases() + 1);
10588 Clusters
.push_back(CaseCluster::range(CaseVal
, CaseVal
, Succ
, Prob
));
10591 MachineBasicBlock
*DefaultMBB
= FuncInfo
.MBBMap
[SI
.getDefaultDest()];
10593 // Cluster adjacent cases with the same destination. We do this at all
10594 // optimization levels because it's cheap to do and will make codegen faster
10595 // if there are many clusters.
10596 sortAndRangeify(Clusters
);
10598 if (TM
.getOptLevel() != CodeGenOpt::None
) {
10599 // Replace an unreachable default with the most popular destination.
10600 // FIXME: Exploit unreachable default more aggressively.
10601 bool UnreachableDefault
=
10602 isa
<UnreachableInst
>(SI
.getDefaultDest()->getFirstNonPHIOrDbg());
10603 if (UnreachableDefault
&& !Clusters
.empty()) {
10604 DenseMap
<const BasicBlock
*, unsigned> Popularity
;
10605 unsigned MaxPop
= 0;
10606 const BasicBlock
*MaxBB
= nullptr;
10607 for (auto I
: SI
.cases()) {
10608 const BasicBlock
*BB
= I
.getCaseSuccessor();
10609 if (++Popularity
[BB
] > MaxPop
) {
10610 MaxPop
= Popularity
[BB
];
10614 // Set new default.
10615 assert(MaxPop
> 0 && MaxBB
);
10616 DefaultMBB
= FuncInfo
.MBBMap
[MaxBB
];
10618 // Remove cases that were pointing to the destination that is now the
10620 CaseClusterVector New
;
10621 New
.reserve(Clusters
.size());
10622 for (CaseCluster
&CC
: Clusters
) {
10623 if (CC
.MBB
!= DefaultMBB
)
10626 Clusters
= std::move(New
);
10630 // The branch probablity of the peeled case.
10631 BranchProbability PeeledCaseProb
= BranchProbability::getZero();
10632 MachineBasicBlock
*PeeledSwitchMBB
=
10633 peelDominantCaseCluster(SI
, Clusters
, PeeledCaseProb
);
10635 // If there is only the default destination, jump there directly.
10636 MachineBasicBlock
*SwitchMBB
= FuncInfo
.MBB
;
10637 if (Clusters
.empty()) {
10638 assert(PeeledSwitchMBB
== SwitchMBB
);
10639 SwitchMBB
->addSuccessor(DefaultMBB
);
10640 if (DefaultMBB
!= NextBlock(SwitchMBB
)) {
10641 DAG
.setRoot(DAG
.getNode(ISD::BR
, getCurSDLoc(), MVT::Other
,
10642 getControlRoot(), DAG
.getBasicBlock(DefaultMBB
)));
10647 findJumpTables(Clusters
, &SI
, DefaultMBB
);
10648 findBitTestClusters(Clusters
, &SI
);
10651 dbgs() << "Case clusters: ";
10652 for (const CaseCluster
&C
: Clusters
) {
10653 if (C
.Kind
== CC_JumpTable
)
10655 if (C
.Kind
== CC_BitTests
)
10658 C
.Low
->getValue().print(dbgs(), true);
10659 if (C
.Low
!= C
.High
) {
10661 C
.High
->getValue().print(dbgs(), true);
10668 assert(!Clusters
.empty());
10669 SwitchWorkList WorkList
;
10670 CaseClusterIt First
= Clusters
.begin();
10671 CaseClusterIt Last
= Clusters
.end() - 1;
10672 auto DefaultProb
= getEdgeProbability(PeeledSwitchMBB
, DefaultMBB
);
10673 // Scale the branchprobability for DefaultMBB if the peel occurs and
10674 // DefaultMBB is not replaced.
10675 if (PeeledCaseProb
!= BranchProbability::getZero() &&
10676 DefaultMBB
== FuncInfo
.MBBMap
[SI
.getDefaultDest()])
10677 DefaultProb
= scaleCaseProbality(DefaultProb
, PeeledCaseProb
);
10678 WorkList
.push_back(
10679 {PeeledSwitchMBB
, First
, Last
, nullptr, nullptr, DefaultProb
});
10681 while (!WorkList
.empty()) {
10682 SwitchWorkListItem W
= WorkList
.back();
10683 WorkList
.pop_back();
10684 unsigned NumClusters
= W
.LastCluster
- W
.FirstCluster
+ 1;
10686 if (NumClusters
> 3 && TM
.getOptLevel() != CodeGenOpt::None
&&
10687 !DefaultMBB
->getParent()->getFunction().optForMinSize()) {
10688 // For optimized builds, lower large range as a balanced binary tree.
10689 splitWorkItem(WorkList
, W
, SI
.getCondition(), SwitchMBB
);
10693 lowerWorkItem(W
, SI
.getCondition(), SwitchMBB
, DefaultMBB
);