1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/GCMetadata.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/CodeGen/StackMaps.h"
38 #include "llvm/CodeGen/WinEHFuncInfo.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DebugInfo.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Statepoint.h"
53 #include "llvm/MC/MCSymbol.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Target/TargetFrameLowering.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 #include "llvm/Target/TargetIntrinsicInfo.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetOptions.h"
64 #include "llvm/Target/TargetSelectionDAGInfo.h"
65 #include "llvm/Target/TargetSubtargetInfo.h"
69 #define DEBUG_TYPE "isel"
71 /// LimitFloatPrecision - Generate low-precision inline sequences for
72 /// some float libcalls (6, 8 or 12 bits).
73 static unsigned LimitFloatPrecision;
75 static cl::opt<unsigned, true>
76 LimitFPPrecision("limit-float-precision",
77 cl::desc("Generate low-precision inline sequences "
78 "for some float libcalls"),
79 cl::location(LimitFloatPrecision),
82 // Limit the width of DAG chains. This is important in general to prevent
83 // prevent DAG-based analysis from blowing up. For example, alias analysis and
84 // load clustering may not complete in reasonable time. It is difficult to
85 // recognize and avoid this situation within each individual analysis, and
86 // future analyses are likely to have the same behavior. Limiting DAG width is
87 // the safe approach, and will be especially important with global DAGs.
89 // MaxParallelChains default is arbitrarily high to avoid affecting
90 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
91 // sequence over this should have been converted to llvm.memcpy by the
92 // frontend. It easy to induce this behavior with .ll code such as:
93 // %buffer = alloca [4096 x i8]
94 // %data = load [4096 x i8]* %argPtr
95 // store [4096 x i8] %data, [4096 x i8]* %buffer
96 static const unsigned MaxParallelChains = 64;
98 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
99 const SDValue *Parts, unsigned NumParts,
100 MVT PartVT, EVT ValueVT, const Value *V);
102 /// getCopyFromParts - Create a value that contains the specified legal parts
103 /// combined into the value they represent. If the parts combine to a type
104 /// larger then ValueVT then AssertOp can be used to specify whether the extra
105 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
106 /// (ISD::AssertSext).
107 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
108 const SDValue *Parts,
109 unsigned NumParts, MVT PartVT, EVT ValueVT,
111 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
112 if (ValueVT.isVector())
113 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
116 assert(NumParts > 0 && "No parts to assemble!");
117 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
118 SDValue Val = Parts[0];
121 // Assemble the value from multiple parts.
122 if (ValueVT.isInteger()) {
123 unsigned PartBits = PartVT.getSizeInBits();
124 unsigned ValueBits = ValueVT.getSizeInBits();
126 // Assemble the power of 2 part.
127 unsigned RoundParts = NumParts & (NumParts - 1) ?
128 1 << Log2_32(NumParts) : NumParts;
129 unsigned RoundBits = PartBits * RoundParts;
130 EVT RoundVT = RoundBits == ValueBits ?
131 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
134 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
136 if (RoundParts > 2) {
137 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
139 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
140 RoundParts / 2, PartVT, HalfVT, V);
142 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
143 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
146 if (TLI.isBigEndian())
149 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
151 if (RoundParts < NumParts) {
152 // Assemble the trailing non-power-of-2 part.
153 unsigned OddParts = NumParts - RoundParts;
154 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
155 Hi = getCopyFromParts(DAG, DL,
156 Parts + RoundParts, OddParts, PartVT, OddVT, V);
158 // Combine the round and odd parts.
160 if (TLI.isBigEndian())
162 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
163 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
164 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
165 DAG.getConstant(Lo.getValueType().getSizeInBits(), DL,
166 TLI.getPointerTy()));
167 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
168 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
170 } else if (PartVT.isFloatingPoint()) {
171 // FP split into multiple FP parts (for ppcf128)
172 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
175 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
176 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
177 if (TLI.hasBigEndianPartOrdering(ValueVT))
179 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
181 // FP split into integer parts (soft fp)
182 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
183 !PartVT.isVector() && "Unexpected split");
184 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
185 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
189 // There is now one part, held in Val. Correct it to match ValueVT.
190 EVT PartEVT = Val.getValueType();
192 if (PartEVT == ValueVT)
195 if (PartEVT.isInteger() && ValueVT.isInteger()) {
196 if (ValueVT.bitsLT(PartEVT)) {
197 // For a truncate, see if we have any information to
198 // indicate whether the truncated bits will always be
199 // zero or sign-extension.
200 if (AssertOp != ISD::DELETED_NODE)
201 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
202 DAG.getValueType(ValueVT));
203 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
205 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
208 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
209 // FP_ROUND's are always exact here.
210 if (ValueVT.bitsLT(Val.getValueType()))
211 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
212 DAG.getTargetConstant(1, DL, TLI.getPointerTy()));
214 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
217 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
218 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
220 llvm_unreachable("Unknown mismatch!");
223 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
224 const Twine &ErrMsg) {
225 const Instruction *I = dyn_cast_or_null<Instruction>(V);
227 return Ctx.emitError(ErrMsg);
229 const char *AsmError = ", possible invalid constraint for vector type";
230 if (const CallInst *CI = dyn_cast<CallInst>(I))
231 if (isa<InlineAsm>(CI->getCalledValue()))
232 return Ctx.emitError(I, ErrMsg + AsmError);
234 return Ctx.emitError(I, ErrMsg);
237 /// getCopyFromPartsVector - Create a value that contains the specified legal
238 /// parts combined into the value they represent. If the parts combine to a
239 /// type larger then ValueVT then AssertOp can be used to specify whether the
240 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
241 /// ValueVT (ISD::AssertSext).
242 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
243 const SDValue *Parts, unsigned NumParts,
244 MVT PartVT, EVT ValueVT, const Value *V) {
245 assert(ValueVT.isVector() && "Not a vector value");
246 assert(NumParts > 0 && "No parts to assemble!");
247 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
248 SDValue Val = Parts[0];
250 // Handle a multi-element vector.
254 unsigned NumIntermediates;
256 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
257 NumIntermediates, RegisterVT);
258 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
259 NumParts = NumRegs; // Silence a compiler warning.
260 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
261 assert(RegisterVT == Parts[0].getSimpleValueType() &&
262 "Part type doesn't match part!");
264 // Assemble the parts into intermediate operands.
265 SmallVector<SDValue, 8> Ops(NumIntermediates);
266 if (NumIntermediates == NumParts) {
267 // If the register was not expanded, truncate or copy the value,
269 for (unsigned i = 0; i != NumParts; ++i)
270 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
271 PartVT, IntermediateVT, V);
272 } else if (NumParts > 0) {
273 // If the intermediate type was expanded, build the intermediate
274 // operands from the parts.
275 assert(NumParts % NumIntermediates == 0 &&
276 "Must expand into a divisible number of parts!");
277 unsigned Factor = NumParts / NumIntermediates;
278 for (unsigned i = 0; i != NumIntermediates; ++i)
279 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
280 PartVT, IntermediateVT, V);
283 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
284 // intermediate operands.
285 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
290 // There is now one part, held in Val. Correct it to match ValueVT.
291 EVT PartEVT = Val.getValueType();
293 if (PartEVT == ValueVT)
296 if (PartEVT.isVector()) {
297 // If the element type of the source/dest vectors are the same, but the
298 // parts vector has more elements than the value vector, then we have a
299 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
301 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
302 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
303 "Cannot narrow, it would be a lossy transformation");
304 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
305 DAG.getConstant(0, DL, TLI.getVectorIdxTy()));
308 // Vector/Vector bitcast.
309 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
310 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
312 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
313 "Cannot handle this kind of promotion");
314 // Promoted vector extract
315 bool Smaller = ValueVT.bitsLE(PartEVT);
316 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
321 // Trivial bitcast if the types are the same size and the destination
322 // vector type is legal.
323 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
324 TLI.isTypeLegal(ValueVT))
325 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
327 // Handle cases such as i8 -> <1 x i1>
328 if (ValueVT.getVectorNumElements() != 1) {
329 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
330 "non-trivial scalar-to-vector conversion");
331 return DAG.getUNDEF(ValueVT);
334 if (ValueVT.getVectorNumElements() == 1 &&
335 ValueVT.getVectorElementType() != PartEVT) {
336 bool Smaller = ValueVT.bitsLE(PartEVT);
337 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
338 DL, ValueVT.getScalarType(), Val);
341 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
344 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
345 SDValue Val, SDValue *Parts, unsigned NumParts,
346 MVT PartVT, const Value *V);
348 /// getCopyToParts - Create a series of nodes that contain the specified value
349 /// split into legal parts. If the parts contain more bits than Val, then, for
350 /// integers, ExtendKind can be used to specify how to generate the extra bits.
351 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
352 SDValue Val, SDValue *Parts, unsigned NumParts,
353 MVT PartVT, const Value *V,
354 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
355 EVT ValueVT = Val.getValueType();
357 // Handle the vector case separately.
358 if (ValueVT.isVector())
359 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
361 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
362 unsigned PartBits = PartVT.getSizeInBits();
363 unsigned OrigNumParts = NumParts;
364 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
369 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
370 EVT PartEVT = PartVT;
371 if (PartEVT == ValueVT) {
372 assert(NumParts == 1 && "No-op copy with multiple parts!");
377 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
378 // If the parts cover more bits than the value has, promote the value.
379 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
380 assert(NumParts == 1 && "Do not know what to promote to!");
381 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
383 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
384 ValueVT.isInteger() &&
385 "Unknown mismatch!");
386 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
387 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
388 if (PartVT == MVT::x86mmx)
389 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
391 } else if (PartBits == ValueVT.getSizeInBits()) {
392 // Different types of the same size.
393 assert(NumParts == 1 && PartEVT != ValueVT);
394 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
395 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
396 // If the parts cover less bits than value has, truncate the value.
397 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
398 ValueVT.isInteger() &&
399 "Unknown mismatch!");
400 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
401 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
402 if (PartVT == MVT::x86mmx)
403 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
406 // The value may have changed - recompute ValueVT.
407 ValueVT = Val.getValueType();
408 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
409 "Failed to tile the value with PartVT!");
412 if (PartEVT != ValueVT)
413 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
414 "scalar-to-vector conversion failed");
420 // Expand the value into multiple parts.
421 if (NumParts & (NumParts - 1)) {
422 // The number of parts is not a power of 2. Split off and copy the tail.
423 assert(PartVT.isInteger() && ValueVT.isInteger() &&
424 "Do not know what to expand to!");
425 unsigned RoundParts = 1 << Log2_32(NumParts);
426 unsigned RoundBits = RoundParts * PartBits;
427 unsigned OddParts = NumParts - RoundParts;
428 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
429 DAG.getIntPtrConstant(RoundBits, DL));
430 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
432 if (TLI.isBigEndian())
433 // The odd parts were reversed by getCopyToParts - unreverse them.
434 std::reverse(Parts + RoundParts, Parts + NumParts);
436 NumParts = RoundParts;
437 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
438 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
441 // The number of parts is a power of 2. Repeatedly bisect the value using
443 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
444 EVT::getIntegerVT(*DAG.getContext(),
445 ValueVT.getSizeInBits()),
448 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
449 for (unsigned i = 0; i < NumParts; i += StepSize) {
450 unsigned ThisBits = StepSize * PartBits / 2;
451 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
452 SDValue &Part0 = Parts[i];
453 SDValue &Part1 = Parts[i+StepSize/2];
455 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
456 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
457 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
458 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
460 if (ThisBits == PartBits && ThisVT != PartVT) {
461 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
462 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
467 if (TLI.isBigEndian())
468 std::reverse(Parts, Parts + OrigNumParts);
472 /// getCopyToPartsVector - Create a series of nodes that contain the specified
473 /// value split into legal parts.
474 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
475 SDValue Val, SDValue *Parts, unsigned NumParts,
476 MVT PartVT, const Value *V) {
477 EVT ValueVT = Val.getValueType();
478 assert(ValueVT.isVector() && "Not a vector");
479 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
482 EVT PartEVT = PartVT;
483 if (PartEVT == ValueVT) {
485 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
486 // Bitconvert vector->vector case.
487 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
488 } else if (PartVT.isVector() &&
489 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
490 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
491 EVT ElementVT = PartVT.getVectorElementType();
492 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
494 SmallVector<SDValue, 16> Ops;
495 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
496 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
497 ElementVT, Val, DAG.getConstant(i, DL,
498 TLI.getVectorIdxTy())));
500 for (unsigned i = ValueVT.getVectorNumElements(),
501 e = PartVT.getVectorNumElements(); i != e; ++i)
502 Ops.push_back(DAG.getUNDEF(ElementVT));
504 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
506 // FIXME: Use CONCAT for 2x -> 4x.
508 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
509 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
510 } else if (PartVT.isVector() &&
511 PartEVT.getVectorElementType().bitsGE(
512 ValueVT.getVectorElementType()) &&
513 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
515 // Promoted vector extract
516 bool Smaller = PartEVT.bitsLE(ValueVT);
517 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
520 // Vector -> scalar conversion.
521 assert(ValueVT.getVectorNumElements() == 1 &&
522 "Only trivial vector-to-scalar conversions should get here!");
523 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
525 DAG.getConstant(0, DL, TLI.getVectorIdxTy()));
527 bool Smaller = ValueVT.bitsLE(PartVT);
528 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
536 // Handle a multi-element vector.
539 unsigned NumIntermediates;
540 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
542 NumIntermediates, RegisterVT);
543 unsigned NumElements = ValueVT.getVectorNumElements();
545 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
546 NumParts = NumRegs; // Silence a compiler warning.
547 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
549 // Split the vector into intermediate operands.
550 SmallVector<SDValue, 8> Ops(NumIntermediates);
551 for (unsigned i = 0; i != NumIntermediates; ++i) {
552 if (IntermediateVT.isVector())
553 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
555 DAG.getConstant(i * (NumElements / NumIntermediates), DL,
556 TLI.getVectorIdxTy()));
558 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
560 DAG.getConstant(i, DL, TLI.getVectorIdxTy()));
563 // Split the intermediate operands into legal parts.
564 if (NumParts == NumIntermediates) {
565 // If the register was not expanded, promote or copy the value,
567 for (unsigned i = 0; i != NumParts; ++i)
568 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
569 } else if (NumParts > 0) {
570 // If the intermediate type was expanded, split each the value into
572 assert(NumIntermediates != 0 && "division by zero");
573 assert(NumParts % NumIntermediates == 0 &&
574 "Must expand into a divisible number of parts!");
575 unsigned Factor = NumParts / NumIntermediates;
576 for (unsigned i = 0; i != NumIntermediates; ++i)
577 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
582 /// RegsForValue - This struct represents the registers (physical or virtual)
583 /// that a particular set of values is assigned, and the type information
584 /// about the value. The most common situation is to represent one value at a
585 /// time, but struct or array values are handled element-wise as multiple
586 /// values. The splitting of aggregates is performed recursively, so that we
587 /// never have aggregate-typed registers. The values at this point do not
588 /// necessarily have legal types, so each value may require one or more
589 /// registers of some legal type.
591 struct RegsForValue {
592 /// ValueVTs - The value types of the values, which may not be legal, and
593 /// may need be promoted or synthesized from one or more registers.
595 SmallVector<EVT, 4> ValueVTs;
597 /// RegVTs - The value types of the registers. This is the same size as
598 /// ValueVTs and it records, for each value, what the type of the assigned
599 /// register or registers are. (Individual values are never synthesized
600 /// from more than one type of register.)
602 /// With virtual registers, the contents of RegVTs is redundant with TLI's
603 /// getRegisterType member function, however when with physical registers
604 /// it is necessary to have a separate record of the types.
606 SmallVector<MVT, 4> RegVTs;
608 /// Regs - This list holds the registers assigned to the values.
609 /// Each legal or promoted value requires one register, and each
610 /// expanded value requires multiple registers.
612 SmallVector<unsigned, 4> Regs;
616 RegsForValue(const SmallVector<unsigned, 4> ®s,
617 MVT regvt, EVT valuevt)
618 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
620 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
621 unsigned Reg, Type *Ty) {
622 ComputeValueVTs(tli, Ty, ValueVTs);
624 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
625 EVT ValueVT = ValueVTs[Value];
626 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
627 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
628 for (unsigned i = 0; i != NumRegs; ++i)
629 Regs.push_back(Reg + i);
630 RegVTs.push_back(RegisterVT);
635 /// append - Add the specified values to this one.
636 void append(const RegsForValue &RHS) {
637 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
638 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
639 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
642 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
643 /// this value and returns the result as a ValueVTs value. This uses
644 /// Chain/Flag as the input and updates them for the output Chain/Flag.
645 /// If the Flag pointer is NULL, no flag is used.
646 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
648 SDValue &Chain, SDValue *Flag,
649 const Value *V = nullptr) const;
651 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
652 /// specified value into the registers specified by this object. This uses
653 /// Chain/Flag as the input and updates them for the output Chain/Flag.
654 /// If the Flag pointer is NULL, no flag is used.
656 getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
657 SDValue *Flag, const Value *V,
658 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
660 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
661 /// operand list. This adds the code marker, matching input operand index
662 /// (if applicable), and includes the number of values added into it.
663 void AddInlineAsmOperands(unsigned Kind,
664 bool HasMatching, unsigned MatchingIdx, SDLoc dl,
666 std::vector<SDValue> &Ops) const;
670 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
671 /// this value and returns the result as a ValueVT value. This uses
672 /// Chain/Flag as the input and updates them for the output Chain/Flag.
673 /// If the Flag pointer is NULL, no flag is used.
674 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
675 FunctionLoweringInfo &FuncInfo,
677 SDValue &Chain, SDValue *Flag,
678 const Value *V) const {
679 // A Value with type {} or [0 x %t] needs no registers.
680 if (ValueVTs.empty())
683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
685 // Assemble the legal parts into the final values.
686 SmallVector<SDValue, 4> Values(ValueVTs.size());
687 SmallVector<SDValue, 8> Parts;
688 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
689 // Copy the legal parts from the registers.
690 EVT ValueVT = ValueVTs[Value];
691 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
692 MVT RegisterVT = RegVTs[Value];
694 Parts.resize(NumRegs);
695 for (unsigned i = 0; i != NumRegs; ++i) {
698 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
700 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
701 *Flag = P.getValue(2);
704 Chain = P.getValue(1);
707 // If the source register was virtual and if we know something about it,
708 // add an assert node.
709 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
710 !RegisterVT.isInteger() || RegisterVT.isVector())
713 const FunctionLoweringInfo::LiveOutInfo *LOI =
714 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
718 unsigned RegSize = RegisterVT.getSizeInBits();
719 unsigned NumSignBits = LOI->NumSignBits;
720 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
722 if (NumZeroBits == RegSize) {
723 // The current value is a zero.
724 // Explicitly express that as it would be easier for
725 // optimizations to kick in.
726 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
730 // FIXME: We capture more information than the dag can represent. For
731 // now, just use the tightest assertzext/assertsext possible.
733 EVT FromVT(MVT::Other);
734 if (NumSignBits == RegSize)
735 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
736 else if (NumZeroBits >= RegSize-1)
737 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
738 else if (NumSignBits > RegSize-8)
739 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
740 else if (NumZeroBits >= RegSize-8)
741 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
742 else if (NumSignBits > RegSize-16)
743 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
744 else if (NumZeroBits >= RegSize-16)
745 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
746 else if (NumSignBits > RegSize-32)
747 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
748 else if (NumZeroBits >= RegSize-32)
749 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
753 // Add an assertion node.
754 assert(FromVT != MVT::Other);
755 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
756 RegisterVT, P, DAG.getValueType(FromVT));
759 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
760 NumRegs, RegisterVT, ValueVT, V);
765 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
768 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
769 /// specified value into the registers specified by this object. This uses
770 /// Chain/Flag as the input and updates them for the output Chain/Flag.
771 /// If the Flag pointer is NULL, no flag is used.
772 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
773 SDValue &Chain, SDValue *Flag, const Value *V,
774 ISD::NodeType PreferredExtendType) const {
775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
776 ISD::NodeType ExtendKind = PreferredExtendType;
778 // Get the list of the values's legal parts.
779 unsigned NumRegs = Regs.size();
780 SmallVector<SDValue, 8> Parts(NumRegs);
781 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
782 EVT ValueVT = ValueVTs[Value];
783 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
784 MVT RegisterVT = RegVTs[Value];
786 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
787 ExtendKind = ISD::ZERO_EXTEND;
789 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
790 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
794 // Copy the parts into the registers.
795 SmallVector<SDValue, 8> Chains(NumRegs);
796 for (unsigned i = 0; i != NumRegs; ++i) {
799 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
801 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
802 *Flag = Part.getValue(1);
805 Chains[i] = Part.getValue(0);
808 if (NumRegs == 1 || Flag)
809 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
810 // flagged to it. That is the CopyToReg nodes and the user are considered
811 // a single scheduling unit. If we create a TokenFactor and return it as
812 // chain, then the TokenFactor is both a predecessor (operand) of the
813 // user as well as a successor (the TF operands are flagged to the user).
814 // c1, f1 = CopyToReg
815 // c2, f2 = CopyToReg
816 // c3 = TokenFactor c1, c2
819 Chain = Chains[NumRegs-1];
821 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
824 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
825 /// operand list. This adds the code marker and includes the number of
826 /// values added into it.
827 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
828 unsigned MatchingIdx, SDLoc dl,
830 std::vector<SDValue> &Ops) const {
831 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
833 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
835 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
836 else if (!Regs.empty() &&
837 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
838 // Put the register class of the virtual registers in the flag word. That
839 // way, later passes can recompute register class constraints for inline
840 // assembly as well as normal instructions.
841 // Don't do this for tied operands that can use the regclass information
843 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
844 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
845 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
848 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
851 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
852 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
853 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
854 MVT RegisterVT = RegVTs[Value];
855 for (unsigned i = 0; i != NumRegs; ++i) {
856 assert(Reg < Regs.size() && "Mismatch in # registers expected");
857 unsigned TheReg = Regs[Reg++];
858 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
860 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
861 // If we clobbered the stack pointer, MFI should know about it.
862 assert(DAG.getMachineFunction().getFrameInfo()->
863 hasInlineAsmWithSPAdjust());
869 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
870 const TargetLibraryInfo *li) {
874 DL = DAG.getTarget().getDataLayout();
875 Context = DAG.getContext();
876 LPadToCallSiteMap.clear();
879 /// clear - Clear out the current SelectionDAG and the associated
880 /// state and prepare this SelectionDAGBuilder object to be used
881 /// for a new block. This doesn't clear out information about
882 /// additional blocks that are needed to complete switch lowering
883 /// or PHI node updating; that information is cleared out as it is
885 void SelectionDAGBuilder::clear() {
887 UnusedArgNodeMap.clear();
888 PendingLoads.clear();
889 PendingExports.clear();
892 SDNodeOrder = LowestSDNodeOrder;
893 StatepointLowering.clear();
896 /// clearDanglingDebugInfo - Clear the dangling debug information
897 /// map. This function is separated from the clear so that debug
898 /// information that is dangling in a basic block can be properly
899 /// resolved in a different basic block. This allows the
900 /// SelectionDAG to resolve dangling debug information attached
902 void SelectionDAGBuilder::clearDanglingDebugInfo() {
903 DanglingDebugInfoMap.clear();
906 /// getRoot - Return the current virtual root of the Selection DAG,
907 /// flushing any PendingLoad items. This must be done before emitting
908 /// a store or any other node that may need to be ordered after any
909 /// prior load instructions.
911 SDValue SelectionDAGBuilder::getRoot() {
912 if (PendingLoads.empty())
913 return DAG.getRoot();
915 if (PendingLoads.size() == 1) {
916 SDValue Root = PendingLoads[0];
918 PendingLoads.clear();
922 // Otherwise, we have to make a token factor node.
923 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
925 PendingLoads.clear();
930 /// getControlRoot - Similar to getRoot, but instead of flushing all the
931 /// PendingLoad items, flush all the PendingExports items. It is necessary
932 /// to do this before emitting a terminator instruction.
934 SDValue SelectionDAGBuilder::getControlRoot() {
935 SDValue Root = DAG.getRoot();
937 if (PendingExports.empty())
940 // Turn all of the CopyToReg chains into one factored node.
941 if (Root.getOpcode() != ISD::EntryToken) {
942 unsigned i = 0, e = PendingExports.size();
943 for (; i != e; ++i) {
944 assert(PendingExports[i].getNode()->getNumOperands() > 1);
945 if (PendingExports[i].getNode()->getOperand(0) == Root)
946 break; // Don't add the root if we already indirectly depend on it.
950 PendingExports.push_back(Root);
953 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
955 PendingExports.clear();
960 void SelectionDAGBuilder::visit(const Instruction &I) {
961 // Set up outgoing PHI node register values before emitting the terminator.
962 if (isa<TerminatorInst>(&I))
963 HandlePHINodesInSuccessorBlocks(I.getParent());
969 visit(I.getOpcode(), I);
971 if (!isa<TerminatorInst>(&I) && !HasTailCall)
972 CopyToExportRegsIfNeeded(&I);
977 void SelectionDAGBuilder::visitPHI(const PHINode &) {
978 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
981 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
982 // Note: this doesn't use InstVisitor, because it has to work with
983 // ConstantExpr's in addition to instructions.
985 default: llvm_unreachable("Unknown instruction type encountered!");
986 // Build the switch statement using the Instruction.def file.
987 #define HANDLE_INST(NUM, OPCODE, CLASS) \
988 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
989 #include "llvm/IR/Instruction.def"
993 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
994 // generate the debug data structures now that we've seen its definition.
995 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
997 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
999 const DbgValueInst *DI = DDI.getDI();
1000 DebugLoc dl = DDI.getdl();
1001 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1002 MDLocalVariable *Variable = DI->getVariable();
1003 MDExpression *Expr = DI->getExpression();
1004 assert(Variable->isValidLocationForIntrinsic(dl) &&
1005 "Expected inlined-at fields to agree");
1006 uint64_t Offset = DI->getOffset();
1007 // A dbg.value for an alloca is always indirect.
1008 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
1010 if (Val.getNode()) {
1011 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, IsIndirect,
1013 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1014 IsIndirect, Offset, dl, DbgSDNodeOrder);
1015 DAG.AddDbgValue(SDV, Val.getNode(), false);
1018 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1019 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1023 /// getCopyFromRegs - If there was virtual register allocated for the value V
1024 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1025 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1026 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1029 if (It != FuncInfo.ValueMap.end()) {
1030 unsigned InReg = It->second;
1031 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
1033 SDValue Chain = DAG.getEntryNode();
1034 res = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1035 resolveDanglingDebugInfo(V, res);
1041 /// getValue - Return an SDValue for the given Value.
1042 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1043 // If we already have an SDValue for this value, use it. It's important
1044 // to do this first, so that we don't create a CopyFromReg if we already
1045 // have a regular SDValue.
1046 SDValue &N = NodeMap[V];
1047 if (N.getNode()) return N;
1049 // If there's a virtual register allocated and initialized for this
1051 SDValue copyFromReg = getCopyFromRegs(V, V->getType());
1052 if (copyFromReg.getNode()) {
1056 // Otherwise create a new SDValue and remember it.
1057 SDValue Val = getValueImpl(V);
1059 resolveDanglingDebugInfo(V, Val);
1063 // Return true if SDValue exists for the given Value
1064 bool SelectionDAGBuilder::findValue(const Value *V) const {
1065 return (NodeMap.find(V) != NodeMap.end()) ||
1066 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1069 /// getNonRegisterValue - Return an SDValue for the given Value, but
1070 /// don't look in FuncInfo.ValueMap for a virtual register.
1071 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1072 // If we already have an SDValue for this value, use it.
1073 SDValue &N = NodeMap[V];
1074 if (N.getNode()) return N;
1076 // Otherwise create a new SDValue and remember it.
1077 SDValue Val = getValueImpl(V);
1079 resolveDanglingDebugInfo(V, Val);
1083 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1084 /// Create an SDValue for the given value.
1085 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1088 if (const Constant *C = dyn_cast<Constant>(V)) {
1089 EVT VT = TLI.getValueType(V->getType(), true);
1091 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1092 return DAG.getConstant(*CI, getCurSDLoc(), VT);
1094 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1095 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1097 if (isa<ConstantPointerNull>(C)) {
1098 unsigned AS = V->getType()->getPointerAddressSpace();
1099 return DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(AS));
1102 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1103 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1105 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1106 return DAG.getUNDEF(VT);
1108 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1109 visit(CE->getOpcode(), *CE);
1110 SDValue N1 = NodeMap[V];
1111 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1115 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1116 SmallVector<SDValue, 4> Constants;
1117 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1119 SDNode *Val = getValue(*OI).getNode();
1120 // If the operand is an empty aggregate, there are no values.
1122 // Add each leaf value from the operand to the Constants list
1123 // to form a flattened list of all the values.
1124 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1125 Constants.push_back(SDValue(Val, i));
1128 return DAG.getMergeValues(Constants, getCurSDLoc());
1131 if (const ConstantDataSequential *CDS =
1132 dyn_cast<ConstantDataSequential>(C)) {
1133 SmallVector<SDValue, 4> Ops;
1134 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1135 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1136 // Add each leaf value from the operand to the Constants list
1137 // to form a flattened list of all the values.
1138 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1139 Ops.push_back(SDValue(Val, i));
1142 if (isa<ArrayType>(CDS->getType()))
1143 return DAG.getMergeValues(Ops, getCurSDLoc());
1144 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1148 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1149 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1150 "Unknown struct or array constant!");
1152 SmallVector<EVT, 4> ValueVTs;
1153 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1154 unsigned NumElts = ValueVTs.size();
1156 return SDValue(); // empty struct
1157 SmallVector<SDValue, 4> Constants(NumElts);
1158 for (unsigned i = 0; i != NumElts; ++i) {
1159 EVT EltVT = ValueVTs[i];
1160 if (isa<UndefValue>(C))
1161 Constants[i] = DAG.getUNDEF(EltVT);
1162 else if (EltVT.isFloatingPoint())
1163 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1165 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1168 return DAG.getMergeValues(Constants, getCurSDLoc());
1171 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1172 return DAG.getBlockAddress(BA, VT);
1174 VectorType *VecTy = cast<VectorType>(V->getType());
1175 unsigned NumElements = VecTy->getNumElements();
1177 // Now that we know the number and type of the elements, get that number of
1178 // elements into the Ops array based on what kind of constant it is.
1179 SmallVector<SDValue, 16> Ops;
1180 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1181 for (unsigned i = 0; i != NumElements; ++i)
1182 Ops.push_back(getValue(CV->getOperand(i)));
1184 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1185 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1188 if (EltVT.isFloatingPoint())
1189 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1191 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1192 Ops.assign(NumElements, Op);
1195 // Create a BUILD_VECTOR node.
1196 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1199 // If this is a static alloca, generate it as the frameindex instead of
1201 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1202 DenseMap<const AllocaInst*, int>::iterator SI =
1203 FuncInfo.StaticAllocaMap.find(AI);
1204 if (SI != FuncInfo.StaticAllocaMap.end())
1205 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1208 // If this is an instruction which fast-isel has deferred, select it now.
1209 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1210 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1211 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1212 SDValue Chain = DAG.getEntryNode();
1213 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1216 llvm_unreachable("Can't get register for value!");
1219 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1220 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1221 SDValue Chain = getControlRoot();
1222 SmallVector<ISD::OutputArg, 8> Outs;
1223 SmallVector<SDValue, 8> OutVals;
1225 if (!FuncInfo.CanLowerReturn) {
1226 unsigned DemoteReg = FuncInfo.DemoteRegister;
1227 const Function *F = I.getParent()->getParent();
1229 // Emit a store of the return value through the virtual register.
1230 // Leave Outs empty so that LowerReturn won't try to load return
1231 // registers the usual way.
1232 SmallVector<EVT, 1> PtrValueVTs;
1233 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1236 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1237 SDValue RetOp = getValue(I.getOperand(0));
1239 SmallVector<EVT, 4> ValueVTs;
1240 SmallVector<uint64_t, 4> Offsets;
1241 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1242 unsigned NumValues = ValueVTs.size();
1244 SmallVector<SDValue, 4> Chains(NumValues);
1245 for (unsigned i = 0; i != NumValues; ++i) {
1246 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1247 RetPtr.getValueType(), RetPtr,
1248 DAG.getIntPtrConstant(Offsets[i],
1251 DAG.getStore(Chain, getCurSDLoc(),
1252 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1253 // FIXME: better loc info would be nice.
1254 Add, MachinePointerInfo(), false, false, 0);
1257 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1258 MVT::Other, Chains);
1259 } else if (I.getNumOperands() != 0) {
1260 SmallVector<EVT, 4> ValueVTs;
1261 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1262 unsigned NumValues = ValueVTs.size();
1264 SDValue RetOp = getValue(I.getOperand(0));
1266 const Function *F = I.getParent()->getParent();
1268 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1269 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1271 ExtendKind = ISD::SIGN_EXTEND;
1272 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1274 ExtendKind = ISD::ZERO_EXTEND;
1276 LLVMContext &Context = F->getContext();
1277 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1280 for (unsigned j = 0; j != NumValues; ++j) {
1281 EVT VT = ValueVTs[j];
1283 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1284 VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
1286 unsigned NumParts = TLI.getNumRegisters(Context, VT);
1287 MVT PartVT = TLI.getRegisterType(Context, VT);
1288 SmallVector<SDValue, 4> Parts(NumParts);
1289 getCopyToParts(DAG, getCurSDLoc(),
1290 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1291 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1293 // 'inreg' on function refers to return value
1294 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1298 // Propagate extension type if any
1299 if (ExtendKind == ISD::SIGN_EXTEND)
1301 else if (ExtendKind == ISD::ZERO_EXTEND)
1304 for (unsigned i = 0; i < NumParts; ++i) {
1305 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1306 VT, /*isfixed=*/true, 0, 0));
1307 OutVals.push_back(Parts[i]);
1313 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1314 CallingConv::ID CallConv =
1315 DAG.getMachineFunction().getFunction()->getCallingConv();
1316 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1317 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1319 // Verify that the target's LowerReturn behaved as expected.
1320 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1321 "LowerReturn didn't return a valid chain!");
1323 // Update the DAG with the new chain value resulting from return lowering.
1327 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1328 /// created for it, emit nodes to copy the value into the virtual
1330 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1332 if (V->getType()->isEmptyTy())
1335 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1336 if (VMI != FuncInfo.ValueMap.end()) {
1337 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1338 CopyValueToVirtualRegister(V, VMI->second);
1342 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1343 /// the current basic block, add it to ValueMap now so that we'll get a
1345 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1346 // No need to export constants.
1347 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1349 // Already exported?
1350 if (FuncInfo.isExportedInst(V)) return;
1352 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1353 CopyValueToVirtualRegister(V, Reg);
1356 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1357 const BasicBlock *FromBB) {
1358 // The operands of the setcc have to be in this block. We don't know
1359 // how to export them from some other block.
1360 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1361 // Can export from current BB.
1362 if (VI->getParent() == FromBB)
1365 // Is already exported, noop.
1366 return FuncInfo.isExportedInst(V);
1369 // If this is an argument, we can export it if the BB is the entry block or
1370 // if it is already exported.
1371 if (isa<Argument>(V)) {
1372 if (FromBB == &FromBB->getParent()->getEntryBlock())
1375 // Otherwise, can only export this if it is already exported.
1376 return FuncInfo.isExportedInst(V);
1379 // Otherwise, constants can always be exported.
1383 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1384 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1385 const MachineBasicBlock *Dst) const {
1386 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1389 const BasicBlock *SrcBB = Src->getBasicBlock();
1390 const BasicBlock *DstBB = Dst->getBasicBlock();
1391 return BPI->getEdgeWeight(SrcBB, DstBB);
1394 void SelectionDAGBuilder::
1395 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1396 uint32_t Weight /* = 0 */) {
1398 Weight = getEdgeWeight(Src, Dst);
1399 Src->addSuccessor(Dst, Weight);
1403 static bool InBlock(const Value *V, const BasicBlock *BB) {
1404 if (const Instruction *I = dyn_cast<Instruction>(V))
1405 return I->getParent() == BB;
1409 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1410 /// This function emits a branch and is used at the leaves of an OR or an
1411 /// AND operator tree.
1414 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1415 MachineBasicBlock *TBB,
1416 MachineBasicBlock *FBB,
1417 MachineBasicBlock *CurBB,
1418 MachineBasicBlock *SwitchBB,
1421 const BasicBlock *BB = CurBB->getBasicBlock();
1423 // If the leaf of the tree is a comparison, merge the condition into
1425 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1426 // The operands of the cmp have to be in this block. We don't know
1427 // how to export them from some other block. If this is the first block
1428 // of the sequence, no exporting is needed.
1429 if (CurBB == SwitchBB ||
1430 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1431 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1432 ISD::CondCode Condition;
1433 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1434 Condition = getICmpCondCode(IC->getPredicate());
1435 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1436 Condition = getFCmpCondCode(FC->getPredicate());
1437 if (TM.Options.NoNaNsFPMath)
1438 Condition = getFCmpCodeWithoutNaN(Condition);
1440 (void)Condition; // silence warning.
1441 llvm_unreachable("Unknown compare instruction");
1444 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1445 TBB, FBB, CurBB, TWeight, FWeight);
1446 SwitchCases.push_back(CB);
1451 // Create a CaseBlock record representing this branch.
1452 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1453 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1454 SwitchCases.push_back(CB);
1457 /// Scale down both weights to fit into uint32_t.
1458 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1459 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1460 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1461 NewTrue = NewTrue / Scale;
1462 NewFalse = NewFalse / Scale;
1465 /// FindMergedConditions - If Cond is an expression like
1466 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1467 MachineBasicBlock *TBB,
1468 MachineBasicBlock *FBB,
1469 MachineBasicBlock *CurBB,
1470 MachineBasicBlock *SwitchBB,
1471 unsigned Opc, uint32_t TWeight,
1473 // If this node is not part of the or/and tree, emit it as a branch.
1474 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1475 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1476 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1477 BOp->getParent() != CurBB->getBasicBlock() ||
1478 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1479 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1480 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1485 // Create TmpBB after CurBB.
1486 MachineFunction::iterator BBI = CurBB;
1487 MachineFunction &MF = DAG.getMachineFunction();
1488 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1489 CurBB->getParent()->insert(++BBI, TmpBB);
1491 if (Opc == Instruction::Or) {
1492 // Codegen X | Y as:
1501 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1502 // The requirement is that
1503 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1504 // = TrueProb for orignal BB.
1505 // Assuming the orignal weights are A and B, one choice is to set BB1's
1506 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1508 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1509 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1510 // TmpBB, but the math is more complicated.
1512 uint64_t NewTrueWeight = TWeight;
1513 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1514 ScaleWeights(NewTrueWeight, NewFalseWeight);
1515 // Emit the LHS condition.
1516 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1517 NewTrueWeight, NewFalseWeight);
1519 NewTrueWeight = TWeight;
1520 NewFalseWeight = 2 * (uint64_t)FWeight;
1521 ScaleWeights(NewTrueWeight, NewFalseWeight);
1522 // Emit the RHS condition into TmpBB.
1523 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1524 NewTrueWeight, NewFalseWeight);
1526 assert(Opc == Instruction::And && "Unknown merge op!");
1527 // Codegen X & Y as:
1535 // This requires creation of TmpBB after CurBB.
1537 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1538 // The requirement is that
1539 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1540 // = FalseProb for orignal BB.
1541 // Assuming the orignal weights are A and B, one choice is to set BB1's
1542 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1544 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1546 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1547 uint64_t NewFalseWeight = FWeight;
1548 ScaleWeights(NewTrueWeight, NewFalseWeight);
1549 // Emit the LHS condition.
1550 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1551 NewTrueWeight, NewFalseWeight);
1553 NewTrueWeight = 2 * (uint64_t)TWeight;
1554 NewFalseWeight = FWeight;
1555 ScaleWeights(NewTrueWeight, NewFalseWeight);
1556 // Emit the RHS condition into TmpBB.
1557 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1558 NewTrueWeight, NewFalseWeight);
1562 /// If the set of cases should be emitted as a series of branches, return true.
1563 /// If we should emit this as a bunch of and/or'd together conditions, return
1566 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1567 if (Cases.size() != 2) return true;
1569 // If this is two comparisons of the same values or'd or and'd together, they
1570 // will get folded into a single comparison, so don't emit two blocks.
1571 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1572 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1573 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1574 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1578 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1579 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1580 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1581 Cases[0].CC == Cases[1].CC &&
1582 isa<Constant>(Cases[0].CmpRHS) &&
1583 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1584 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1586 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1593 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1594 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1596 // Update machine-CFG edges.
1597 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1599 if (I.isUnconditional()) {
1600 // Update machine-CFG edges.
1601 BrMBB->addSuccessor(Succ0MBB);
1603 // If this is not a fall-through branch or optimizations are switched off,
1605 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1606 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1607 MVT::Other, getControlRoot(),
1608 DAG.getBasicBlock(Succ0MBB)));
1613 // If this condition is one of the special cases we handle, do special stuff
1615 const Value *CondVal = I.getCondition();
1616 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1618 // If this is a series of conditions that are or'd or and'd together, emit
1619 // this as a sequence of branches instead of setcc's with and/or operations.
1620 // As long as jumps are not expensive, this should improve performance.
1621 // For example, instead of something like:
1634 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1635 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1636 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1637 BOp->getOpcode() == Instruction::Or)) {
1638 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1639 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1640 getEdgeWeight(BrMBB, Succ1MBB));
1641 // If the compares in later blocks need to use values not currently
1642 // exported from this block, export them now. This block should always
1643 // be the first entry.
1644 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1646 // Allow some cases to be rejected.
1647 if (ShouldEmitAsBranches(SwitchCases)) {
1648 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1649 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1650 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1653 // Emit the branch for this block.
1654 visitSwitchCase(SwitchCases[0], BrMBB);
1655 SwitchCases.erase(SwitchCases.begin());
1659 // Okay, we decided not to do this, remove any inserted MBB's and clear
1661 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1662 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1664 SwitchCases.clear();
1668 // Create a CaseBlock record representing this branch.
1669 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1670 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1672 // Use visitSwitchCase to actually insert the fast branch sequence for this
1674 visitSwitchCase(CB, BrMBB);
1677 /// visitSwitchCase - Emits the necessary code to represent a single node in
1678 /// the binary search tree resulting from lowering a switch instruction.
1679 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1680 MachineBasicBlock *SwitchBB) {
1682 SDValue CondLHS = getValue(CB.CmpLHS);
1683 SDLoc dl = getCurSDLoc();
1685 // Build the setcc now.
1687 // Fold "(X == true)" to X and "(X == false)" to !X to
1688 // handle common cases produced by branch lowering.
1689 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1690 CB.CC == ISD::SETEQ)
1692 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1693 CB.CC == ISD::SETEQ) {
1694 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
1695 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1697 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1699 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1701 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1702 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1704 SDValue CmpOp = getValue(CB.CmpMHS);
1705 EVT VT = CmpOp.getValueType();
1707 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1708 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
1711 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1712 VT, CmpOp, DAG.getConstant(Low, dl, VT));
1713 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1714 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
1718 // Update successor info
1719 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1720 // TrueBB and FalseBB are always different unless the incoming IR is
1721 // degenerate. This only happens when running llc on weird IR.
1722 if (CB.TrueBB != CB.FalseBB)
1723 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1725 // If the lhs block is the next block, invert the condition so that we can
1726 // fall through to the lhs instead of the rhs block.
1727 if (CB.TrueBB == NextBlock(SwitchBB)) {
1728 std::swap(CB.TrueBB, CB.FalseBB);
1729 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
1730 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1733 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1734 MVT::Other, getControlRoot(), Cond,
1735 DAG.getBasicBlock(CB.TrueBB));
1737 // Insert the false branch. Do this even if it's a fall through branch,
1738 // this makes it easier to do DAG optimizations which require inverting
1739 // the branch condition.
1740 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1741 DAG.getBasicBlock(CB.FalseBB));
1743 DAG.setRoot(BrCond);
1746 /// visitJumpTable - Emit JumpTable node in the current MBB
1747 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1748 // Emit the code for the jump table
1749 assert(JT.Reg != -1U && "Should lower JT Header first!");
1750 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1751 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1753 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1754 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1755 MVT::Other, Index.getValue(1),
1757 DAG.setRoot(BrJumpTable);
1760 /// visitJumpTableHeader - This function emits necessary code to produce index
1761 /// in the JumpTable from switch case.
1762 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1763 JumpTableHeader &JTH,
1764 MachineBasicBlock *SwitchBB) {
1765 SDLoc dl = getCurSDLoc();
1767 // Subtract the lowest switch case value from the value being switched on and
1768 // conditional branch to default mbb if the result is greater than the
1769 // difference between smallest and largest cases.
1770 SDValue SwitchOp = getValue(JTH.SValue);
1771 EVT VT = SwitchOp.getValueType();
1772 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1773 DAG.getConstant(JTH.First, dl, VT));
1775 // The SDNode we just created, which holds the value being switched on minus
1776 // the smallest case value, needs to be copied to a virtual register so it
1777 // can be used as an index into the jump table in a subsequent basic block.
1778 // This value may be smaller or larger than the target's pointer type, and
1779 // therefore require extension or truncating.
1780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1781 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy());
1783 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1784 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
1785 JumpTableReg, SwitchOp);
1786 JT.Reg = JumpTableReg;
1788 // Emit the range check for the jump table, and branch to the default block
1789 // for the switch statement if the value being switched on exceeds the largest
1790 // case in the switch.
1792 DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
1793 Sub.getValueType()),
1794 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT),
1797 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1798 MVT::Other, CopyTo, CMP,
1799 DAG.getBasicBlock(JT.Default));
1801 // Avoid emitting unnecessary branches to the next block.
1802 if (JT.MBB != NextBlock(SwitchBB))
1803 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1804 DAG.getBasicBlock(JT.MBB));
1806 DAG.setRoot(BrCond);
1809 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1810 /// tail spliced into a stack protector check success bb.
1812 /// For a high level explanation of how this fits into the stack protector
1813 /// generation see the comment on the declaration of class
1814 /// StackProtectorDescriptor.
1815 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1816 MachineBasicBlock *ParentBB) {
1818 // First create the loads to the guard/stack slot for the comparison.
1819 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1820 EVT PtrTy = TLI.getPointerTy();
1822 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1823 int FI = MFI->getStackProtectorIndex();
1825 const Value *IRGuard = SPD.getGuard();
1826 SDValue GuardPtr = getValue(IRGuard);
1827 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1830 TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1833 SDLoc dl = getCurSDLoc();
1835 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1836 // guard value from the virtual register holding the value. Otherwise, emit a
1837 // volatile load to retrieve the stack guard value.
1838 unsigned GuardReg = SPD.getGuardReg();
1840 if (GuardReg && TLI.useLoadStackGuardNode())
1841 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg,
1844 Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
1845 GuardPtr, MachinePointerInfo(IRGuard, 0),
1846 true, false, false, Align);
1848 SDValue StackSlot = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
1850 MachinePointerInfo::getFixedStack(FI),
1851 true, false, false, Align);
1853 // Perform the comparison via a subtract/getsetcc.
1854 EVT VT = Guard.getValueType();
1855 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
1858 DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
1859 Sub.getValueType()),
1860 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
1862 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1863 // branch to failure MBB.
1864 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1865 MVT::Other, StackSlot.getOperand(0),
1866 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1867 // Otherwise branch to success MBB.
1868 SDValue Br = DAG.getNode(ISD::BR, dl,
1870 DAG.getBasicBlock(SPD.getSuccessMBB()));
1875 /// Codegen the failure basic block for a stack protector check.
1877 /// A failure stack protector machine basic block consists simply of a call to
1878 /// __stack_chk_fail().
1880 /// For a high level explanation of how this fits into the stack protector
1881 /// generation see the comment on the declaration of class
1882 /// StackProtectorDescriptor.
1884 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1885 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1887 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1888 nullptr, 0, false, getCurSDLoc(), false, false).second;
1892 /// visitBitTestHeader - This function emits necessary code to produce value
1893 /// suitable for "bit tests"
1894 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1895 MachineBasicBlock *SwitchBB) {
1896 SDLoc dl = getCurSDLoc();
1898 // Subtract the minimum value
1899 SDValue SwitchOp = getValue(B.SValue);
1900 EVT VT = SwitchOp.getValueType();
1901 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1902 DAG.getConstant(B.First, dl, VT));
1905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1907 DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
1908 Sub.getValueType()),
1909 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
1911 // Determine the type of the test operands.
1912 bool UsePtrType = false;
1913 if (!TLI.isTypeLegal(VT))
1916 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1917 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1918 // Switch table case range are encoded into series of masks.
1919 // Just use pointer type, it's guaranteed to fit.
1925 VT = TLI.getPointerTy();
1926 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
1929 B.RegVT = VT.getSimpleVT();
1930 B.Reg = FuncInfo.CreateReg(B.RegVT);
1931 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
1933 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1935 addSuccessorWithWeight(SwitchBB, B.Default);
1936 addSuccessorWithWeight(SwitchBB, MBB);
1938 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
1939 MVT::Other, CopyTo, RangeCmp,
1940 DAG.getBasicBlock(B.Default));
1942 // Avoid emitting unnecessary branches to the next block.
1943 if (MBB != NextBlock(SwitchBB))
1944 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
1945 DAG.getBasicBlock(MBB));
1947 DAG.setRoot(BrRange);
1950 /// visitBitTestCase - this function produces one "bit test"
1951 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1952 MachineBasicBlock* NextMBB,
1953 uint32_t BranchWeightToNext,
1956 MachineBasicBlock *SwitchBB) {
1957 SDLoc dl = getCurSDLoc();
1959 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
1961 unsigned PopCount = countPopulation(B.Mask);
1962 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1963 if (PopCount == 1) {
1964 // Testing for a single bit; just compare the shift count with what it
1965 // would need to be to shift a 1 bit in that position.
1967 dl, TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1968 DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), ISD::SETEQ);
1969 } else if (PopCount == BB.Range) {
1970 // There is only one zero bit in the range, test for it directly.
1972 dl, TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1973 DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), ISD::SETNE);
1975 // Make desired shift
1976 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
1977 DAG.getConstant(1, dl, VT), ShiftOp);
1979 // Emit bit tests and jumps
1980 SDValue AndOp = DAG.getNode(ISD::AND, dl,
1981 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
1982 Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1983 DAG.getConstant(0, dl, VT), ISD::SETNE);
1986 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1987 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1988 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1989 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1991 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
1992 MVT::Other, getControlRoot(),
1993 Cmp, DAG.getBasicBlock(B.TargetBB));
1995 // Avoid emitting unnecessary branches to the next block.
1996 if (NextMBB != NextBlock(SwitchBB))
1997 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
1998 DAG.getBasicBlock(NextMBB));
2003 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2004 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2006 // Retrieve successors.
2007 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2008 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2010 const Value *Callee(I.getCalledValue());
2011 const Function *Fn = dyn_cast<Function>(Callee);
2012 if (isa<InlineAsm>(Callee))
2014 else if (Fn && Fn->isIntrinsic()) {
2015 switch (Fn->getIntrinsicID()) {
2017 llvm_unreachable("Cannot invoke this intrinsic");
2018 case Intrinsic::donothing:
2019 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2021 case Intrinsic::experimental_patchpoint_void:
2022 case Intrinsic::experimental_patchpoint_i64:
2023 visitPatchpoint(&I, LandingPad);
2025 case Intrinsic::experimental_gc_statepoint:
2026 LowerStatepoint(ImmutableStatepoint(&I), LandingPad);
2030 LowerCallTo(&I, getValue(Callee), false, LandingPad);
2032 // If the value of the invoke is used outside of its defining block, make it
2033 // available as a virtual register.
2034 // We already took care of the exported value for the statepoint instruction
2035 // during call to the LowerStatepoint.
2036 if (!isStatepoint(I)) {
2037 CopyToExportRegsIfNeeded(&I);
2040 // Update successor info
2041 addSuccessorWithWeight(InvokeMBB, Return);
2042 addSuccessorWithWeight(InvokeMBB, LandingPad);
2044 // Drop into normal successor.
2045 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2046 MVT::Other, getControlRoot(),
2047 DAG.getBasicBlock(Return)));
2050 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2051 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2054 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2055 assert(FuncInfo.MBB->isLandingPad() &&
2056 "Call to landingpad not in landing pad!");
2058 MachineBasicBlock *MBB = FuncInfo.MBB;
2059 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2060 AddLandingPadInfo(LP, MMI, MBB);
2062 // If there aren't registers to copy the values into (e.g., during SjLj
2063 // exceptions), then don't bother to create these DAG nodes.
2064 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2065 if (TLI.getExceptionPointerRegister() == 0 &&
2066 TLI.getExceptionSelectorRegister() == 0)
2069 SmallVector<EVT, 2> ValueVTs;
2070 SDLoc dl = getCurSDLoc();
2071 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
2072 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2074 // Get the two live-in registers as SDValues. The physregs have already been
2075 // copied into virtual registers.
2077 if (FuncInfo.ExceptionPointerVirtReg) {
2078 Ops[0] = DAG.getZExtOrTrunc(
2079 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2080 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2083 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy());
2085 Ops[1] = DAG.getZExtOrTrunc(
2086 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2087 FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2091 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2092 DAG.getVTList(ValueVTs), Ops);
2097 SelectionDAGBuilder::visitLandingPadClauseBB(GlobalValue *ClauseGV,
2098 MachineBasicBlock *LPadBB) {
2099 SDValue Chain = getControlRoot();
2100 SDLoc dl = getCurSDLoc();
2102 // Get the typeid that we will dispatch on later.
2103 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2104 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy());
2105 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
2106 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(ClauseGV);
2107 SDValue Sel = DAG.getConstant(TypeID, dl, TLI.getPointerTy());
2108 Chain = DAG.getCopyToReg(Chain, dl, VReg, Sel);
2110 // Branch to the main landing pad block.
2111 MachineBasicBlock *ClauseMBB = FuncInfo.MBB;
2112 ClauseMBB->addSuccessor(LPadBB);
2113 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, Chain,
2114 DAG.getBasicBlock(LPadBB)));
2118 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2120 for (const CaseCluster &CC : Clusters)
2121 assert(CC.Low == CC.High && "Input clusters must be single-case");
2124 std::sort(Clusters.begin(), Clusters.end(),
2125 [](const CaseCluster &a, const CaseCluster &b) {
2126 return a.Low->getValue().slt(b.Low->getValue());
2129 // Merge adjacent clusters with the same destination.
2130 const unsigned N = Clusters.size();
2131 unsigned DstIndex = 0;
2132 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2133 CaseCluster &CC = Clusters[SrcIndex];
2134 const ConstantInt *CaseVal = CC.Low;
2135 MachineBasicBlock *Succ = CC.MBB;
2137 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2138 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2139 // If this case has the same successor and is a neighbour, merge it into
2140 // the previous cluster.
2141 Clusters[DstIndex - 1].High = CaseVal;
2142 Clusters[DstIndex - 1].Weight += CC.Weight;
2143 assert(Clusters[DstIndex - 1].Weight >= CC.Weight && "Weight overflow!");
2145 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2146 sizeof(Clusters[SrcIndex]));
2149 Clusters.resize(DstIndex);
2152 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2153 MachineBasicBlock *Last) {
2155 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2156 if (JTCases[i].first.HeaderBB == First)
2157 JTCases[i].first.HeaderBB = Last;
2159 // Update BitTestCases.
2160 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2161 if (BitTestCases[i].Parent == First)
2162 BitTestCases[i].Parent = Last;
2165 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2166 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2168 // Update machine-CFG edges with unique successors.
2169 SmallSet<BasicBlock*, 32> Done;
2170 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2171 BasicBlock *BB = I.getSuccessor(i);
2172 bool Inserted = Done.insert(BB).second;
2176 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2177 addSuccessorWithWeight(IndirectBrMBB, Succ);
2180 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2181 MVT::Other, getControlRoot(),
2182 getValue(I.getAddress())));
2185 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2186 if (DAG.getTarget().Options.TrapUnreachable)
2187 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2190 void SelectionDAGBuilder::visitFSub(const User &I) {
2191 // -0.0 - X --> fneg
2192 Type *Ty = I.getType();
2193 if (isa<Constant>(I.getOperand(0)) &&
2194 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2195 SDValue Op2 = getValue(I.getOperand(1));
2196 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2197 Op2.getValueType(), Op2));
2201 visitBinary(I, ISD::FSUB);
2204 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2205 SDValue Op1 = getValue(I.getOperand(0));
2206 SDValue Op2 = getValue(I.getOperand(1));
2211 if (const OverflowingBinaryOperator *OFBinOp =
2212 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2213 nuw = OFBinOp->hasNoUnsignedWrap();
2214 nsw = OFBinOp->hasNoSignedWrap();
2216 if (const PossiblyExactOperator *ExactOp =
2217 dyn_cast<const PossiblyExactOperator>(&I))
2218 exact = ExactOp->isExact();
2220 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2221 Op1, Op2, nuw, nsw, exact);
2222 setValue(&I, BinNodeValue);
2225 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2226 SDValue Op1 = getValue(I.getOperand(0));
2227 SDValue Op2 = getValue(I.getOperand(1));
2230 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2232 // Coerce the shift amount to the right type if we can.
2233 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2234 unsigned ShiftSize = ShiftTy.getSizeInBits();
2235 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2236 SDLoc DL = getCurSDLoc();
2238 // If the operand is smaller than the shift count type, promote it.
2239 if (ShiftSize > Op2Size)
2240 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2242 // If the operand is larger than the shift count type but the shift
2243 // count type has enough bits to represent any shift value, truncate
2244 // it now. This is a common case and it exposes the truncate to
2245 // optimization early.
2246 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2247 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2248 // Otherwise we'll need to temporarily settle for some other convenient
2249 // type. Type legalization will make adjustments once the shiftee is split.
2251 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2258 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2260 if (const OverflowingBinaryOperator *OFBinOp =
2261 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2262 nuw = OFBinOp->hasNoUnsignedWrap();
2263 nsw = OFBinOp->hasNoSignedWrap();
2265 if (const PossiblyExactOperator *ExactOp =
2266 dyn_cast<const PossiblyExactOperator>(&I))
2267 exact = ExactOp->isExact();
2270 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2275 void SelectionDAGBuilder::visitSDiv(const User &I) {
2276 SDValue Op1 = getValue(I.getOperand(0));
2277 SDValue Op2 = getValue(I.getOperand(1));
2279 // Turn exact SDivs into multiplications.
2280 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2282 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2283 !isa<ConstantSDNode>(Op1) &&
2284 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2285 setValue(&I, DAG.getTargetLoweringInfo()
2286 .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
2288 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2292 void SelectionDAGBuilder::visitICmp(const User &I) {
2293 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2294 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2295 predicate = IC->getPredicate();
2296 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2297 predicate = ICmpInst::Predicate(IC->getPredicate());
2298 SDValue Op1 = getValue(I.getOperand(0));
2299 SDValue Op2 = getValue(I.getOperand(1));
2300 ISD::CondCode Opcode = getICmpCondCode(predicate);
2302 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2303 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2306 void SelectionDAGBuilder::visitFCmp(const User &I) {
2307 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2308 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2309 predicate = FC->getPredicate();
2310 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2311 predicate = FCmpInst::Predicate(FC->getPredicate());
2312 SDValue Op1 = getValue(I.getOperand(0));
2313 SDValue Op2 = getValue(I.getOperand(1));
2314 ISD::CondCode Condition = getFCmpCondCode(predicate);
2315 if (TM.Options.NoNaNsFPMath)
2316 Condition = getFCmpCodeWithoutNaN(Condition);
2317 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2318 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2321 void SelectionDAGBuilder::visitSelect(const User &I) {
2322 SmallVector<EVT, 4> ValueVTs;
2323 ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
2324 unsigned NumValues = ValueVTs.size();
2325 if (NumValues == 0) return;
2327 SmallVector<SDValue, 4> Values(NumValues);
2328 SDValue Cond = getValue(I.getOperand(0));
2329 SDValue TrueVal = getValue(I.getOperand(1));
2330 SDValue FalseVal = getValue(I.getOperand(2));
2331 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2332 ISD::VSELECT : ISD::SELECT;
2334 for (unsigned i = 0; i != NumValues; ++i)
2335 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2336 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2338 SDValue(TrueVal.getNode(),
2339 TrueVal.getResNo() + i),
2340 SDValue(FalseVal.getNode(),
2341 FalseVal.getResNo() + i));
2343 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2344 DAG.getVTList(ValueVTs), Values));
2347 void SelectionDAGBuilder::visitTrunc(const User &I) {
2348 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2349 SDValue N = getValue(I.getOperand(0));
2350 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2351 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2354 void SelectionDAGBuilder::visitZExt(const User &I) {
2355 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2356 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2357 SDValue N = getValue(I.getOperand(0));
2358 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2359 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2362 void SelectionDAGBuilder::visitSExt(const User &I) {
2363 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2364 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2365 SDValue N = getValue(I.getOperand(0));
2366 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2367 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2370 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2371 // FPTrunc is never a no-op cast, no need to check
2372 SDValue N = getValue(I.getOperand(0));
2373 SDLoc dl = getCurSDLoc();
2374 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2375 EVT DestVT = TLI.getValueType(I.getType());
2376 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
2377 DAG.getTargetConstant(0, dl, TLI.getPointerTy())));
2380 void SelectionDAGBuilder::visitFPExt(const User &I) {
2381 // FPExt is never a no-op cast, no need to check
2382 SDValue N = getValue(I.getOperand(0));
2383 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2384 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2387 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2388 // FPToUI is never a no-op cast, no need to check
2389 SDValue N = getValue(I.getOperand(0));
2390 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2391 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2394 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2395 // FPToSI is never a no-op cast, no need to check
2396 SDValue N = getValue(I.getOperand(0));
2397 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2398 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2401 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2402 // UIToFP is never a no-op cast, no need to check
2403 SDValue N = getValue(I.getOperand(0));
2404 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2405 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2408 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2409 // SIToFP is never a no-op cast, no need to check
2410 SDValue N = getValue(I.getOperand(0));
2411 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2412 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2415 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2416 // What to do depends on the size of the integer and the size of the pointer.
2417 // We can either truncate, zero extend, or no-op, accordingly.
2418 SDValue N = getValue(I.getOperand(0));
2419 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2420 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2423 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2424 // What to do depends on the size of the integer and the size of the pointer.
2425 // We can either truncate, zero extend, or no-op, accordingly.
2426 SDValue N = getValue(I.getOperand(0));
2427 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2428 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2431 void SelectionDAGBuilder::visitBitCast(const User &I) {
2432 SDValue N = getValue(I.getOperand(0));
2433 SDLoc dl = getCurSDLoc();
2434 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2436 // BitCast assures us that source and destination are the same size so this is
2437 // either a BITCAST or a no-op.
2438 if (DestVT != N.getValueType())
2439 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
2440 DestVT, N)); // convert types.
2441 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2442 // might fold any kind of constant expression to an integer constant and that
2443 // is not what we are looking for. Only regcognize a bitcast of a genuine
2444 // constant integer as an opaque constant.
2445 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2446 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
2449 setValue(&I, N); // noop cast.
2452 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2453 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2454 const Value *SV = I.getOperand(0);
2455 SDValue N = getValue(SV);
2456 EVT DestVT = TLI.getValueType(I.getType());
2458 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2459 unsigned DestAS = I.getType()->getPointerAddressSpace();
2461 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2462 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2467 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2468 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2469 SDValue InVec = getValue(I.getOperand(0));
2470 SDValue InVal = getValue(I.getOperand(1));
2471 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
2472 getCurSDLoc(), TLI.getVectorIdxTy());
2473 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2474 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
2477 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2478 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2479 SDValue InVec = getValue(I.getOperand(0));
2480 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
2481 getCurSDLoc(), TLI.getVectorIdxTy());
2482 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2483 TLI.getValueType(I.getType()), InVec, InIdx));
2486 // Utility for visitShuffleVector - Return true if every element in Mask,
2487 // beginning from position Pos and ending in Pos+Size, falls within the
2488 // specified sequential range [L, L+Pos). or is undef.
2489 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
2490 unsigned Pos, unsigned Size, int Low) {
2491 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
2492 if (Mask[i] >= 0 && Mask[i] != Low)
2497 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2498 SDValue Src1 = getValue(I.getOperand(0));
2499 SDValue Src2 = getValue(I.getOperand(1));
2501 SmallVector<int, 8> Mask;
2502 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2503 unsigned MaskNumElts = Mask.size();
2505 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2506 EVT VT = TLI.getValueType(I.getType());
2507 EVT SrcVT = Src1.getValueType();
2508 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2510 if (SrcNumElts == MaskNumElts) {
2511 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2516 // Normalize the shuffle vector since mask and vector length don't match.
2517 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2518 // Mask is longer than the source vectors and is a multiple of the source
2519 // vectors. We can use concatenate vector to make the mask and vectors
2521 if (SrcNumElts*2 == MaskNumElts) {
2522 // First check for Src1 in low and Src2 in high
2523 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
2524 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
2525 // The shuffle is concatenating two vectors together.
2526 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2530 // Then check for Src2 in low and Src1 in high
2531 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
2532 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
2533 // The shuffle is concatenating two vectors together.
2534 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2540 // Pad both vectors with undefs to make them the same length as the mask.
2541 unsigned NumConcat = MaskNumElts / SrcNumElts;
2542 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2543 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2544 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2546 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2547 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2551 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2552 getCurSDLoc(), VT, MOps1);
2553 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2554 getCurSDLoc(), VT, MOps2);
2556 // Readjust mask for new input vector length.
2557 SmallVector<int, 8> MappedOps;
2558 for (unsigned i = 0; i != MaskNumElts; ++i) {
2560 if (Idx >= (int)SrcNumElts)
2561 Idx -= SrcNumElts - MaskNumElts;
2562 MappedOps.push_back(Idx);
2565 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2570 if (SrcNumElts > MaskNumElts) {
2571 // Analyze the access pattern of the vector to see if we can extract
2572 // two subvectors and do the shuffle. The analysis is done by calculating
2573 // the range of elements the mask access on both vectors.
2574 int MinRange[2] = { static_cast<int>(SrcNumElts),
2575 static_cast<int>(SrcNumElts)};
2576 int MaxRange[2] = {-1, -1};
2578 for (unsigned i = 0; i != MaskNumElts; ++i) {
2584 if (Idx >= (int)SrcNumElts) {
2588 if (Idx > MaxRange[Input])
2589 MaxRange[Input] = Idx;
2590 if (Idx < MinRange[Input])
2591 MinRange[Input] = Idx;
2594 // Check if the access is smaller than the vector size and can we find
2595 // a reasonable extract index.
2596 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
2598 int StartIdx[2]; // StartIdx to extract from
2599 for (unsigned Input = 0; Input < 2; ++Input) {
2600 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
2601 RangeUse[Input] = 0; // Unused
2602 StartIdx[Input] = 0;
2606 // Find a good start index that is a multiple of the mask length. Then
2607 // see if the rest of the elements are in range.
2608 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2609 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2610 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2611 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2614 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2615 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2618 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
2619 // Extract appropriate subvector and generate a vector shuffle
2620 for (unsigned Input = 0; Input < 2; ++Input) {
2621 SDValue &Src = Input == 0 ? Src1 : Src2;
2622 if (RangeUse[Input] == 0)
2623 Src = DAG.getUNDEF(VT);
2625 SDLoc dl = getCurSDLoc();
2627 ISD::EXTRACT_SUBVECTOR, dl, VT, Src,
2628 DAG.getConstant(StartIdx[Input], dl, TLI.getVectorIdxTy()));
2632 // Calculate new mask.
2633 SmallVector<int, 8> MappedOps;
2634 for (unsigned i = 0; i != MaskNumElts; ++i) {
2637 if (Idx < (int)SrcNumElts)
2640 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
2642 MappedOps.push_back(Idx);
2645 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2651 // We can't use either concat vectors or extract subvectors so fall back to
2652 // replacing the shuffle with extract and build vector.
2653 // to insert and build vector.
2654 EVT EltVT = VT.getVectorElementType();
2655 EVT IdxVT = TLI.getVectorIdxTy();
2656 SDLoc dl = getCurSDLoc();
2657 SmallVector<SDValue,8> Ops;
2658 for (unsigned i = 0; i != MaskNumElts; ++i) {
2663 Res = DAG.getUNDEF(EltVT);
2665 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
2666 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
2668 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2669 EltVT, Src, DAG.getConstant(Idx, dl, IdxVT));
2675 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops));
2678 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2679 const Value *Op0 = I.getOperand(0);
2680 const Value *Op1 = I.getOperand(1);
2681 Type *AggTy = I.getType();
2682 Type *ValTy = Op1->getType();
2683 bool IntoUndef = isa<UndefValue>(Op0);
2684 bool FromUndef = isa<UndefValue>(Op1);
2686 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2688 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2689 SmallVector<EVT, 4> AggValueVTs;
2690 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2691 SmallVector<EVT, 4> ValValueVTs;
2692 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2694 unsigned NumAggValues = AggValueVTs.size();
2695 unsigned NumValValues = ValValueVTs.size();
2696 SmallVector<SDValue, 4> Values(NumAggValues);
2698 // Ignore an insertvalue that produces an empty object
2699 if (!NumAggValues) {
2700 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2704 SDValue Agg = getValue(Op0);
2706 // Copy the beginning value(s) from the original aggregate.
2707 for (; i != LinearIndex; ++i)
2708 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2709 SDValue(Agg.getNode(), Agg.getResNo() + i);
2710 // Copy values from the inserted value(s).
2712 SDValue Val = getValue(Op1);
2713 for (; i != LinearIndex + NumValValues; ++i)
2714 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2715 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2717 // Copy remaining value(s) from the original aggregate.
2718 for (; i != NumAggValues; ++i)
2719 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2720 SDValue(Agg.getNode(), Agg.getResNo() + i);
2722 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2723 DAG.getVTList(AggValueVTs), Values));
2726 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2727 const Value *Op0 = I.getOperand(0);
2728 Type *AggTy = Op0->getType();
2729 Type *ValTy = I.getType();
2730 bool OutOfUndef = isa<UndefValue>(Op0);
2732 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2734 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2735 SmallVector<EVT, 4> ValValueVTs;
2736 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2738 unsigned NumValValues = ValValueVTs.size();
2740 // Ignore a extractvalue that produces an empty object
2741 if (!NumValValues) {
2742 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2746 SmallVector<SDValue, 4> Values(NumValValues);
2748 SDValue Agg = getValue(Op0);
2749 // Copy out the selected value(s).
2750 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2751 Values[i - LinearIndex] =
2753 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2754 SDValue(Agg.getNode(), Agg.getResNo() + i);
2756 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2757 DAG.getVTList(ValValueVTs), Values));
2760 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2761 Value *Op0 = I.getOperand(0);
2762 // Note that the pointer operand may be a vector of pointers. Take the scalar
2763 // element which holds a pointer.
2764 Type *Ty = Op0->getType()->getScalarType();
2765 unsigned AS = Ty->getPointerAddressSpace();
2766 SDValue N = getValue(Op0);
2767 SDLoc dl = getCurSDLoc();
2769 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2771 const Value *Idx = *OI;
2772 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
2773 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
2776 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
2777 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
2778 DAG.getConstant(Offset, dl, N.getValueType()));
2781 Ty = StTy->getElementType(Field);
2783 Ty = cast<SequentialType>(Ty)->getElementType();
2784 MVT PtrTy = DAG.getTargetLoweringInfo().getPointerTy(AS);
2785 unsigned PtrSize = PtrTy.getSizeInBits();
2786 APInt ElementSize(PtrSize, DL->getTypeAllocSize(Ty));
2788 // If this is a constant subscript, handle it quickly.
2789 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
2792 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
2793 SDValue OffsVal = DAG.getConstant(Offs, dl, PtrTy);
2794 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal);
2798 // N = N + Idx * ElementSize;
2799 SDValue IdxN = getValue(Idx);
2801 // If the index is smaller or larger than intptr_t, truncate or extend
2803 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
2805 // If this is a multiply by a power of two, turn it into a shl
2806 // immediately. This is a very common case.
2807 if (ElementSize != 1) {
2808 if (ElementSize.isPowerOf2()) {
2809 unsigned Amt = ElementSize.logBase2();
2810 IdxN = DAG.getNode(ISD::SHL, dl,
2811 N.getValueType(), IdxN,
2812 DAG.getConstant(Amt, dl, IdxN.getValueType()));
2814 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
2815 IdxN = DAG.getNode(ISD::MUL, dl,
2816 N.getValueType(), IdxN, Scale);
2820 N = DAG.getNode(ISD::ADD, dl,
2821 N.getValueType(), N, IdxN);
2828 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2829 // If this is a fixed sized alloca in the entry block of the function,
2830 // allocate it statically on the stack.
2831 if (FuncInfo.StaticAllocaMap.count(&I))
2832 return; // getValue will auto-populate this.
2834 SDLoc dl = getCurSDLoc();
2835 Type *Ty = I.getAllocatedType();
2836 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2837 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
2839 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
2842 SDValue AllocSize = getValue(I.getArraySize());
2844 EVT IntPtr = TLI.getPointerTy();
2845 if (AllocSize.getValueType() != IntPtr)
2846 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
2848 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
2850 DAG.getConstant(TySize, dl, IntPtr));
2852 // Handle alignment. If the requested alignment is less than or equal to
2853 // the stack alignment, ignore it. If the size is greater than or equal to
2854 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2855 unsigned StackAlign =
2856 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
2857 if (Align <= StackAlign)
2860 // Round the size of the allocation up to the stack alignment size
2861 // by add SA-1 to the size.
2862 AllocSize = DAG.getNode(ISD::ADD, dl,
2863 AllocSize.getValueType(), AllocSize,
2864 DAG.getIntPtrConstant(StackAlign - 1, dl));
2866 // Mask out the low bits for alignment purposes.
2867 AllocSize = DAG.getNode(ISD::AND, dl,
2868 AllocSize.getValueType(), AllocSize,
2869 DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
2872 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
2873 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2874 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
2876 DAG.setRoot(DSA.getValue(1));
2878 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
2881 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
2883 return visitAtomicLoad(I);
2885 const Value *SV = I.getOperand(0);
2886 SDValue Ptr = getValue(SV);
2888 Type *Ty = I.getType();
2890 bool isVolatile = I.isVolatile();
2891 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
2892 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
2893 unsigned Alignment = I.getAlignment();
2896 I.getAAMetadata(AAInfo);
2897 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
2899 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2900 SmallVector<EVT, 4> ValueVTs;
2901 SmallVector<uint64_t, 4> Offsets;
2902 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2903 unsigned NumValues = ValueVTs.size();
2908 bool ConstantMemory = false;
2909 if (isVolatile || NumValues > MaxParallelChains)
2910 // Serialize volatile loads with other side effects.
2912 else if (AA->pointsToConstantMemory(
2913 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
2914 // Do not serialize (non-volatile) loads of constant memory with anything.
2915 Root = DAG.getEntryNode();
2916 ConstantMemory = true;
2918 // Do not serialize non-volatile loads against each other.
2919 Root = DAG.getRoot();
2922 SDLoc dl = getCurSDLoc();
2925 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
2927 SmallVector<SDValue, 4> Values(NumValues);
2928 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
2930 EVT PtrVT = Ptr.getValueType();
2931 unsigned ChainI = 0;
2932 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
2933 // Serializing loads here may result in excessive register pressure, and
2934 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
2935 // could recover a bit by hoisting nodes upward in the chain by recognizing
2936 // they are side-effect free or do not alias. The optimizer should really
2937 // avoid this case by converting large object/array copies to llvm.memcpy
2938 // (MaxParallelChains should always remain as failsafe).
2939 if (ChainI == MaxParallelChains) {
2940 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
2941 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2942 makeArrayRef(Chains.data(), ChainI));
2946 SDValue A = DAG.getNode(ISD::ADD, dl,
2948 DAG.getConstant(Offsets[i], dl, PtrVT));
2949 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root,
2950 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
2951 isNonTemporal, isInvariant, Alignment, AAInfo,
2955 Chains[ChainI] = L.getValue(1);
2958 if (!ConstantMemory) {
2959 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2960 makeArrayRef(Chains.data(), ChainI));
2964 PendingLoads.push_back(Chain);
2967 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
2968 DAG.getVTList(ValueVTs), Values));
2971 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
2973 return visitAtomicStore(I);
2975 const Value *SrcV = I.getOperand(0);
2976 const Value *PtrV = I.getOperand(1);
2978 SmallVector<EVT, 4> ValueVTs;
2979 SmallVector<uint64_t, 4> Offsets;
2980 ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
2981 ValueVTs, &Offsets);
2982 unsigned NumValues = ValueVTs.size();
2986 // Get the lowered operands. Note that we do this after
2987 // checking if NumResults is zero, because with zero results
2988 // the operands won't have values in the map.
2989 SDValue Src = getValue(SrcV);
2990 SDValue Ptr = getValue(PtrV);
2992 SDValue Root = getRoot();
2993 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
2995 EVT PtrVT = Ptr.getValueType();
2996 bool isVolatile = I.isVolatile();
2997 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
2998 unsigned Alignment = I.getAlignment();
2999 SDLoc dl = getCurSDLoc();
3002 I.getAAMetadata(AAInfo);
3004 unsigned ChainI = 0;
3005 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3006 // See visitLoad comments.
3007 if (ChainI == MaxParallelChains) {
3008 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3009 makeArrayRef(Chains.data(), ChainI));
3013 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3014 DAG.getConstant(Offsets[i], dl, PtrVT));
3015 SDValue St = DAG.getStore(Root, dl,
3016 SDValue(Src.getNode(), Src.getResNo() + i),
3017 Add, MachinePointerInfo(PtrV, Offsets[i]),
3018 isVolatile, isNonTemporal, Alignment, AAInfo);
3019 Chains[ChainI] = St;
3022 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3023 makeArrayRef(Chains.data(), ChainI));
3024 DAG.setRoot(StoreNode);
3027 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3028 SDLoc sdl = getCurSDLoc();
3030 // llvm.masked.store.*(Src0, Ptr, alignemt, Mask)
3031 Value *PtrOperand = I.getArgOperand(1);
3032 SDValue Ptr = getValue(PtrOperand);
3033 SDValue Src0 = getValue(I.getArgOperand(0));
3034 SDValue Mask = getValue(I.getArgOperand(3));
3035 EVT VT = Src0.getValueType();
3036 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3038 Alignment = DAG.getEVTAlignment(VT);
3041 I.getAAMetadata(AAInfo);
3043 MachineMemOperand *MMO =
3044 DAG.getMachineFunction().
3045 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3046 MachineMemOperand::MOStore, VT.getStoreSize(),
3048 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3050 DAG.setRoot(StoreNode);
3051 setValue(&I, StoreNode);
3054 // Gather/scatter receive a vector of pointers.
3055 // This vector of pointers may be represented as a base pointer + vector of
3056 // indices, it depends on GEP and instruction preceeding GEP
3057 // that calculates indices
3058 static bool getUniformBase(Value *& Ptr, SDValue& Base, SDValue& Index,
3059 SelectionDAGBuilder* SDB) {
3061 assert (Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3062 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
3063 if (!Gep || Gep->getNumOperands() > 2)
3065 ShuffleVectorInst *ShuffleInst =
3066 dyn_cast<ShuffleVectorInst>(Gep->getPointerOperand());
3067 if (!ShuffleInst || !ShuffleInst->getMask()->isNullValue() ||
3068 cast<Instruction>(ShuffleInst->getOperand(0))->getOpcode() !=
3069 Instruction::InsertElement)
3072 Ptr = cast<InsertElementInst>(ShuffleInst->getOperand(0))->getOperand(1);
3074 SelectionDAG& DAG = SDB->DAG;
3075 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3076 // Check is the Ptr is inside current basic block
3077 // If not, look for the shuffle instruction
3078 if (SDB->findValue(Ptr))
3079 Base = SDB->getValue(Ptr);
3080 else if (SDB->findValue(ShuffleInst)) {
3081 SDValue ShuffleNode = SDB->getValue(ShuffleInst);
3082 SDLoc sdl = ShuffleNode;
3083 Base = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl,
3084 ShuffleNode.getValueType().getScalarType(), ShuffleNode,
3085 DAG.getConstant(0, sdl, TLI.getVectorIdxTy()));
3086 SDB->setValue(Ptr, Base);
3091 Value *IndexVal = Gep->getOperand(1);
3092 if (SDB->findValue(IndexVal)) {
3093 Index = SDB->getValue(IndexVal);
3095 if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
3096 IndexVal = Sext->getOperand(0);
3097 if (SDB->findValue(IndexVal))
3098 Index = SDB->getValue(IndexVal);
3105 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3106 SDLoc sdl = getCurSDLoc();
3108 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3109 Value *Ptr = I.getArgOperand(1);
3110 SDValue Src0 = getValue(I.getArgOperand(0));
3111 SDValue Mask = getValue(I.getArgOperand(3));
3112 EVT VT = Src0.getValueType();
3113 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3115 Alignment = DAG.getEVTAlignment(VT);
3116 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3119 I.getAAMetadata(AAInfo);
3123 Value *BasePtr = Ptr;
3124 bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3126 Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3127 MachineMemOperand *MMO = DAG.getMachineFunction().
3128 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3129 MachineMemOperand::MOStore, VT.getStoreSize(),
3132 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy());
3133 Index = getValue(Ptr);
3135 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
3136 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3138 DAG.setRoot(Scatter);
3139 setValue(&I, Scatter);
3142 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3143 SDLoc sdl = getCurSDLoc();
3145 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
3146 Value *PtrOperand = I.getArgOperand(0);
3147 SDValue Ptr = getValue(PtrOperand);
3148 SDValue Src0 = getValue(I.getArgOperand(3));
3149 SDValue Mask = getValue(I.getArgOperand(2));
3151 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3152 EVT VT = TLI.getValueType(I.getType());
3153 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3155 Alignment = DAG.getEVTAlignment(VT);
3158 I.getAAMetadata(AAInfo);
3159 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3161 SDValue InChain = DAG.getRoot();
3162 if (AA->pointsToConstantMemory(
3163 AliasAnalysis::Location(PtrOperand,
3164 AA->getTypeStoreSize(I.getType()),
3166 // Do not serialize (non-volatile) loads of constant memory with anything.
3167 InChain = DAG.getEntryNode();
3170 MachineMemOperand *MMO =
3171 DAG.getMachineFunction().
3172 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3173 MachineMemOperand::MOLoad, VT.getStoreSize(),
3174 Alignment, AAInfo, Ranges);
3176 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
3178 SDValue OutChain = Load.getValue(1);
3179 DAG.setRoot(OutChain);
3183 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
3184 SDLoc sdl = getCurSDLoc();
3186 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
3187 Value *Ptr = I.getArgOperand(0);
3188 SDValue Src0 = getValue(I.getArgOperand(3));
3189 SDValue Mask = getValue(I.getArgOperand(2));
3191 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3192 EVT VT = TLI.getValueType(I.getType());
3193 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3195 Alignment = DAG.getEVTAlignment(VT);
3198 I.getAAMetadata(AAInfo);
3199 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3201 SDValue Root = DAG.getRoot();
3204 Value *BasePtr = Ptr;
3205 bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3206 bool ConstantMemory = false;
3207 if (UniformBase && AA->pointsToConstantMemory(
3208 AliasAnalysis::Location(BasePtr,
3209 AA->getTypeStoreSize(I.getType()),
3211 // Do not serialize (non-volatile) loads of constant memory with anything.
3212 Root = DAG.getEntryNode();
3213 ConstantMemory = true;
3216 MachineMemOperand *MMO =
3217 DAG.getMachineFunction().
3218 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
3219 MachineMemOperand::MOLoad, VT.getStoreSize(),
3220 Alignment, AAInfo, Ranges);
3223 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy());
3224 Index = getValue(Ptr);
3226 SDValue Ops[] = { Root, Src0, Mask, Base, Index };
3227 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
3230 SDValue OutChain = Gather.getValue(1);
3231 if (!ConstantMemory)
3232 PendingLoads.push_back(OutChain);
3233 setValue(&I, Gather);
3236 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3237 SDLoc dl = getCurSDLoc();
3238 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3239 AtomicOrdering FailureOrder = I.getFailureOrdering();
3240 SynchronizationScope Scope = I.getSynchScope();
3242 SDValue InChain = getRoot();
3244 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3245 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3246 SDValue L = DAG.getAtomicCmpSwap(
3247 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3248 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3249 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3250 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3252 SDValue OutChain = L.getValue(2);
3255 DAG.setRoot(OutChain);
3258 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3259 SDLoc dl = getCurSDLoc();
3261 switch (I.getOperation()) {
3262 default: llvm_unreachable("Unknown atomicrmw operation");
3263 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3264 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3265 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3266 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3267 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3268 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3269 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3270 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3271 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3272 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3273 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3275 AtomicOrdering Order = I.getOrdering();
3276 SynchronizationScope Scope = I.getSynchScope();
3278 SDValue InChain = getRoot();
3281 DAG.getAtomic(NT, dl,
3282 getValue(I.getValOperand()).getSimpleValueType(),
3284 getValue(I.getPointerOperand()),
3285 getValue(I.getValOperand()),
3286 I.getPointerOperand(),
3287 /* Alignment=*/ 0, Order, Scope);
3289 SDValue OutChain = L.getValue(1);
3292 DAG.setRoot(OutChain);
3295 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3296 SDLoc dl = getCurSDLoc();
3297 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3300 Ops[1] = DAG.getConstant(I.getOrdering(), dl, TLI.getPointerTy());
3301 Ops[2] = DAG.getConstant(I.getSynchScope(), dl, TLI.getPointerTy());
3302 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3305 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3306 SDLoc dl = getCurSDLoc();
3307 AtomicOrdering Order = I.getOrdering();
3308 SynchronizationScope Scope = I.getSynchScope();
3310 SDValue InChain = getRoot();
3312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3313 EVT VT = TLI.getValueType(I.getType());
3315 if (I.getAlignment() < VT.getSizeInBits() / 8)
3316 report_fatal_error("Cannot generate unaligned atomic load");
3318 MachineMemOperand *MMO =
3319 DAG.getMachineFunction().
3320 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3321 MachineMemOperand::MOVolatile |
3322 MachineMemOperand::MOLoad,
3324 I.getAlignment() ? I.getAlignment() :
3325 DAG.getEVTAlignment(VT));
3327 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3329 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3330 getValue(I.getPointerOperand()), MMO,
3333 SDValue OutChain = L.getValue(1);
3336 DAG.setRoot(OutChain);
3339 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3340 SDLoc dl = getCurSDLoc();
3342 AtomicOrdering Order = I.getOrdering();
3343 SynchronizationScope Scope = I.getSynchScope();
3345 SDValue InChain = getRoot();
3347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3348 EVT VT = TLI.getValueType(I.getValueOperand()->getType());
3350 if (I.getAlignment() < VT.getSizeInBits() / 8)
3351 report_fatal_error("Cannot generate unaligned atomic store");
3354 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3356 getValue(I.getPointerOperand()),
3357 getValue(I.getValueOperand()),
3358 I.getPointerOperand(), I.getAlignment(),
3361 DAG.setRoot(OutChain);
3364 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3366 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3367 unsigned Intrinsic) {
3368 bool HasChain = !I.doesNotAccessMemory();
3369 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3371 // Build the operand list.
3372 SmallVector<SDValue, 8> Ops;
3373 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3375 // We don't need to serialize loads against other loads.
3376 Ops.push_back(DAG.getRoot());
3378 Ops.push_back(getRoot());
3382 // Info is set by getTgtMemInstrinsic
3383 TargetLowering::IntrinsicInfo Info;
3384 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3385 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3387 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3388 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3389 Info.opc == ISD::INTRINSIC_W_CHAIN)
3390 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
3391 TLI.getPointerTy()));
3393 // Add all operands of the call to the operand list.
3394 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3395 SDValue Op = getValue(I.getArgOperand(i));
3399 SmallVector<EVT, 4> ValueVTs;
3400 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3403 ValueVTs.push_back(MVT::Other);
3405 SDVTList VTs = DAG.getVTList(ValueVTs);
3409 if (IsTgtIntrinsic) {
3410 // This is target intrinsic that touches memory
3411 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3412 VTs, Ops, Info.memVT,
3413 MachinePointerInfo(Info.ptrVal, Info.offset),
3414 Info.align, Info.vol,
3415 Info.readMem, Info.writeMem, Info.size);
3416 } else if (!HasChain) {
3417 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3418 } else if (!I.getType()->isVoidTy()) {
3419 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3421 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3425 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3427 PendingLoads.push_back(Chain);
3432 if (!I.getType()->isVoidTy()) {
3433 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3434 EVT VT = TLI.getValueType(PTy);
3435 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3438 setValue(&I, Result);
3442 /// GetSignificand - Get the significand and build it into a floating-point
3443 /// number with exponent of 1:
3445 /// Op = (Op & 0x007fffff) | 0x3f800000;
3447 /// where Op is the hexadecimal representation of floating point value.
3449 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3450 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3451 DAG.getConstant(0x007fffff, dl, MVT::i32));
3452 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3453 DAG.getConstant(0x3f800000, dl, MVT::i32));
3454 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3457 /// GetExponent - Get the exponent:
3459 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3461 /// where Op is the hexadecimal representation of floating point value.
3463 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3465 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3466 DAG.getConstant(0x7f800000, dl, MVT::i32));
3467 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3468 DAG.getConstant(23, dl, TLI.getPointerTy()));
3469 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3470 DAG.getConstant(127, dl, MVT::i32));
3471 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3474 /// getF32Constant - Get 32-bit floating point constant.
3476 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) {
3477 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
3481 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
3482 SelectionDAG &DAG) {
3483 // IntegerPartOfX = ((int32_t)(t0);
3484 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3486 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
3487 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3488 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3490 // IntegerPartOfX <<= 23;
3491 IntegerPartOfX = DAG.getNode(
3492 ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3493 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy()));
3495 SDValue TwoToFractionalPartOfX;
3496 if (LimitFloatPrecision <= 6) {
3497 // For floating-point precision of 6:
3499 // TwoToFractionalPartOfX =
3501 // (0.735607626f + 0.252464424f * x) * x;
3503 // error 0.0144103317, which is 6 bits
3504 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3505 getF32Constant(DAG, 0x3e814304, dl));
3506 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3507 getF32Constant(DAG, 0x3f3c50c8, dl));
3508 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3509 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3510 getF32Constant(DAG, 0x3f7f5e7e, dl));
3511 } else if (LimitFloatPrecision <= 12) {
3512 // For floating-point precision of 12:
3514 // TwoToFractionalPartOfX =
3517 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3519 // error 0.000107046256, which is 13 to 14 bits
3520 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3521 getF32Constant(DAG, 0x3da235e3, dl));
3522 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3523 getF32Constant(DAG, 0x3e65b8f3, dl));
3524 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3525 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3526 getF32Constant(DAG, 0x3f324b07, dl));
3527 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3528 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3529 getF32Constant(DAG, 0x3f7ff8fd, dl));
3530 } else { // LimitFloatPrecision <= 18
3531 // For floating-point precision of 18:
3533 // TwoToFractionalPartOfX =
3537 // (0.554906021e-1f +
3538 // (0.961591928e-2f +
3539 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3540 // error 2.47208000*10^(-7), which is better than 18 bits
3541 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3542 getF32Constant(DAG, 0x3924b03e, dl));
3543 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3544 getF32Constant(DAG, 0x3ab24b87, dl));
3545 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3546 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3547 getF32Constant(DAG, 0x3c1d8c17, dl));
3548 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3549 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3550 getF32Constant(DAG, 0x3d634a1d, dl));
3551 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3552 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3553 getF32Constant(DAG, 0x3e75fe14, dl));
3554 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3555 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3556 getF32Constant(DAG, 0x3f317234, dl));
3557 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3558 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3559 getF32Constant(DAG, 0x3f800000, dl));
3562 // Add the exponent into the result in integer domain.
3563 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
3564 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3565 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
3568 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3569 /// limited-precision mode.
3570 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3571 const TargetLowering &TLI) {
3572 if (Op.getValueType() == MVT::f32 &&
3573 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3575 // Put the exponent in the right bit position for later addition to the
3578 // #define LOG2OFe 1.4426950f
3579 // t0 = Op * LOG2OFe
3580 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3581 getF32Constant(DAG, 0x3fb8aa3b, dl));
3582 return getLimitedPrecisionExp2(t0, dl, DAG);
3585 // No special expansion.
3586 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
3589 /// expandLog - Lower a log intrinsic. Handles the special sequences for
3590 /// limited-precision mode.
3591 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3592 const TargetLowering &TLI) {
3593 if (Op.getValueType() == MVT::f32 &&
3594 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3595 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3597 // Scale the exponent by log(2) [0.69314718f].
3598 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3599 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3600 getF32Constant(DAG, 0x3f317218, dl));
3602 // Get the significand and build it into a floating-point number with
3604 SDValue X = GetSignificand(DAG, Op1, dl);
3606 SDValue LogOfMantissa;
3607 if (LimitFloatPrecision <= 6) {
3608 // For floating-point precision of 6:
3612 // (1.4034025f - 0.23903021f * x) * x;
3614 // error 0.0034276066, which is better than 8 bits
3615 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3616 getF32Constant(DAG, 0xbe74c456, dl));
3617 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3618 getF32Constant(DAG, 0x3fb3a2b1, dl));
3619 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3620 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3621 getF32Constant(DAG, 0x3f949a29, dl));
3622 } else if (LimitFloatPrecision <= 12) {
3623 // For floating-point precision of 12:
3629 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3631 // error 0.000061011436, which is 14 bits
3632 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3633 getF32Constant(DAG, 0xbd67b6d6, dl));
3634 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3635 getF32Constant(DAG, 0x3ee4f4b8, dl));
3636 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3637 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3638 getF32Constant(DAG, 0x3fbc278b, dl));
3639 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3640 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3641 getF32Constant(DAG, 0x40348e95, dl));
3642 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3643 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3644 getF32Constant(DAG, 0x3fdef31a, dl));
3645 } else { // LimitFloatPrecision <= 18
3646 // For floating-point precision of 18:
3654 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3656 // error 0.0000023660568, which is better than 18 bits
3657 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3658 getF32Constant(DAG, 0xbc91e5ac, dl));
3659 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3660 getF32Constant(DAG, 0x3e4350aa, dl));
3661 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3662 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3663 getF32Constant(DAG, 0x3f60d3e3, dl));
3664 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3665 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3666 getF32Constant(DAG, 0x4011cdf0, dl));
3667 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3668 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3669 getF32Constant(DAG, 0x406cfd1c, dl));
3670 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3671 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3672 getF32Constant(DAG, 0x408797cb, dl));
3673 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3674 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3675 getF32Constant(DAG, 0x4006dcab, dl));
3678 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
3681 // No special expansion.
3682 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
3685 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
3686 /// limited-precision mode.
3687 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3688 const TargetLowering &TLI) {
3689 if (Op.getValueType() == MVT::f32 &&
3690 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3691 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3693 // Get the exponent.
3694 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3696 // Get the significand and build it into a floating-point number with
3698 SDValue X = GetSignificand(DAG, Op1, dl);
3700 // Different possible minimax approximations of significand in
3701 // floating-point for various degrees of accuracy over [1,2].
3702 SDValue Log2ofMantissa;
3703 if (LimitFloatPrecision <= 6) {
3704 // For floating-point precision of 6:
3706 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3708 // error 0.0049451742, which is more than 7 bits
3709 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3710 getF32Constant(DAG, 0xbeb08fe0, dl));
3711 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3712 getF32Constant(DAG, 0x40019463, dl));
3713 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3714 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3715 getF32Constant(DAG, 0x3fd6633d, dl));
3716 } else if (LimitFloatPrecision <= 12) {
3717 // For floating-point precision of 12:
3723 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3725 // error 0.0000876136000, which is better than 13 bits
3726 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3727 getF32Constant(DAG, 0xbda7262e, dl));
3728 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3729 getF32Constant(DAG, 0x3f25280b, dl));
3730 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3731 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3732 getF32Constant(DAG, 0x4007b923, dl));
3733 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3734 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3735 getF32Constant(DAG, 0x40823e2f, dl));
3736 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3737 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3738 getF32Constant(DAG, 0x4020d29c, dl));
3739 } else { // LimitFloatPrecision <= 18
3740 // For floating-point precision of 18:
3749 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3751 // error 0.0000018516, which is better than 18 bits
3752 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3753 getF32Constant(DAG, 0xbcd2769e, dl));
3754 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3755 getF32Constant(DAG, 0x3e8ce0b9, dl));
3756 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3757 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3758 getF32Constant(DAG, 0x3fa22ae7, dl));
3759 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3760 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3761 getF32Constant(DAG, 0x40525723, dl));
3762 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3763 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3764 getF32Constant(DAG, 0x40aaf200, dl));
3765 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3766 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3767 getF32Constant(DAG, 0x40c39dad, dl));
3768 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3769 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3770 getF32Constant(DAG, 0x4042902c, dl));
3773 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
3776 // No special expansion.
3777 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
3780 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
3781 /// limited-precision mode.
3782 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3783 const TargetLowering &TLI) {
3784 if (Op.getValueType() == MVT::f32 &&
3785 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3786 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3788 // Scale the exponent by log10(2) [0.30102999f].
3789 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3790 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3791 getF32Constant(DAG, 0x3e9a209a, dl));
3793 // Get the significand and build it into a floating-point number with
3795 SDValue X = GetSignificand(DAG, Op1, dl);
3797 SDValue Log10ofMantissa;
3798 if (LimitFloatPrecision <= 6) {
3799 // For floating-point precision of 6:
3801 // Log10ofMantissa =
3803 // (0.60948995f - 0.10380950f * x) * x;
3805 // error 0.0014886165, which is 6 bits
3806 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3807 getF32Constant(DAG, 0xbdd49a13, dl));
3808 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3809 getF32Constant(DAG, 0x3f1c0789, dl));
3810 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3811 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3812 getF32Constant(DAG, 0x3f011300, dl));
3813 } else if (LimitFloatPrecision <= 12) {
3814 // For floating-point precision of 12:
3816 // Log10ofMantissa =
3819 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3821 // error 0.00019228036, which is better than 12 bits
3822 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3823 getF32Constant(DAG, 0x3d431f31, dl));
3824 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3825 getF32Constant(DAG, 0x3ea21fb2, dl));
3826 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3827 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3828 getF32Constant(DAG, 0x3f6ae232, dl));
3829 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3830 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3831 getF32Constant(DAG, 0x3f25f7c3, dl));
3832 } else { // LimitFloatPrecision <= 18
3833 // For floating-point precision of 18:
3835 // Log10ofMantissa =
3840 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3842 // error 0.0000037995730, which is better than 18 bits
3843 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3844 getF32Constant(DAG, 0x3c5d51ce, dl));
3845 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3846 getF32Constant(DAG, 0x3e00685a, dl));
3847 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3848 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3849 getF32Constant(DAG, 0x3efb6798, dl));
3850 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3851 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3852 getF32Constant(DAG, 0x3f88d192, dl));
3853 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3854 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3855 getF32Constant(DAG, 0x3fc4316c, dl));
3856 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3857 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3858 getF32Constant(DAG, 0x3f57ce70, dl));
3861 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
3864 // No special expansion.
3865 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
3868 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3869 /// limited-precision mode.
3870 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3871 const TargetLowering &TLI) {
3872 if (Op.getValueType() == MVT::f32 &&
3873 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
3874 return getLimitedPrecisionExp2(Op, dl, DAG);
3876 // No special expansion.
3877 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
3880 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3881 /// limited-precision mode with x == 10.0f.
3882 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
3883 SelectionDAG &DAG, const TargetLowering &TLI) {
3884 bool IsExp10 = false;
3885 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
3886 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3887 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
3889 IsExp10 = LHSC->isExactlyValue(Ten);
3894 // Put the exponent in the right bit position for later addition to the
3897 // #define LOG2OF10 3.3219281f
3898 // t0 = Op * LOG2OF10;
3899 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
3900 getF32Constant(DAG, 0x40549a78, dl));
3901 return getLimitedPrecisionExp2(t0, dl, DAG);
3904 // No special expansion.
3905 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
3909 /// ExpandPowI - Expand a llvm.powi intrinsic.
3910 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
3911 SelectionDAG &DAG) {
3912 // If RHS is a constant, we can expand this out to a multiplication tree,
3913 // otherwise we end up lowering to a call to __powidf2 (for example). When
3914 // optimizing for size, we only want to do this if the expansion would produce
3915 // a small number of multiplies, otherwise we do the full expansion.
3916 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3917 // Get the exponent as a positive value.
3918 unsigned Val = RHSC->getSExtValue();
3919 if ((int)Val < 0) Val = -Val;
3921 // powi(x, 0) -> 1.0
3923 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
3925 const Function *F = DAG.getMachineFunction().getFunction();
3926 if (!F->hasFnAttribute(Attribute::OptimizeForSize) ||
3927 // If optimizing for size, don't insert too many multiplies. This
3928 // inserts up to 5 multiplies.
3929 countPopulation(Val) + Log2_32(Val) < 7) {
3930 // We use the simple binary decomposition method to generate the multiply
3931 // sequence. There are more optimal ways to do this (for example,
3932 // powi(x,15) generates one more multiply than it should), but this has
3933 // the benefit of being both really simple and much better than a libcall.
3934 SDValue Res; // Logically starts equal to 1.0
3935 SDValue CurSquare = LHS;
3939 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3941 Res = CurSquare; // 1.0*CurSquare.
3944 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3945 CurSquare, CurSquare);
3949 // If the original was negative, invert the result, producing 1/(x*x*x).
3950 if (RHSC->getSExtValue() < 0)
3951 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3952 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
3957 // Otherwise, expand to a libcall.
3958 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3961 // getTruncatedArgReg - Find underlying register used for an truncated
3963 static unsigned getTruncatedArgReg(const SDValue &N) {
3964 if (N.getOpcode() != ISD::TRUNCATE)
3967 const SDValue &Ext = N.getOperand(0);
3968 if (Ext.getOpcode() == ISD::AssertZext ||
3969 Ext.getOpcode() == ISD::AssertSext) {
3970 const SDValue &CFR = Ext.getOperand(0);
3971 if (CFR.getOpcode() == ISD::CopyFromReg)
3972 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
3973 if (CFR.getOpcode() == ISD::TRUNCATE)
3974 return getTruncatedArgReg(CFR);
3979 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
3980 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
3981 /// At the end of instruction selection, they will be inserted to the entry BB.
3982 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
3983 const Value *V, MDLocalVariable *Variable, MDExpression *Expr,
3984 MDLocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
3985 const Argument *Arg = dyn_cast<Argument>(V);
3989 MachineFunction &MF = DAG.getMachineFunction();
3990 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
3992 // Ignore inlined function arguments here.
3994 // FIXME: Should we be checking DL->inlinedAt() to determine this?
3995 if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
3998 Optional<MachineOperand> Op;
3999 // Some arguments' frame index is recorded during argument lowering.
4000 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4001 Op = MachineOperand::CreateFI(FI);
4003 if (!Op && N.getNode()) {
4005 if (N.getOpcode() == ISD::CopyFromReg)
4006 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4008 Reg = getTruncatedArgReg(N);
4009 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4010 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4011 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4016 Op = MachineOperand::CreateReg(Reg, false);
4020 // Check if ValueMap has reg number.
4021 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4022 if (VMI != FuncInfo.ValueMap.end())
4023 Op = MachineOperand::CreateReg(VMI->second, false);
4026 if (!Op && N.getNode())
4027 // Check if frame index is available.
4028 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4029 if (FrameIndexSDNode *FINode =
4030 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4031 Op = MachineOperand::CreateFI(FINode->getIndex());
4036 assert(Variable->isValidLocationForIntrinsic(DL) &&
4037 "Expected inlined-at fields to agree");
4039 FuncInfo.ArgDbgValues.push_back(
4040 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4041 Op->getReg(), Offset, Variable, Expr));
4043 FuncInfo.ArgDbgValues.push_back(
4044 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4047 .addMetadata(Variable)
4048 .addMetadata(Expr));
4053 // VisualStudio defines setjmp as _setjmp
4054 #if defined(_MSC_VER) && defined(setjmp) && \
4055 !defined(setjmp_undefined_for_msvc)
4056 # pragma push_macro("setjmp")
4058 # define setjmp_undefined_for_msvc
4061 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4062 /// we want to emit this as a call to a named external function, return the name
4063 /// otherwise lower it and return null.
4065 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4066 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4067 SDLoc sdl = getCurSDLoc();
4068 DebugLoc dl = getCurDebugLoc();
4071 switch (Intrinsic) {
4073 // By default, turn this into a target intrinsic node.
4074 visitTargetIntrinsic(I, Intrinsic);
4076 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4077 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4078 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
4079 case Intrinsic::returnaddress:
4080 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
4081 getValue(I.getArgOperand(0))));
4083 case Intrinsic::frameaddress:
4084 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4085 getValue(I.getArgOperand(0))));
4087 case Intrinsic::read_register: {
4088 Value *Reg = I.getArgOperand(0);
4090 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4091 EVT VT = TLI.getValueType(I.getType());
4092 setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
4095 case Intrinsic::write_register: {
4096 Value *Reg = I.getArgOperand(0);
4097 Value *RegValue = I.getArgOperand(1);
4098 SDValue Chain = getValue(RegValue).getOperand(0);
4100 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4101 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4102 RegName, getValue(RegValue)));
4105 case Intrinsic::setjmp:
4106 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4107 case Intrinsic::longjmp:
4108 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4109 case Intrinsic::memcpy: {
4110 // FIXME: this definition of "user defined address space" is x86-specific
4111 // Assert for address < 256 since we support only user defined address
4113 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4115 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4117 "Unknown address space");
4118 SDValue Op1 = getValue(I.getArgOperand(0));
4119 SDValue Op2 = getValue(I.getArgOperand(1));
4120 SDValue Op3 = getValue(I.getArgOperand(2));
4121 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4123 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4124 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4125 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4126 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4128 MachinePointerInfo(I.getArgOperand(0)),
4129 MachinePointerInfo(I.getArgOperand(1)));
4130 updateDAGForMaybeTailCall(MC);
4133 case Intrinsic::memset: {
4134 // FIXME: this definition of "user defined address space" is x86-specific
4135 // Assert for address < 256 since we support only user defined address
4137 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4139 "Unknown address space");
4140 SDValue Op1 = getValue(I.getArgOperand(0));
4141 SDValue Op2 = getValue(I.getArgOperand(1));
4142 SDValue Op3 = getValue(I.getArgOperand(2));
4143 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4145 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4146 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4147 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4148 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4149 isTC, MachinePointerInfo(I.getArgOperand(0)));
4150 updateDAGForMaybeTailCall(MS);
4153 case Intrinsic::memmove: {
4154 // FIXME: this definition of "user defined address space" is x86-specific
4155 // Assert for address < 256 since we support only user defined address
4157 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4159 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4161 "Unknown address space");
4162 SDValue Op1 = getValue(I.getArgOperand(0));
4163 SDValue Op2 = getValue(I.getArgOperand(1));
4164 SDValue Op3 = getValue(I.getArgOperand(2));
4165 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4167 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4168 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4169 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4170 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4171 isTC, MachinePointerInfo(I.getArgOperand(0)),
4172 MachinePointerInfo(I.getArgOperand(1)));
4173 updateDAGForMaybeTailCall(MM);
4176 case Intrinsic::dbg_declare: {
4177 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4178 MDLocalVariable *Variable = DI.getVariable();
4179 MDExpression *Expression = DI.getExpression();
4180 const Value *Address = DI.getAddress();
4181 assert(Variable && "Missing variable");
4183 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4187 // Check if address has undef value.
4188 if (isa<UndefValue>(Address) ||
4189 (Address->use_empty() && !isa<Argument>(Address))) {
4190 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4194 SDValue &N = NodeMap[Address];
4195 if (!N.getNode() && isa<Argument>(Address))
4196 // Check unused arguments map.
4197 N = UnusedArgNodeMap[Address];
4200 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4201 Address = BCI->getOperand(0);
4202 // Parameters are handled specially.
4203 bool isParameter = Variable->getTag() == dwarf::DW_TAG_arg_variable ||
4204 isa<Argument>(Address);
4206 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4208 if (isParameter && !AI) {
4209 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4211 // Byval parameter. We have a frame index at this point.
4212 SDV = DAG.getFrameIndexDbgValue(
4213 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
4215 // Address is an argument, so try to emit its dbg value using
4216 // virtual register info from the FuncInfo.ValueMap.
4217 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4222 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4223 true, 0, dl, SDNodeOrder);
4225 // Can't do anything with other non-AI cases yet.
4226 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4227 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4228 DEBUG(Address->dump());
4231 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4233 // If Address is an argument then try to emit its dbg value using
4234 // virtual register info from the FuncInfo.ValueMap.
4235 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4237 // If variable is pinned by a alloca in dominating bb then
4238 // use StaticAllocaMap.
4239 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4240 if (AI->getParent() != DI.getParent()) {
4241 DenseMap<const AllocaInst*, int>::iterator SI =
4242 FuncInfo.StaticAllocaMap.find(AI);
4243 if (SI != FuncInfo.StaticAllocaMap.end()) {
4244 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4245 0, dl, SDNodeOrder);
4246 DAG.AddDbgValue(SDV, nullptr, false);
4251 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4256 case Intrinsic::dbg_value: {
4257 const DbgValueInst &DI = cast<DbgValueInst>(I);
4258 assert(DI.getVariable() && "Missing variable");
4260 MDLocalVariable *Variable = DI.getVariable();
4261 MDExpression *Expression = DI.getExpression();
4262 uint64_t Offset = DI.getOffset();
4263 const Value *V = DI.getValue();
4268 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4269 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4271 DAG.AddDbgValue(SDV, nullptr, false);
4273 // Do not use getValue() in here; we don't want to generate code at
4274 // this point if it hasn't been done yet.
4275 SDValue N = NodeMap[V];
4276 if (!N.getNode() && isa<Argument>(V))
4277 // Check unused arguments map.
4278 N = UnusedArgNodeMap[V];
4280 // A dbg.value for an alloca is always indirect.
4281 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
4282 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
4284 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4285 IsIndirect, Offset, dl, SDNodeOrder);
4286 DAG.AddDbgValue(SDV, N.getNode(), false);
4288 } else if (!V->use_empty() ) {
4289 // Do not call getValue(V) yet, as we don't want to generate code.
4290 // Remember it for later.
4291 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4292 DanglingDebugInfoMap[V] = DDI;
4294 // We may expand this to cover more cases. One case where we have no
4295 // data available is an unreferenced parameter.
4296 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4300 // Build a debug info table entry.
4301 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4302 V = BCI->getOperand(0);
4303 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4304 // Don't handle byval struct arguments or VLAs, for example.
4306 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4307 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4310 DenseMap<const AllocaInst*, int>::iterator SI =
4311 FuncInfo.StaticAllocaMap.find(AI);
4312 if (SI == FuncInfo.StaticAllocaMap.end())
4313 return nullptr; // VLAs.
4317 case Intrinsic::eh_typeid_for: {
4318 // Find the type id for the given typeinfo.
4319 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4320 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4321 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
4326 case Intrinsic::eh_return_i32:
4327 case Intrinsic::eh_return_i64:
4328 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4329 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4332 getValue(I.getArgOperand(0)),
4333 getValue(I.getArgOperand(1))));
4335 case Intrinsic::eh_unwind_init:
4336 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4338 case Intrinsic::eh_dwarf_cfa: {
4339 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4340 TLI.getPointerTy());
4341 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4342 CfaArg.getValueType(),
4343 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4344 CfaArg.getValueType()),
4346 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4347 DAG.getConstant(0, sdl, TLI.getPointerTy()));
4348 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4352 case Intrinsic::eh_sjlj_callsite: {
4353 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4354 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4355 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4356 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4358 MMI.setCurrentCallSite(CI->getZExtValue());
4361 case Intrinsic::eh_sjlj_functioncontext: {
4362 // Get and store the index of the function context.
4363 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4365 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4366 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4367 MFI->setFunctionContextIndex(FI);
4370 case Intrinsic::eh_sjlj_setjmp: {
4373 Ops[1] = getValue(I.getArgOperand(0));
4374 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4375 DAG.getVTList(MVT::i32, MVT::Other), Ops);
4376 setValue(&I, Op.getValue(0));
4377 DAG.setRoot(Op.getValue(1));
4380 case Intrinsic::eh_sjlj_longjmp: {
4381 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4382 getRoot(), getValue(I.getArgOperand(0))));
4386 case Intrinsic::masked_gather:
4387 visitMaskedGather(I);
4388 case Intrinsic::masked_load:
4391 case Intrinsic::masked_scatter:
4392 visitMaskedScatter(I);
4393 case Intrinsic::masked_store:
4394 visitMaskedStore(I);
4396 case Intrinsic::x86_mmx_pslli_w:
4397 case Intrinsic::x86_mmx_pslli_d:
4398 case Intrinsic::x86_mmx_pslli_q:
4399 case Intrinsic::x86_mmx_psrli_w:
4400 case Intrinsic::x86_mmx_psrli_d:
4401 case Intrinsic::x86_mmx_psrli_q:
4402 case Intrinsic::x86_mmx_psrai_w:
4403 case Intrinsic::x86_mmx_psrai_d: {
4404 SDValue ShAmt = getValue(I.getArgOperand(1));
4405 if (isa<ConstantSDNode>(ShAmt)) {
4406 visitTargetIntrinsic(I, Intrinsic);
4409 unsigned NewIntrinsic = 0;
4410 EVT ShAmtVT = MVT::v2i32;
4411 switch (Intrinsic) {
4412 case Intrinsic::x86_mmx_pslli_w:
4413 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4415 case Intrinsic::x86_mmx_pslli_d:
4416 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4418 case Intrinsic::x86_mmx_pslli_q:
4419 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4421 case Intrinsic::x86_mmx_psrli_w:
4422 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4424 case Intrinsic::x86_mmx_psrli_d:
4425 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4427 case Intrinsic::x86_mmx_psrli_q:
4428 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4430 case Intrinsic::x86_mmx_psrai_w:
4431 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4433 case Intrinsic::x86_mmx_psrai_d:
4434 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4436 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4439 // The vector shift intrinsics with scalars uses 32b shift amounts but
4440 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4442 // We must do this early because v2i32 is not a legal type.
4445 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
4446 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
4447 EVT DestVT = TLI.getValueType(I.getType());
4448 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4449 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4450 DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
4451 getValue(I.getArgOperand(0)), ShAmt);
4455 case Intrinsic::convertff:
4456 case Intrinsic::convertfsi:
4457 case Intrinsic::convertfui:
4458 case Intrinsic::convertsif:
4459 case Intrinsic::convertuif:
4460 case Intrinsic::convertss:
4461 case Intrinsic::convertsu:
4462 case Intrinsic::convertus:
4463 case Intrinsic::convertuu: {
4464 ISD::CvtCode Code = ISD::CVT_INVALID;
4465 switch (Intrinsic) {
4466 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4467 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4468 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4469 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4470 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4471 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4472 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4473 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4474 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4475 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4477 EVT DestVT = TLI.getValueType(I.getType());
4478 const Value *Op1 = I.getArgOperand(0);
4479 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4480 DAG.getValueType(DestVT),
4481 DAG.getValueType(getValue(Op1).getValueType()),
4482 getValue(I.getArgOperand(1)),
4483 getValue(I.getArgOperand(2)),
4488 case Intrinsic::powi:
4489 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4490 getValue(I.getArgOperand(1)), DAG));
4492 case Intrinsic::log:
4493 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4495 case Intrinsic::log2:
4496 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4498 case Intrinsic::log10:
4499 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4501 case Intrinsic::exp:
4502 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4504 case Intrinsic::exp2:
4505 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4507 case Intrinsic::pow:
4508 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4509 getValue(I.getArgOperand(1)), DAG, TLI));
4511 case Intrinsic::sqrt:
4512 case Intrinsic::fabs:
4513 case Intrinsic::sin:
4514 case Intrinsic::cos:
4515 case Intrinsic::floor:
4516 case Intrinsic::ceil:
4517 case Intrinsic::trunc:
4518 case Intrinsic::rint:
4519 case Intrinsic::nearbyint:
4520 case Intrinsic::round: {
4522 switch (Intrinsic) {
4523 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4524 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
4525 case Intrinsic::fabs: Opcode = ISD::FABS; break;
4526 case Intrinsic::sin: Opcode = ISD::FSIN; break;
4527 case Intrinsic::cos: Opcode = ISD::FCOS; break;
4528 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
4529 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
4530 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
4531 case Intrinsic::rint: Opcode = ISD::FRINT; break;
4532 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
4533 case Intrinsic::round: Opcode = ISD::FROUND; break;
4536 setValue(&I, DAG.getNode(Opcode, sdl,
4537 getValue(I.getArgOperand(0)).getValueType(),
4538 getValue(I.getArgOperand(0))));
4541 case Intrinsic::minnum:
4542 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
4543 getValue(I.getArgOperand(0)).getValueType(),
4544 getValue(I.getArgOperand(0)),
4545 getValue(I.getArgOperand(1))));
4547 case Intrinsic::maxnum:
4548 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
4549 getValue(I.getArgOperand(0)).getValueType(),
4550 getValue(I.getArgOperand(0)),
4551 getValue(I.getArgOperand(1))));
4553 case Intrinsic::copysign:
4554 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
4555 getValue(I.getArgOperand(0)).getValueType(),
4556 getValue(I.getArgOperand(0)),
4557 getValue(I.getArgOperand(1))));
4559 case Intrinsic::fma:
4560 setValue(&I, DAG.getNode(ISD::FMA, sdl,
4561 getValue(I.getArgOperand(0)).getValueType(),
4562 getValue(I.getArgOperand(0)),
4563 getValue(I.getArgOperand(1)),
4564 getValue(I.getArgOperand(2))));
4566 case Intrinsic::fmuladd: {
4567 EVT VT = TLI.getValueType(I.getType());
4568 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
4569 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
4570 setValue(&I, DAG.getNode(ISD::FMA, sdl,
4571 getValue(I.getArgOperand(0)).getValueType(),
4572 getValue(I.getArgOperand(0)),
4573 getValue(I.getArgOperand(1)),
4574 getValue(I.getArgOperand(2))));
4576 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
4577 getValue(I.getArgOperand(0)).getValueType(),
4578 getValue(I.getArgOperand(0)),
4579 getValue(I.getArgOperand(1)));
4580 SDValue Add = DAG.getNode(ISD::FADD, sdl,
4581 getValue(I.getArgOperand(0)).getValueType(),
4583 getValue(I.getArgOperand(2)));
4588 case Intrinsic::convert_to_fp16:
4589 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
4590 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
4591 getValue(I.getArgOperand(0)),
4592 DAG.getTargetConstant(0, sdl,
4595 case Intrinsic::convert_from_fp16:
4597 DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
4598 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
4599 getValue(I.getArgOperand(0)))));
4601 case Intrinsic::pcmarker: {
4602 SDValue Tmp = getValue(I.getArgOperand(0));
4603 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
4606 case Intrinsic::readcyclecounter: {
4607 SDValue Op = getRoot();
4608 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
4609 DAG.getVTList(MVT::i64, MVT::Other), Op);
4611 DAG.setRoot(Res.getValue(1));
4614 case Intrinsic::bswap:
4615 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
4616 getValue(I.getArgOperand(0)).getValueType(),
4617 getValue(I.getArgOperand(0))));
4619 case Intrinsic::cttz: {
4620 SDValue Arg = getValue(I.getArgOperand(0));
4621 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
4622 EVT Ty = Arg.getValueType();
4623 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
4627 case Intrinsic::ctlz: {
4628 SDValue Arg = getValue(I.getArgOperand(0));
4629 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
4630 EVT Ty = Arg.getValueType();
4631 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
4635 case Intrinsic::ctpop: {
4636 SDValue Arg = getValue(I.getArgOperand(0));
4637 EVT Ty = Arg.getValueType();
4638 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
4641 case Intrinsic::stacksave: {
4642 SDValue Op = getRoot();
4643 Res = DAG.getNode(ISD::STACKSAVE, sdl,
4644 DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
4646 DAG.setRoot(Res.getValue(1));
4649 case Intrinsic::stackrestore: {
4650 Res = getValue(I.getArgOperand(0));
4651 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
4654 case Intrinsic::stackprotector: {
4655 // Emit code into the DAG to store the stack guard onto the stack.
4656 MachineFunction &MF = DAG.getMachineFunction();
4657 MachineFrameInfo *MFI = MF.getFrameInfo();
4658 EVT PtrTy = TLI.getPointerTy();
4659 SDValue Src, Chain = getRoot();
4660 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
4661 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
4663 // See if Ptr is a bitcast. If it is, look through it and see if we can get
4664 // global variable __stack_chk_guard.
4666 if (const Operator *BC = dyn_cast<Operator>(Ptr))
4667 if (BC->getOpcode() == Instruction::BitCast)
4668 GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
4670 if (GV && TLI.useLoadStackGuardNode()) {
4671 // Emit a LOAD_STACK_GUARD node.
4672 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
4674 MachinePointerInfo MPInfo(GV);
4675 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
4676 unsigned Flags = MachineMemOperand::MOLoad |
4677 MachineMemOperand::MOInvariant;
4678 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
4679 PtrTy.getSizeInBits() / 8,
4680 DAG.getEVTAlignment(PtrTy));
4681 Node->setMemRefs(MemRefs, MemRefs + 1);
4683 // Copy the guard value to a virtual register so that it can be
4684 // retrieved in the epilogue.
4685 Src = SDValue(Node, 0);
4686 const TargetRegisterClass *RC =
4687 TLI.getRegClassFor(Src.getSimpleValueType());
4688 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
4690 SPDescriptor.setGuardReg(Reg);
4691 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
4693 Src = getValue(I.getArgOperand(0)); // The guard's value.
4696 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4698 int FI = FuncInfo.StaticAllocaMap[Slot];
4699 MFI->setStackProtectorIndex(FI);
4701 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4703 // Store the stack protector onto the stack.
4704 Res = DAG.getStore(Chain, sdl, Src, FIN,
4705 MachinePointerInfo::getFixedStack(FI),
4711 case Intrinsic::objectsize: {
4712 // If we don't know by now, we're never going to know.
4713 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4715 assert(CI && "Non-constant type in __builtin_object_size?");
4717 SDValue Arg = getValue(I.getCalledValue());
4718 EVT Ty = Arg.getValueType();
4721 Res = DAG.getConstant(-1ULL, sdl, Ty);
4723 Res = DAG.getConstant(0, sdl, Ty);
4728 case Intrinsic::annotation:
4729 case Intrinsic::ptr_annotation:
4730 // Drop the intrinsic, but forward the value
4731 setValue(&I, getValue(I.getOperand(0)));
4733 case Intrinsic::assume:
4734 case Intrinsic::var_annotation:
4735 // Discard annotate attributes and assumptions
4738 case Intrinsic::init_trampoline: {
4739 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4743 Ops[1] = getValue(I.getArgOperand(0));
4744 Ops[2] = getValue(I.getArgOperand(1));
4745 Ops[3] = getValue(I.getArgOperand(2));
4746 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4747 Ops[5] = DAG.getSrcValue(F);
4749 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
4754 case Intrinsic::adjust_trampoline: {
4755 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
4757 getValue(I.getArgOperand(0))));
4760 case Intrinsic::gcroot:
4762 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
4763 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4765 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4766 GFI->addStackRoot(FI->getIndex(), TypeMap);
4769 case Intrinsic::gcread:
4770 case Intrinsic::gcwrite:
4771 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4772 case Intrinsic::flt_rounds:
4773 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
4776 case Intrinsic::expect: {
4777 // Just replace __builtin_expect(exp, c) with EXP.
4778 setValue(&I, getValue(I.getArgOperand(0)));
4782 case Intrinsic::debugtrap:
4783 case Intrinsic::trap: {
4784 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
4785 if (TrapFuncName.empty()) {
4786 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
4787 ISD::TRAP : ISD::DEBUGTRAP;
4788 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
4791 TargetLowering::ArgListTy Args;
4793 TargetLowering::CallLoweringInfo CLI(DAG);
4794 CLI.setDebugLoc(sdl).setChain(getRoot())
4795 .setCallee(CallingConv::C, I.getType(),
4796 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
4797 std::move(Args), 0);
4799 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
4800 DAG.setRoot(Result.second);
4804 case Intrinsic::uadd_with_overflow:
4805 case Intrinsic::sadd_with_overflow:
4806 case Intrinsic::usub_with_overflow:
4807 case Intrinsic::ssub_with_overflow:
4808 case Intrinsic::umul_with_overflow:
4809 case Intrinsic::smul_with_overflow: {
4811 switch (Intrinsic) {
4812 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4813 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
4814 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
4815 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
4816 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
4817 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
4818 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
4820 SDValue Op1 = getValue(I.getArgOperand(0));
4821 SDValue Op2 = getValue(I.getArgOperand(1));
4823 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
4824 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
4827 case Intrinsic::prefetch: {
4829 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4831 Ops[1] = getValue(I.getArgOperand(0));
4832 Ops[2] = getValue(I.getArgOperand(1));
4833 Ops[3] = getValue(I.getArgOperand(2));
4834 Ops[4] = getValue(I.getArgOperand(3));
4835 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
4836 DAG.getVTList(MVT::Other), Ops,
4837 EVT::getIntegerVT(*Context, 8),
4838 MachinePointerInfo(I.getArgOperand(0)),
4840 false, /* volatile */
4842 rw==1)); /* write */
4845 case Intrinsic::lifetime_start:
4846 case Intrinsic::lifetime_end: {
4847 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
4848 // Stack coloring is not enabled in O0, discard region information.
4849 if (TM.getOptLevel() == CodeGenOpt::None)
4852 SmallVector<Value *, 4> Allocas;
4853 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
4855 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
4856 E = Allocas.end(); Object != E; ++Object) {
4857 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
4859 // Could not find an Alloca.
4860 if (!LifetimeObject)
4863 // First check that the Alloca is static, otherwise it won't have a
4864 // valid frame index.
4865 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
4866 if (SI == FuncInfo.StaticAllocaMap.end())
4869 int FI = SI->second;
4873 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
4874 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
4876 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
4881 case Intrinsic::invariant_start:
4882 // Discard region information.
4883 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4885 case Intrinsic::invariant_end:
4886 // Discard region information.
4888 case Intrinsic::stackprotectorcheck: {
4889 // Do not actually emit anything for this basic block. Instead we initialize
4890 // the stack protector descriptor and export the guard variable so we can
4891 // access it in FinishBasicBlock.
4892 const BasicBlock *BB = I.getParent();
4893 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
4894 ExportFromCurrentBlock(SPDescriptor.getGuard());
4896 // Flush our exports since we are going to process a terminator.
4897 (void)getControlRoot();
4900 case Intrinsic::clear_cache:
4901 return TLI.getClearCacheBuiltinName();
4902 case Intrinsic::eh_actions:
4903 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4905 case Intrinsic::donothing:
4908 case Intrinsic::experimental_stackmap: {
4912 case Intrinsic::experimental_patchpoint_void:
4913 case Intrinsic::experimental_patchpoint_i64: {
4914 visitPatchpoint(&I);
4917 case Intrinsic::experimental_gc_statepoint: {
4921 case Intrinsic::experimental_gc_result_int:
4922 case Intrinsic::experimental_gc_result_float:
4923 case Intrinsic::experimental_gc_result_ptr:
4924 case Intrinsic::experimental_gc_result: {
4928 case Intrinsic::experimental_gc_relocate: {
4932 case Intrinsic::instrprof_increment:
4933 llvm_unreachable("instrprof failed to lower an increment");
4935 case Intrinsic::frameescape: {
4936 MachineFunction &MF = DAG.getMachineFunction();
4937 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4939 // Directly emit some FRAME_ALLOC machine instrs. Label assignment emission
4940 // is the same on all targets.
4941 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
4942 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
4943 if (isa<ConstantPointerNull>(Arg))
4944 continue; // Skip null pointers. They represent a hole in index space.
4945 AllocaInst *Slot = cast<AllocaInst>(Arg);
4946 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
4947 "can only escape static allocas");
4948 int FI = FuncInfo.StaticAllocaMap[Slot];
4949 MCSymbol *FrameAllocSym =
4950 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
4951 GlobalValue::getRealLinkageName(MF.getName()), Idx);
4952 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
4953 TII->get(TargetOpcode::FRAME_ALLOC))
4954 .addSym(FrameAllocSym)
4961 case Intrinsic::framerecover: {
4962 // i8* @llvm.framerecover(i8* %fn, i8* %fp, i32 %idx)
4963 MachineFunction &MF = DAG.getMachineFunction();
4964 MVT PtrVT = TLI.getPointerTy(0);
4966 // Get the symbol that defines the frame offset.
4967 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
4968 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
4969 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
4970 MCSymbol *FrameAllocSym =
4971 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
4972 GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
4974 // Create a TargetExternalSymbol for the label to avoid any target lowering
4975 // that would make this PC relative.
4976 StringRef Name = FrameAllocSym->getName();
4977 assert(Name.data()[Name.size()] == '\0' && "not null terminated");
4978 SDValue OffsetSym = DAG.getTargetExternalSymbol(Name.data(), PtrVT);
4980 DAG.getNode(ISD::FRAME_ALLOC_RECOVER, sdl, PtrVT, OffsetSym);
4982 // Add the offset to the FP.
4983 Value *FP = I.getArgOperand(1);
4984 SDValue FPVal = getValue(FP);
4985 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
4990 case Intrinsic::eh_begincatch:
4991 case Intrinsic::eh_endcatch:
4992 llvm_unreachable("begin/end catch intrinsics not lowered in codegen");
4993 case Intrinsic::eh_exceptioncode: {
4994 unsigned Reg = TLI.getExceptionPointerRegister();
4995 assert(Reg && "cannot get exception code on this platform");
4996 MVT PtrVT = TLI.getPointerTy();
4997 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
4998 unsigned VReg = FuncInfo.MBB->addLiveIn(Reg, PtrRC);
5000 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5001 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5008 std::pair<SDValue, SDValue>
5009 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5010 MachineBasicBlock *LandingPad) {
5011 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5012 MCSymbol *BeginLabel = nullptr;
5015 // Insert a label before the invoke call to mark the try range. This can be
5016 // used to detect deletion of the invoke via the MachineModuleInfo.
5017 BeginLabel = MMI.getContext().CreateTempSymbol();
5019 // For SjLj, keep track of which landing pads go with which invokes
5020 // so as to maintain the ordering of pads in the LSDA.
5021 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5022 if (CallSiteIndex) {
5023 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5024 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5026 // Now that the call site is handled, stop tracking it.
5027 MMI.setCurrentCallSite(0);
5030 // Both PendingLoads and PendingExports must be flushed here;
5031 // this call might not return.
5033 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5035 CLI.setChain(getRoot());
5037 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5038 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5040 assert((CLI.IsTailCall || Result.second.getNode()) &&
5041 "Non-null chain expected with non-tail call!");
5042 assert((Result.second.getNode() || !Result.first.getNode()) &&
5043 "Null value expected with tail call!");
5045 if (!Result.second.getNode()) {
5046 // As a special case, a null chain means that a tail call has been emitted
5047 // and the DAG root is already updated.
5050 // Since there's no actual continuation from this block, nothing can be
5051 // relying on us setting vregs for them.
5052 PendingExports.clear();
5054 DAG.setRoot(Result.second);
5058 // Insert a label at the end of the invoke call to mark the try range. This
5059 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5060 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5061 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5063 // Inform MachineModuleInfo of range.
5064 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5070 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5072 MachineBasicBlock *LandingPad) {
5073 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5074 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5075 Type *RetTy = FTy->getReturnType();
5077 TargetLowering::ArgListTy Args;
5078 TargetLowering::ArgListEntry Entry;
5079 Args.reserve(CS.arg_size());
5081 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5083 const Value *V = *i;
5086 if (V->getType()->isEmptyTy())
5089 SDValue ArgNode = getValue(V);
5090 Entry.Node = ArgNode; Entry.Ty = V->getType();
5092 // Skip the first return-type Attribute to get to params.
5093 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5094 Args.push_back(Entry);
5096 // If we have an explicit sret argument that is an Instruction, (i.e., it
5097 // might point to function-local memory), we can't meaningfully tail-call.
5098 if (Entry.isSRet && isa<Instruction>(V))
5102 // Check if target-independent constraints permit a tail call here.
5103 // Target-dependent constraints are checked within TLI->LowerCallTo.
5104 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5107 TargetLowering::CallLoweringInfo CLI(DAG);
5108 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5109 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5110 .setTailCall(isTailCall);
5111 std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
5113 if (Result.first.getNode())
5114 setValue(CS.getInstruction(), Result.first);
5117 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5118 /// value is equal or not-equal to zero.
5119 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5120 for (const User *U : V->users()) {
5121 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5122 if (IC->isEquality())
5123 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5124 if (C->isNullValue())
5126 // Unknown instruction.
5132 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5134 SelectionDAGBuilder &Builder) {
5136 // Check to see if this load can be trivially constant folded, e.g. if the
5137 // input is from a string literal.
5138 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5139 // Cast pointer to the type we really want to load.
5140 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5141 PointerType::getUnqual(LoadTy));
5143 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5144 const_cast<Constant *>(LoadInput), *Builder.DL))
5145 return Builder.getValue(LoadCst);
5148 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5149 // still constant memory, the input chain can be the entry node.
5151 bool ConstantMemory = false;
5153 // Do not serialize (non-volatile) loads of constant memory with anything.
5154 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5155 Root = Builder.DAG.getEntryNode();
5156 ConstantMemory = true;
5158 // Do not serialize non-volatile loads against each other.
5159 Root = Builder.DAG.getRoot();
5162 SDValue Ptr = Builder.getValue(PtrVal);
5163 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5164 Ptr, MachinePointerInfo(PtrVal),
5166 false /*nontemporal*/,
5167 false /*isinvariant*/, 1 /* align=1 */);
5169 if (!ConstantMemory)
5170 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5174 /// processIntegerCallValue - Record the value for an instruction that
5175 /// produces an integer result, converting the type where necessary.
5176 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5179 EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5181 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5183 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5184 setValue(&I, Value);
5187 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5188 /// If so, return true and lower it, otherwise return false and it will be
5189 /// lowered like a normal call.
5190 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5191 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5192 if (I.getNumArgOperands() != 3)
5195 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5196 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5197 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5198 !I.getType()->isIntegerTy())
5201 const Value *Size = I.getArgOperand(2);
5202 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5203 if (CSize && CSize->getZExtValue() == 0) {
5204 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5205 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
5209 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5210 std::pair<SDValue, SDValue> Res =
5211 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5212 getValue(LHS), getValue(RHS), getValue(Size),
5213 MachinePointerInfo(LHS),
5214 MachinePointerInfo(RHS));
5215 if (Res.first.getNode()) {
5216 processIntegerCallValue(I, Res.first, true);
5217 PendingLoads.push_back(Res.second);
5221 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5222 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5223 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5224 bool ActuallyDoIt = true;
5227 switch (CSize->getZExtValue()) {
5229 LoadVT = MVT::Other;
5231 ActuallyDoIt = false;
5235 LoadTy = Type::getInt16Ty(CSize->getContext());
5239 LoadTy = Type::getInt32Ty(CSize->getContext());
5243 LoadTy = Type::getInt64Ty(CSize->getContext());
5247 LoadVT = MVT::v4i32;
5248 LoadTy = Type::getInt32Ty(CSize->getContext());
5249 LoadTy = VectorType::get(LoadTy, 4);
5254 // This turns into unaligned loads. We only do this if the target natively
5255 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5256 // we'll only produce a small number of byte loads.
5258 // Require that we can find a legal MVT, and only do this if the target
5259 // supports unaligned loads of that type. Expanding into byte loads would
5261 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5262 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5263 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5264 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5265 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5266 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5267 // TODO: Check alignment of src and dest ptrs.
5268 if (!TLI.isTypeLegal(LoadVT) ||
5269 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5270 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5271 ActuallyDoIt = false;
5275 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5276 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5278 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5280 processIntegerCallValue(I, Res, false);
5289 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5290 /// form. If so, return true and lower it, otherwise return false and it
5291 /// will be lowered like a normal call.
5292 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5293 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5294 if (I.getNumArgOperands() != 3)
5297 const Value *Src = I.getArgOperand(0);
5298 const Value *Char = I.getArgOperand(1);
5299 const Value *Length = I.getArgOperand(2);
5300 if (!Src->getType()->isPointerTy() ||
5301 !Char->getType()->isIntegerTy() ||
5302 !Length->getType()->isIntegerTy() ||
5303 !I.getType()->isPointerTy())
5306 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5307 std::pair<SDValue, SDValue> Res =
5308 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5309 getValue(Src), getValue(Char), getValue(Length),
5310 MachinePointerInfo(Src));
5311 if (Res.first.getNode()) {
5312 setValue(&I, Res.first);
5313 PendingLoads.push_back(Res.second);
5320 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5321 /// optimized form. If so, return true and lower it, otherwise return false
5322 /// and it will be lowered like a normal call.
5323 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5324 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5325 if (I.getNumArgOperands() != 2)
5328 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5329 if (!Arg0->getType()->isPointerTy() ||
5330 !Arg1->getType()->isPointerTy() ||
5331 !I.getType()->isPointerTy())
5334 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5335 std::pair<SDValue, SDValue> Res =
5336 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5337 getValue(Arg0), getValue(Arg1),
5338 MachinePointerInfo(Arg0),
5339 MachinePointerInfo(Arg1), isStpcpy);
5340 if (Res.first.getNode()) {
5341 setValue(&I, Res.first);
5342 DAG.setRoot(Res.second);
5349 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5350 /// If so, return true and lower it, otherwise return false and it will be
5351 /// lowered like a normal call.
5352 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5353 // Verify that the prototype makes sense. int strcmp(void*,void*)
5354 if (I.getNumArgOperands() != 2)
5357 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5358 if (!Arg0->getType()->isPointerTy() ||
5359 !Arg1->getType()->isPointerTy() ||
5360 !I.getType()->isIntegerTy())
5363 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5364 std::pair<SDValue, SDValue> Res =
5365 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5366 getValue(Arg0), getValue(Arg1),
5367 MachinePointerInfo(Arg0),
5368 MachinePointerInfo(Arg1));
5369 if (Res.first.getNode()) {
5370 processIntegerCallValue(I, Res.first, true);
5371 PendingLoads.push_back(Res.second);
5378 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5379 /// form. If so, return true and lower it, otherwise return false and it
5380 /// will be lowered like a normal call.
5381 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5382 // Verify that the prototype makes sense. size_t strlen(char *)
5383 if (I.getNumArgOperands() != 1)
5386 const Value *Arg0 = I.getArgOperand(0);
5387 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5390 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5391 std::pair<SDValue, SDValue> Res =
5392 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5393 getValue(Arg0), MachinePointerInfo(Arg0));
5394 if (Res.first.getNode()) {
5395 processIntegerCallValue(I, Res.first, false);
5396 PendingLoads.push_back(Res.second);
5403 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5404 /// form. If so, return true and lower it, otherwise return false and it
5405 /// will be lowered like a normal call.
5406 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5407 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5408 if (I.getNumArgOperands() != 2)
5411 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5412 if (!Arg0->getType()->isPointerTy() ||
5413 !Arg1->getType()->isIntegerTy() ||
5414 !I.getType()->isIntegerTy())
5417 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5418 std::pair<SDValue, SDValue> Res =
5419 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5420 getValue(Arg0), getValue(Arg1),
5421 MachinePointerInfo(Arg0));
5422 if (Res.first.getNode()) {
5423 processIntegerCallValue(I, Res.first, false);
5424 PendingLoads.push_back(Res.second);
5431 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5432 /// operation (as expected), translate it to an SDNode with the specified opcode
5433 /// and return true.
5434 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5436 // Sanity check that it really is a unary floating-point call.
5437 if (I.getNumArgOperands() != 1 ||
5438 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5439 I.getType() != I.getArgOperand(0)->getType() ||
5440 !I.onlyReadsMemory())
5443 SDValue Tmp = getValue(I.getArgOperand(0));
5444 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5448 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
5449 /// operation (as expected), translate it to an SDNode with the specified opcode
5450 /// and return true.
5451 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5453 // Sanity check that it really is a binary floating-point call.
5454 if (I.getNumArgOperands() != 2 ||
5455 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5456 I.getType() != I.getArgOperand(0)->getType() ||
5457 I.getType() != I.getArgOperand(1)->getType() ||
5458 !I.onlyReadsMemory())
5461 SDValue Tmp0 = getValue(I.getArgOperand(0));
5462 SDValue Tmp1 = getValue(I.getArgOperand(1));
5463 EVT VT = Tmp0.getValueType();
5464 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5468 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5469 // Handle inline assembly differently.
5470 if (isa<InlineAsm>(I.getCalledValue())) {
5475 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5476 ComputeUsesVAFloatArgument(I, &MMI);
5478 const char *RenameFn = nullptr;
5479 if (Function *F = I.getCalledFunction()) {
5480 if (F->isDeclaration()) {
5481 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5482 if (unsigned IID = II->getIntrinsicID(F)) {
5483 RenameFn = visitIntrinsicCall(I, IID);
5488 if (unsigned IID = F->getIntrinsicID()) {
5489 RenameFn = visitIntrinsicCall(I, IID);
5495 // Check for well-known libc/libm calls. If the function is internal, it
5496 // can't be a library call.
5498 if (!F->hasLocalLinkage() && F->hasName() &&
5499 LibInfo->getLibFunc(F->getName(), Func) &&
5500 LibInfo->hasOptimizedCodeGen(Func)) {
5503 case LibFunc::copysign:
5504 case LibFunc::copysignf:
5505 case LibFunc::copysignl:
5506 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5507 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5508 I.getType() == I.getArgOperand(0)->getType() &&
5509 I.getType() == I.getArgOperand(1)->getType() &&
5510 I.onlyReadsMemory()) {
5511 SDValue LHS = getValue(I.getArgOperand(0));
5512 SDValue RHS = getValue(I.getArgOperand(1));
5513 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5514 LHS.getValueType(), LHS, RHS));
5519 case LibFunc::fabsf:
5520 case LibFunc::fabsl:
5521 if (visitUnaryFloatCall(I, ISD::FABS))
5525 case LibFunc::fminf:
5526 case LibFunc::fminl:
5527 if (visitBinaryFloatCall(I, ISD::FMINNUM))
5531 case LibFunc::fmaxf:
5532 case LibFunc::fmaxl:
5533 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
5539 if (visitUnaryFloatCall(I, ISD::FSIN))
5545 if (visitUnaryFloatCall(I, ISD::FCOS))
5549 case LibFunc::sqrtf:
5550 case LibFunc::sqrtl:
5551 case LibFunc::sqrt_finite:
5552 case LibFunc::sqrtf_finite:
5553 case LibFunc::sqrtl_finite:
5554 if (visitUnaryFloatCall(I, ISD::FSQRT))
5557 case LibFunc::floor:
5558 case LibFunc::floorf:
5559 case LibFunc::floorl:
5560 if (visitUnaryFloatCall(I, ISD::FFLOOR))
5563 case LibFunc::nearbyint:
5564 case LibFunc::nearbyintf:
5565 case LibFunc::nearbyintl:
5566 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
5570 case LibFunc::ceilf:
5571 case LibFunc::ceill:
5572 if (visitUnaryFloatCall(I, ISD::FCEIL))
5576 case LibFunc::rintf:
5577 case LibFunc::rintl:
5578 if (visitUnaryFloatCall(I, ISD::FRINT))
5581 case LibFunc::round:
5582 case LibFunc::roundf:
5583 case LibFunc::roundl:
5584 if (visitUnaryFloatCall(I, ISD::FROUND))
5587 case LibFunc::trunc:
5588 case LibFunc::truncf:
5589 case LibFunc::truncl:
5590 if (visitUnaryFloatCall(I, ISD::FTRUNC))
5594 case LibFunc::log2f:
5595 case LibFunc::log2l:
5596 if (visitUnaryFloatCall(I, ISD::FLOG2))
5600 case LibFunc::exp2f:
5601 case LibFunc::exp2l:
5602 if (visitUnaryFloatCall(I, ISD::FEXP2))
5605 case LibFunc::memcmp:
5606 if (visitMemCmpCall(I))
5609 case LibFunc::memchr:
5610 if (visitMemChrCall(I))
5613 case LibFunc::strcpy:
5614 if (visitStrCpyCall(I, false))
5617 case LibFunc::stpcpy:
5618 if (visitStrCpyCall(I, true))
5621 case LibFunc::strcmp:
5622 if (visitStrCmpCall(I))
5625 case LibFunc::strlen:
5626 if (visitStrLenCall(I))
5629 case LibFunc::strnlen:
5630 if (visitStrNLenCall(I))
5639 Callee = getValue(I.getCalledValue());
5641 Callee = DAG.getExternalSymbol(RenameFn,
5642 DAG.getTargetLoweringInfo().getPointerTy());
5644 // Check if we can potentially perform a tail call. More detailed checking is
5645 // be done within LowerCallTo, after more information about the call is known.
5646 LowerCallTo(&I, Callee, I.isTailCall());
5651 /// AsmOperandInfo - This contains information for each constraint that we are
5653 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
5655 /// CallOperand - If this is the result output operand or a clobber
5656 /// this is null, otherwise it is the incoming operand to the CallInst.
5657 /// This gets modified as the asm is processed.
5658 SDValue CallOperand;
5660 /// AssignedRegs - If this is a register or register class operand, this
5661 /// contains the set of register corresponding to the operand.
5662 RegsForValue AssignedRegs;
5664 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5665 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
5668 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5669 /// corresponds to. If there is no Value* for this operand, it returns
5671 EVT getCallOperandValEVT(LLVMContext &Context,
5672 const TargetLowering &TLI,
5673 const DataLayout *DL) const {
5674 if (!CallOperandVal) return MVT::Other;
5676 if (isa<BasicBlock>(CallOperandVal))
5677 return TLI.getPointerTy();
5679 llvm::Type *OpTy = CallOperandVal->getType();
5681 // FIXME: code duplicated from TargetLowering::ParseConstraints().
5682 // If this is an indirect operand, the operand is a pointer to the
5685 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5687 report_fatal_error("Indirect operand for inline asm not a pointer!");
5688 OpTy = PtrTy->getElementType();
5691 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5692 if (StructType *STy = dyn_cast<StructType>(OpTy))
5693 if (STy->getNumElements() == 1)
5694 OpTy = STy->getElementType(0);
5696 // If OpTy is not a single value, it may be a struct/union that we
5697 // can tile with integers.
5698 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5699 unsigned BitSize = DL->getTypeSizeInBits(OpTy);
5708 OpTy = IntegerType::get(Context, BitSize);
5713 return TLI.getValueType(OpTy, true);
5717 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5719 } // end anonymous namespace
5721 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5722 /// specified operand. We prefer to assign virtual registers, to allow the
5723 /// register allocator to handle the assignment process. However, if the asm
5724 /// uses features that we can't model on machineinstrs, we have SDISel do the
5725 /// allocation. This produces generally horrible, but correct, code.
5727 /// OpInfo describes the operand.
5729 static void GetRegistersForValue(SelectionDAG &DAG,
5730 const TargetLowering &TLI,
5732 SDISelAsmOperandInfo &OpInfo) {
5733 LLVMContext &Context = *DAG.getContext();
5735 MachineFunction &MF = DAG.getMachineFunction();
5736 SmallVector<unsigned, 4> Regs;
5738 // If this is a constraint for a single physreg, or a constraint for a
5739 // register class, find it.
5740 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
5741 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
5742 OpInfo.ConstraintCode,
5743 OpInfo.ConstraintVT);
5745 unsigned NumRegs = 1;
5746 if (OpInfo.ConstraintVT != MVT::Other) {
5747 // If this is a FP input in an integer register (or visa versa) insert a bit
5748 // cast of the input value. More generally, handle any case where the input
5749 // value disagrees with the register class we plan to stick this in.
5750 if (OpInfo.Type == InlineAsm::isInput &&
5751 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5752 // Try to convert to the first EVT that the reg class contains. If the
5753 // types are identical size, use a bitcast to convert (e.g. two differing
5755 MVT RegVT = *PhysReg.second->vt_begin();
5756 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
5757 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5758 RegVT, OpInfo.CallOperand);
5759 OpInfo.ConstraintVT = RegVT;
5760 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5761 // If the input is a FP value and we want it in FP registers, do a
5762 // bitcast to the corresponding integer type. This turns an f64 value
5763 // into i64, which can be passed with two i32 values on a 32-bit
5765 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
5766 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5767 RegVT, OpInfo.CallOperand);
5768 OpInfo.ConstraintVT = RegVT;
5772 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5776 EVT ValueVT = OpInfo.ConstraintVT;
5778 // If this is a constraint for a specific physical register, like {r17},
5780 if (unsigned AssignedReg = PhysReg.first) {
5781 const TargetRegisterClass *RC = PhysReg.second;
5782 if (OpInfo.ConstraintVT == MVT::Other)
5783 ValueVT = *RC->vt_begin();
5785 // Get the actual register value type. This is important, because the user
5786 // may have asked for (e.g.) the AX register in i32 type. We need to
5787 // remember that AX is actually i16 to get the right extension.
5788 RegVT = *RC->vt_begin();
5790 // This is a explicit reference to a physical register.
5791 Regs.push_back(AssignedReg);
5793 // If this is an expanded reference, add the rest of the regs to Regs.
5795 TargetRegisterClass::iterator I = RC->begin();
5796 for (; *I != AssignedReg; ++I)
5797 assert(I != RC->end() && "Didn't find reg!");
5799 // Already added the first reg.
5801 for (; NumRegs; --NumRegs, ++I) {
5802 assert(I != RC->end() && "Ran out of registers to allocate!");
5807 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5811 // Otherwise, if this was a reference to an LLVM register class, create vregs
5812 // for this reference.
5813 if (const TargetRegisterClass *RC = PhysReg.second) {
5814 RegVT = *RC->vt_begin();
5815 if (OpInfo.ConstraintVT == MVT::Other)
5818 // Create the appropriate number of virtual registers.
5819 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5820 for (; NumRegs; --NumRegs)
5821 Regs.push_back(RegInfo.createVirtualRegister(RC));
5823 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5827 // Otherwise, we couldn't allocate enough registers for this.
5830 /// visitInlineAsm - Handle a call to an InlineAsm object.
5832 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5833 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5835 /// ConstraintOperands - Information about all of the constraints.
5836 SDISelAsmOperandInfoVector ConstraintOperands;
5838 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5839 TargetLowering::AsmOperandInfoVector TargetConstraints =
5840 TLI.ParseConstraints(DAG.getSubtarget().getRegisterInfo(), CS);
5842 bool hasMemory = false;
5844 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5845 unsigned ResNo = 0; // ResNo - The result number of the next output.
5846 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5847 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
5848 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5850 MVT OpVT = MVT::Other;
5852 // Compute the value type for each operand.
5853 switch (OpInfo.Type) {
5854 case InlineAsm::isOutput:
5855 // Indirect outputs just consume an argument.
5856 if (OpInfo.isIndirect) {
5857 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5861 // The return value of the call is this value. As such, there is no
5862 // corresponding argument.
5863 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5864 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
5865 OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
5867 assert(ResNo == 0 && "Asm only has one result!");
5868 OpVT = TLI.getSimpleValueType(CS.getType());
5872 case InlineAsm::isInput:
5873 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5875 case InlineAsm::isClobber:
5880 // If this is an input or an indirect output, process the call argument.
5881 // BasicBlocks are labels, currently appearing only in asm's.
5882 if (OpInfo.CallOperandVal) {
5883 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5884 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5886 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5890 OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, DL).getSimpleVT();
5893 OpInfo.ConstraintVT = OpVT;
5895 // Indirect operand accesses access memory.
5896 if (OpInfo.isIndirect)
5899 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
5900 TargetLowering::ConstraintType
5901 CType = TLI.getConstraintType(OpInfo.Codes[j]);
5902 if (CType == TargetLowering::C_Memory) {
5910 SDValue Chain, Flag;
5912 // We won't need to flush pending loads if this asm doesn't touch
5913 // memory and is nonvolatile.
5914 if (hasMemory || IA->hasSideEffects())
5917 Chain = DAG.getRoot();
5919 // Second pass over the constraints: compute which constraint option to use
5920 // and assign registers to constraints that want a specific physreg.
5921 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5922 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5924 // If this is an output operand with a matching input operand, look up the
5925 // matching input. If their types mismatch, e.g. one is an integer, the
5926 // other is floating point, or their sizes are different, flag it as an
5928 if (OpInfo.hasMatchingInput()) {
5929 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5931 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5932 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
5933 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5934 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5935 OpInfo.ConstraintVT);
5936 std::pair<unsigned, const TargetRegisterClass *> InputRC =
5937 TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5938 Input.ConstraintVT);
5939 if ((OpInfo.ConstraintVT.isInteger() !=
5940 Input.ConstraintVT.isInteger()) ||
5941 (MatchRC.second != InputRC.second)) {
5942 report_fatal_error("Unsupported asm: input constraint"
5943 " with a matching output constraint of"
5944 " incompatible type!");
5946 Input.ConstraintVT = OpInfo.ConstraintVT;
5950 // Compute the constraint code and ConstraintType to use.
5951 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5953 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5954 OpInfo.Type == InlineAsm::isClobber)
5957 // If this is a memory input, and if the operand is not indirect, do what we
5958 // need to to provide an address for the memory input.
5959 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5960 !OpInfo.isIndirect) {
5961 assert((OpInfo.isMultipleAlternative ||
5962 (OpInfo.Type == InlineAsm::isInput)) &&
5963 "Can only indirectify direct input operands!");
5965 // Memory operands really want the address of the value. If we don't have
5966 // an indirect input, put it in the constpool if we can, otherwise spill
5967 // it to a stack slot.
5968 // TODO: This isn't quite right. We need to handle these according to
5969 // the addressing mode that the constraint wants. Also, this may take
5970 // an additional register for the computation and we don't want that
5973 // If the operand is a float, integer, or vector constant, spill to a
5974 // constant pool entry to get its address.
5975 const Value *OpVal = OpInfo.CallOperandVal;
5976 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5977 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
5978 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5979 TLI.getPointerTy());
5981 // Otherwise, create a stack slot and emit a store to it before the
5983 Type *Ty = OpVal->getType();
5984 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
5985 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
5986 MachineFunction &MF = DAG.getMachineFunction();
5987 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5988 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5989 Chain = DAG.getStore(Chain, getCurSDLoc(),
5990 OpInfo.CallOperand, StackSlot,
5991 MachinePointerInfo::getFixedStack(SSFI),
5993 OpInfo.CallOperand = StackSlot;
5996 // There is no longer a Value* corresponding to this operand.
5997 OpInfo.CallOperandVal = nullptr;
5999 // It is now an indirect operand.
6000 OpInfo.isIndirect = true;
6003 // If this constraint is for a specific register, allocate it before
6005 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6006 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6009 // Second pass - Loop over all of the operands, assigning virtual or physregs
6010 // to register class operands.
6011 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6012 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6014 // C_Register operands have already been allocated, Other/Memory don't need
6016 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6017 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6020 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6021 std::vector<SDValue> AsmNodeOperands;
6022 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6023 AsmNodeOperands.push_back(
6024 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6025 TLI.getPointerTy()));
6027 // If we have a !srcloc metadata node associated with it, we want to attach
6028 // this to the ultimately generated inline asm machineinstr. To do this, we
6029 // pass in the third operand as this (potentially null) inline asm MDNode.
6030 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6031 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6033 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6034 // bits as operand 3.
6035 unsigned ExtraInfo = 0;
6036 if (IA->hasSideEffects())
6037 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6038 if (IA->isAlignStack())
6039 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6040 // Set the asm dialect.
6041 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6043 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6044 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6045 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6047 // Compute the constraint code and ConstraintType to use.
6048 TLI.ComputeConstraintToUse(OpInfo, SDValue());
6050 // Ideally, we would only check against memory constraints. However, the
6051 // meaning of an other constraint can be target-specific and we can't easily
6052 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6053 // for other constriants as well.
6054 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6055 OpInfo.ConstraintType == TargetLowering::C_Other) {
6056 if (OpInfo.Type == InlineAsm::isInput)
6057 ExtraInfo |= InlineAsm::Extra_MayLoad;
6058 else if (OpInfo.Type == InlineAsm::isOutput)
6059 ExtraInfo |= InlineAsm::Extra_MayStore;
6060 else if (OpInfo.Type == InlineAsm::isClobber)
6061 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6065 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo, getCurSDLoc(),
6066 TLI.getPointerTy()));
6068 // Loop over all of the inputs, copying the operand values into the
6069 // appropriate registers and processing the output regs.
6070 RegsForValue RetValRegs;
6072 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6073 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6075 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6076 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6078 switch (OpInfo.Type) {
6079 case InlineAsm::isOutput: {
6080 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6081 OpInfo.ConstraintType != TargetLowering::C_Register) {
6082 // Memory output, or 'other' output (e.g. 'X' constraint).
6083 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6085 unsigned ConstraintID =
6086 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6087 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6088 "Failed to convert memory constraint code to constraint id.");
6090 // Add information to the INLINEASM node to know about this output.
6091 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6092 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
6093 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
6095 AsmNodeOperands.push_back(OpInfo.CallOperand);
6099 // Otherwise, this is a register or register class output.
6101 // Copy the output from the appropriate register. Find a register that
6103 if (OpInfo.AssignedRegs.Regs.empty()) {
6104 LLVMContext &Ctx = *DAG.getContext();
6105 Ctx.emitError(CS.getInstruction(),
6106 "couldn't allocate output register for constraint '" +
6107 Twine(OpInfo.ConstraintCode) + "'");
6111 // If this is an indirect operand, store through the pointer after the
6113 if (OpInfo.isIndirect) {
6114 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6115 OpInfo.CallOperandVal));
6117 // This is the result value of the call.
6118 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6119 // Concatenate this output onto the outputs list.
6120 RetValRegs.append(OpInfo.AssignedRegs);
6123 // Add information to the INLINEASM node to know that this register is
6126 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6127 ? InlineAsm::Kind_RegDefEarlyClobber
6128 : InlineAsm::Kind_RegDef,
6129 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
6132 case InlineAsm::isInput: {
6133 SDValue InOperandVal = OpInfo.CallOperand;
6135 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6136 // If this is required to match an output register we have already set,
6137 // just use its register.
6138 unsigned OperandNo = OpInfo.getMatchedOperand();
6140 // Scan until we find the definition we already emitted of this operand.
6141 // When we find it, create a RegsForValue operand.
6142 unsigned CurOp = InlineAsm::Op_FirstOperand;
6143 for (; OperandNo; --OperandNo) {
6144 // Advance to the next operand.
6146 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6147 assert((InlineAsm::isRegDefKind(OpFlag) ||
6148 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6149 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6150 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6154 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6155 if (InlineAsm::isRegDefKind(OpFlag) ||
6156 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6157 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6158 if (OpInfo.isIndirect) {
6159 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6160 LLVMContext &Ctx = *DAG.getContext();
6161 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6162 " don't know how to handle tied "
6163 "indirect register inputs");
6167 RegsForValue MatchedRegs;
6168 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6169 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6170 MatchedRegs.RegVTs.push_back(RegVT);
6171 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6172 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6174 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6175 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6177 LLVMContext &Ctx = *DAG.getContext();
6178 Ctx.emitError(CS.getInstruction(),
6179 "inline asm error: This value"
6180 " type register class is not natively supported!");
6184 SDLoc dl = getCurSDLoc();
6185 // Use the produced MatchedRegs object to
6186 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6187 Chain, &Flag, CS.getInstruction());
6188 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6189 true, OpInfo.getMatchedOperand(), dl,
6190 DAG, AsmNodeOperands);
6194 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6195 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6196 "Unexpected number of operands");
6197 // Add information to the INLINEASM node to know about this input.
6198 // See InlineAsm.h isUseOperandTiedToDef.
6199 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
6200 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6201 OpInfo.getMatchedOperand());
6202 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag, getCurSDLoc(),
6203 TLI.getPointerTy()));
6204 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6208 // Treat indirect 'X' constraint as memory.
6209 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6211 OpInfo.ConstraintType = TargetLowering::C_Memory;
6213 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6214 std::vector<SDValue> Ops;
6215 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6218 LLVMContext &Ctx = *DAG.getContext();
6219 Ctx.emitError(CS.getInstruction(),
6220 "invalid operand for inline asm constraint '" +
6221 Twine(OpInfo.ConstraintCode) + "'");
6225 // Add information to the INLINEASM node to know about this input.
6226 unsigned ResOpType =
6227 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6228 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6230 TLI.getPointerTy()));
6231 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6235 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6236 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6237 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6238 "Memory operands expect pointer values");
6240 unsigned ConstraintID =
6241 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6242 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6243 "Failed to convert memory constraint code to constraint id.");
6245 // Add information to the INLINEASM node to know about this input.
6246 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6247 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
6248 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6251 AsmNodeOperands.push_back(InOperandVal);
6255 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6256 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6257 "Unknown constraint type!");
6259 // TODO: Support this.
6260 if (OpInfo.isIndirect) {
6261 LLVMContext &Ctx = *DAG.getContext();
6262 Ctx.emitError(CS.getInstruction(),
6263 "Don't know how to handle indirect register inputs yet "
6264 "for constraint '" +
6265 Twine(OpInfo.ConstraintCode) + "'");
6269 // Copy the input into the appropriate registers.
6270 if (OpInfo.AssignedRegs.Regs.empty()) {
6271 LLVMContext &Ctx = *DAG.getContext();
6272 Ctx.emitError(CS.getInstruction(),
6273 "couldn't allocate input reg for constraint '" +
6274 Twine(OpInfo.ConstraintCode) + "'");
6278 SDLoc dl = getCurSDLoc();
6280 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6281 Chain, &Flag, CS.getInstruction());
6283 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6284 dl, DAG, AsmNodeOperands);
6287 case InlineAsm::isClobber: {
6288 // Add the clobbered value to the operand list, so that the register
6289 // allocator is aware that the physreg got clobbered.
6290 if (!OpInfo.AssignedRegs.Regs.empty())
6291 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6292 false, 0, getCurSDLoc(), DAG,
6299 // Finish up input operands. Set the input chain and add the flag last.
6300 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6301 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6303 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6304 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6305 Flag = Chain.getValue(1);
6307 // If this asm returns a register value, copy the result from that register
6308 // and set it as the value of the call.
6309 if (!RetValRegs.Regs.empty()) {
6310 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6311 Chain, &Flag, CS.getInstruction());
6313 // FIXME: Why don't we do this for inline asms with MRVs?
6314 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6315 EVT ResultType = TLI.getValueType(CS.getType());
6317 // If any of the results of the inline asm is a vector, it may have the
6318 // wrong width/num elts. This can happen for register classes that can
6319 // contain multiple different value types. The preg or vreg allocated may
6320 // not have the same VT as was expected. Convert it to the right type
6321 // with bit_convert.
6322 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6323 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6326 } else if (ResultType != Val.getValueType() &&
6327 ResultType.isInteger() && Val.getValueType().isInteger()) {
6328 // If a result value was tied to an input value, the computed result may
6329 // have a wider width than the expected result. Extract the relevant
6331 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6334 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6337 setValue(CS.getInstruction(), Val);
6338 // Don't need to use this as a chain in this case.
6339 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6343 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6345 // Process indirect outputs, first output all of the flagged copies out of
6347 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6348 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6349 const Value *Ptr = IndirectStoresToEmit[i].second;
6350 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6352 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6355 // Emit the non-flagged stores from the physregs.
6356 SmallVector<SDValue, 8> OutChains;
6357 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6358 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6359 StoresToEmit[i].first,
6360 getValue(StoresToEmit[i].second),
6361 MachinePointerInfo(StoresToEmit[i].second),
6363 OutChains.push_back(Val);
6366 if (!OutChains.empty())
6367 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6372 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6373 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6374 MVT::Other, getRoot(),
6375 getValue(I.getArgOperand(0)),
6376 DAG.getSrcValue(I.getArgOperand(0))));
6379 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6380 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6381 const DataLayout &DL = *TLI.getDataLayout();
6382 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurSDLoc(),
6383 getRoot(), getValue(I.getOperand(0)),
6384 DAG.getSrcValue(I.getOperand(0)),
6385 DL.getABITypeAlignment(I.getType()));
6387 DAG.setRoot(V.getValue(1));
6390 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6391 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6392 MVT::Other, getRoot(),
6393 getValue(I.getArgOperand(0)),
6394 DAG.getSrcValue(I.getArgOperand(0))));
6397 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6398 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6399 MVT::Other, getRoot(),
6400 getValue(I.getArgOperand(0)),
6401 getValue(I.getArgOperand(1)),
6402 DAG.getSrcValue(I.getArgOperand(0)),
6403 DAG.getSrcValue(I.getArgOperand(1))));
6406 /// \brief Lower an argument list according to the target calling convention.
6408 /// \return A tuple of <return-value, token-chain>
6410 /// This is a helper for lowering intrinsics that follow a target calling
6411 /// convention or require stack pointer adjustment. Only a subset of the
6412 /// intrinsic's operands need to participate in the calling convention.
6413 std::pair<SDValue, SDValue>
6414 SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
6415 unsigned NumArgs, SDValue Callee,
6417 MachineBasicBlock *LandingPad,
6418 bool IsPatchPoint) {
6419 TargetLowering::ArgListTy Args;
6420 Args.reserve(NumArgs);
6422 // Populate the argument list.
6423 // Attributes for args start at offset 1, after the return attribute.
6424 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6425 ArgI != ArgE; ++ArgI) {
6426 const Value *V = CS->getOperand(ArgI);
6428 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6430 TargetLowering::ArgListEntry Entry;
6431 Entry.Node = getValue(V);
6432 Entry.Ty = V->getType();
6433 Entry.setAttributes(&CS, AttrI);
6434 Args.push_back(Entry);
6437 Type *retTy = UseVoidTy ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
6438 TargetLowering::CallLoweringInfo CLI(DAG);
6439 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
6440 .setCallee(CS.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
6441 .setDiscardResult(CS->use_empty()).setIsPatchPoint(IsPatchPoint);
6443 return lowerInvokable(CLI, LandingPad);
6446 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6447 /// or patchpoint target node's operand list.
6449 /// Constants are converted to TargetConstants purely as an optimization to
6450 /// avoid constant materialization and register allocation.
6452 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6453 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6454 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6455 /// address materialization and register allocation, but may also be required
6456 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6457 /// alloca in the entry block, then the runtime may assume that the alloca's
6458 /// StackMap location can be read immediately after compilation and that the
6459 /// location is valid at any point during execution (this is similar to the
6460 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6461 /// only available in a register, then the runtime would need to trap when
6462 /// execution reaches the StackMap in order to read the alloca's location.
6463 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
6464 SDLoc DL, SmallVectorImpl<SDValue> &Ops,
6465 SelectionDAGBuilder &Builder) {
6466 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6467 SDValue OpVal = Builder.getValue(CS.getArgument(i));
6468 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6470 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
6472 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
6473 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6474 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6476 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
6478 Ops.push_back(OpVal);
6482 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6483 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6484 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6485 // [live variables...])
6487 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6489 SDValue Chain, InFlag, Callee, NullPtr;
6490 SmallVector<SDValue, 32> Ops;
6492 SDLoc DL = getCurSDLoc();
6493 Callee = getValue(CI.getCalledValue());
6494 NullPtr = DAG.getIntPtrConstant(0, DL, true);
6496 // The stackmap intrinsic only records the live variables (the arguemnts
6497 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6498 // intrinsic, this won't be lowered to a function call. This means we don't
6499 // have to worry about calling conventions and target specific lowering code.
6500 // Instead we perform the call lowering right here.
6502 // chain, flag = CALLSEQ_START(chain, 0)
6503 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6504 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6506 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
6507 InFlag = Chain.getValue(1);
6509 // Add the <id> and <numBytes> constants.
6510 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6511 Ops.push_back(DAG.getTargetConstant(
6512 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
6513 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6514 Ops.push_back(DAG.getTargetConstant(
6515 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
6518 // Push live variables for the stack map.
6519 addStackMapLiveVars(&CI, 2, DL, Ops, *this);
6521 // We are not pushing any register mask info here on the operands list,
6522 // because the stackmap doesn't clobber anything.
6524 // Push the chain and the glue flag.
6525 Ops.push_back(Chain);
6526 Ops.push_back(InFlag);
6528 // Create the STACKMAP node.
6529 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6530 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
6531 Chain = SDValue(SM, 0);
6532 InFlag = Chain.getValue(1);
6534 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
6536 // Stackmaps don't generate values, so nothing goes into the NodeMap.
6538 // Set the root to the target-lowered call chain.
6541 // Inform the Frame Information that we have a stackmap in this function.
6542 FuncInfo.MF->getFrameInfo()->setHasStackMap();
6545 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6546 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
6547 MachineBasicBlock *LandingPad) {
6548 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
6553 // [live variables...])
6555 CallingConv::ID CC = CS.getCallingConv();
6556 bool IsAnyRegCC = CC == CallingConv::AnyReg;
6557 bool HasDef = !CS->getType()->isVoidTy();
6558 SDLoc dl = getCurSDLoc();
6559 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
6561 // Handle immediate and symbolic callees.
6562 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
6563 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
6565 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
6566 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
6567 SDLoc(SymbolicCallee),
6568 SymbolicCallee->getValueType(0));
6570 // Get the real number of arguments participating in the call <numArgs>
6571 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
6572 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
6574 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
6575 // Intrinsics include all meta-operands up to but not including CC.
6576 unsigned NumMetaOpers = PatchPointOpers::CCPos;
6577 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
6578 "Not enough arguments provided to the patchpoint intrinsic");
6580 // For AnyRegCC the arguments are lowered later on manually.
6581 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
6582 std::pair<SDValue, SDValue> Result =
6583 lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC,
6586 SDNode *CallEnd = Result.second.getNode();
6587 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6588 CallEnd = CallEnd->getOperand(0).getNode();
6590 /// Get a call instruction from the call sequence chain.
6591 /// Tail calls are not allowed.
6592 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6593 "Expected a callseq node.");
6594 SDNode *Call = CallEnd->getOperand(0).getNode();
6595 bool HasGlue = Call->getGluedNode();
6597 // Replace the target specific call node with the patchable intrinsic.
6598 SmallVector<SDValue, 8> Ops;
6600 // Add the <id> and <numBytes> constants.
6601 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
6602 Ops.push_back(DAG.getTargetConstant(
6603 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
6604 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
6605 Ops.push_back(DAG.getTargetConstant(
6606 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
6610 Ops.push_back(Callee);
6612 // Adjust <numArgs> to account for any arguments that have been passed on the
6614 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
6615 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
6616 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
6617 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
6619 // Add the calling convention
6620 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
6622 // Add the arguments we omitted previously. The register allocator should
6623 // place these in any free register.
6625 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
6626 Ops.push_back(getValue(CS.getArgument(i)));
6628 // Push the arguments from the call instruction up to the register mask.
6629 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
6630 Ops.append(Call->op_begin() + 2, e);
6632 // Push live variables for the stack map.
6633 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
6635 // Push the register mask info.
6637 Ops.push_back(*(Call->op_end()-2));
6639 Ops.push_back(*(Call->op_end()-1));
6641 // Push the chain (this is originally the first operand of the call, but
6642 // becomes now the last or second to last operand).
6643 Ops.push_back(*(Call->op_begin()));
6645 // Push the glue flag (last operand).
6647 Ops.push_back(*(Call->op_end()-1));
6650 if (IsAnyRegCC && HasDef) {
6651 // Create the return types based on the intrinsic definition
6652 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6653 SmallVector<EVT, 3> ValueVTs;
6654 ComputeValueVTs(TLI, CS->getType(), ValueVTs);
6655 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
6657 // There is always a chain and a glue type at the end
6658 ValueVTs.push_back(MVT::Other);
6659 ValueVTs.push_back(MVT::Glue);
6660 NodeTys = DAG.getVTList(ValueVTs);
6662 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6664 // Replace the target specific call node with a PATCHPOINT node.
6665 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
6668 // Update the NodeMap.
6671 setValue(CS.getInstruction(), SDValue(MN, 0));
6673 setValue(CS.getInstruction(), Result.first);
6676 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
6677 // call sequence. Furthermore the location of the chain and glue can change
6678 // when the AnyReg calling convention is used and the intrinsic returns a
6680 if (IsAnyRegCC && HasDef) {
6681 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
6682 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
6683 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
6685 DAG.ReplaceAllUsesWith(Call, MN);
6686 DAG.DeleteNode(Call);
6688 // Inform the Frame Information that we have a patchpoint in this function.
6689 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
6692 /// Returns an AttributeSet representing the attributes applied to the return
6693 /// value of the given call.
6694 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
6695 SmallVector<Attribute::AttrKind, 2> Attrs;
6697 Attrs.push_back(Attribute::SExt);
6699 Attrs.push_back(Attribute::ZExt);
6701 Attrs.push_back(Attribute::InReg);
6703 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
6707 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6708 /// implementation, which just calls LowerCall.
6709 /// FIXME: When all targets are
6710 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6711 std::pair<SDValue, SDValue>
6712 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
6713 // Handle the incoming return values from the call.
6715 Type *OrigRetTy = CLI.RetTy;
6716 SmallVector<EVT, 4> RetTys;
6717 SmallVector<uint64_t, 4> Offsets;
6718 ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
6720 SmallVector<ISD::OutputArg, 4> Outs;
6721 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
6723 bool CanLowerReturn =
6724 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
6725 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
6727 SDValue DemoteStackSlot;
6728 int DemoteStackIdx = -100;
6729 if (!CanLowerReturn) {
6730 // FIXME: equivalent assert?
6731 // assert(!CS.hasInAllocaArgument() &&
6732 // "sret demotion is incompatible with inalloca");
6733 uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
6734 unsigned Align = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
6735 MachineFunction &MF = CLI.DAG.getMachineFunction();
6736 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6737 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
6739 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
6741 Entry.Node = DemoteStackSlot;
6742 Entry.Ty = StackSlotPtrType;
6743 Entry.isSExt = false;
6744 Entry.isZExt = false;
6745 Entry.isInReg = false;
6746 Entry.isSRet = true;
6747 Entry.isNest = false;
6748 Entry.isByVal = false;
6749 Entry.isReturned = false;
6750 Entry.Alignment = Align;
6751 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
6752 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
6754 // sret demotion isn't compatible with tail-calls, since the sret argument
6755 // points into the callers stack frame.
6756 CLI.IsTailCall = false;
6758 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6760 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6761 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
6762 for (unsigned i = 0; i != NumRegs; ++i) {
6763 ISD::InputArg MyFlags;
6764 MyFlags.VT = RegisterVT;
6766 MyFlags.Used = CLI.IsReturnValueUsed;
6768 MyFlags.Flags.setSExt();
6770 MyFlags.Flags.setZExt();
6772 MyFlags.Flags.setInReg();
6773 CLI.Ins.push_back(MyFlags);
6778 // Handle all of the outgoing arguments.
6780 CLI.OutVals.clear();
6781 ArgListTy &Args = CLI.getArgs();
6782 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6783 SmallVector<EVT, 4> ValueVTs;
6784 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6785 Type *FinalType = Args[i].Ty;
6786 if (Args[i].isByVal)
6787 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
6788 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
6789 FinalType, CLI.CallConv, CLI.IsVarArg);
6790 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
6792 EVT VT = ValueVTs[Value];
6793 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
6794 SDValue Op = SDValue(Args[i].Node.getNode(),
6795 Args[i].Node.getResNo() + Value);
6796 ISD::ArgFlagsTy Flags;
6797 unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
6803 if (Args[i].isInReg)
6807 if (Args[i].isByVal)
6809 if (Args[i].isInAlloca) {
6810 Flags.setInAlloca();
6811 // Set the byval flag for CCAssignFn callbacks that don't know about
6812 // inalloca. This way we can know how many bytes we should've allocated
6813 // and how many bytes a callee cleanup function will pop. If we port
6814 // inalloca to more targets, we'll have to add custom inalloca handling
6815 // in the various CC lowering callbacks.
6818 if (Args[i].isByVal || Args[i].isInAlloca) {
6819 PointerType *Ty = cast<PointerType>(Args[i].Ty);
6820 Type *ElementTy = Ty->getElementType();
6821 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
6822 // For ByVal, alignment should come from FE. BE will guess if this
6823 // info is not there but there are cases it cannot get right.
6824 unsigned FrameAlign;
6825 if (Args[i].Alignment)
6826 FrameAlign = Args[i].Alignment;
6828 FrameAlign = getByValTypeAlignment(ElementTy);
6829 Flags.setByValAlign(FrameAlign);
6834 Flags.setInConsecutiveRegs();
6835 Flags.setOrigAlign(OriginalAlignment);
6837 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
6838 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
6839 SmallVector<SDValue, 4> Parts(NumParts);
6840 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6843 ExtendKind = ISD::SIGN_EXTEND;
6844 else if (Args[i].isZExt)
6845 ExtendKind = ISD::ZERO_EXTEND;
6847 // Conservatively only handle 'returned' on non-vectors for now
6848 if (Args[i].isReturned && !Op.getValueType().isVector()) {
6849 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
6850 "unexpected use of 'returned'");
6851 // Before passing 'returned' to the target lowering code, ensure that
6852 // either the register MVT and the actual EVT are the same size or that
6853 // the return value and argument are extended in the same way; in these
6854 // cases it's safe to pass the argument register value unchanged as the
6855 // return register value (although it's at the target's option whether
6857 // TODO: allow code generation to take advantage of partially preserved
6858 // registers rather than clobbering the entire register when the
6859 // parameter extension method is not compatible with the return
6861 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
6862 (ExtendKind != ISD::ANY_EXTEND &&
6863 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
6864 Flags.setReturned();
6867 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
6868 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
6870 for (unsigned j = 0; j != NumParts; ++j) {
6871 // if it isn't first piece, alignment must be 1
6872 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
6873 i < CLI.NumFixedArgs,
6874 i, j*Parts[j].getValueType().getStoreSize());
6875 if (NumParts > 1 && j == 0)
6876 MyFlags.Flags.setSplit();
6878 MyFlags.Flags.setOrigAlign(1);
6880 CLI.Outs.push_back(MyFlags);
6881 CLI.OutVals.push_back(Parts[j]);
6884 if (NeedsRegBlock && Value == NumValues - 1)
6885 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
6889 SmallVector<SDValue, 4> InVals;
6890 CLI.Chain = LowerCall(CLI, InVals);
6892 // Verify that the target's LowerCall behaved as expected.
6893 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
6894 "LowerCall didn't return a valid chain!");
6895 assert((!CLI.IsTailCall || InVals.empty()) &&
6896 "LowerCall emitted a return value for a tail call!");
6897 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
6898 "LowerCall didn't emit the correct number of values!");
6900 // For a tail call, the return value is merely live-out and there aren't
6901 // any nodes in the DAG representing it. Return a special value to
6902 // indicate that a tail call has been emitted and no more Instructions
6903 // should be processed in the current block.
6904 if (CLI.IsTailCall) {
6905 CLI.DAG.setRoot(CLI.Chain);
6906 return std::make_pair(SDValue(), SDValue());
6909 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
6910 assert(InVals[i].getNode() &&
6911 "LowerCall emitted a null value!");
6912 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
6913 "LowerCall emitted a value with the wrong type!");
6916 SmallVector<SDValue, 4> ReturnValues;
6917 if (!CanLowerReturn) {
6918 // The instruction result is the result of loading from the
6919 // hidden sret parameter.
6920 SmallVector<EVT, 1> PVTs;
6921 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
6923 ComputeValueVTs(*this, PtrRetTy, PVTs);
6924 assert(PVTs.size() == 1 && "Pointers should fit in one register");
6925 EVT PtrVT = PVTs[0];
6927 unsigned NumValues = RetTys.size();
6928 ReturnValues.resize(NumValues);
6929 SmallVector<SDValue, 4> Chains(NumValues);
6931 for (unsigned i = 0; i < NumValues; ++i) {
6932 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
6933 CLI.DAG.getConstant(Offsets[i], CLI.DL,
6935 SDValue L = CLI.DAG.getLoad(
6936 RetTys[i], CLI.DL, CLI.Chain, Add,
6937 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
6939 ReturnValues[i] = L;
6940 Chains[i] = L.getValue(1);
6943 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
6945 // Collect the legal value parts into potentially illegal values
6946 // that correspond to the original function's return values.
6947 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6949 AssertOp = ISD::AssertSext;
6950 else if (CLI.RetZExt)
6951 AssertOp = ISD::AssertZext;
6952 unsigned CurReg = 0;
6953 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6955 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6956 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
6958 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
6959 NumRegs, RegisterVT, VT, nullptr,
6964 // For a function returning void, there is no return value. We can't create
6965 // such a node, so we just return a null return value in that case. In
6966 // that case, nothing will actually look at the value.
6967 if (ReturnValues.empty())
6968 return std::make_pair(SDValue(), CLI.Chain);
6971 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
6972 CLI.DAG.getVTList(RetTys), ReturnValues);
6973 return std::make_pair(Res, CLI.Chain);
6976 void TargetLowering::LowerOperationWrapper(SDNode *N,
6977 SmallVectorImpl<SDValue> &Results,
6978 SelectionDAG &DAG) const {
6979 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6981 Results.push_back(Res);
6984 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6985 llvm_unreachable("LowerOperation not implemented for this target!");
6989 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
6990 SDValue Op = getNonRegisterValue(V);
6991 assert((Op.getOpcode() != ISD::CopyFromReg ||
6992 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6993 "Copy from a reg to the same reg!");
6994 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6996 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6997 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6998 SDValue Chain = DAG.getEntryNode();
7000 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7001 FuncInfo.PreferredExtendType.end())
7003 : FuncInfo.PreferredExtendType[V];
7004 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7005 PendingExports.push_back(Chain);
7008 #include "llvm/CodeGen/SelectionDAGISel.h"
7010 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7011 /// entry block, return true. This includes arguments used by switches, since
7012 /// the switch may expand into multiple basic blocks.
7013 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7014 // With FastISel active, we may be splitting blocks, so force creation
7015 // of virtual registers for all non-dead arguments.
7017 return A->use_empty();
7019 const BasicBlock *Entry = A->getParent()->begin();
7020 for (const User *U : A->users())
7021 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7022 return false; // Use not in entry block.
7027 void SelectionDAGISel::LowerArguments(const Function &F) {
7028 SelectionDAG &DAG = SDB->DAG;
7029 SDLoc dl = SDB->getCurSDLoc();
7030 const DataLayout *DL = TLI->getDataLayout();
7031 SmallVector<ISD::InputArg, 16> Ins;
7033 if (!FuncInfo->CanLowerReturn) {
7034 // Put in an sret pointer parameter before all the other parameters.
7035 SmallVector<EVT, 1> ValueVTs;
7036 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7038 // NOTE: Assuming that a pointer will never break down to more than one VT
7040 ISD::ArgFlagsTy Flags;
7042 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7043 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
7044 ISD::InputArg::NoArgIndex, 0);
7045 Ins.push_back(RetArg);
7048 // Set up the incoming argument description vector.
7050 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7051 I != E; ++I, ++Idx) {
7052 SmallVector<EVT, 4> ValueVTs;
7053 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7054 bool isArgValueUsed = !I->use_empty();
7055 unsigned PartBase = 0;
7056 Type *FinalType = I->getType();
7057 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7058 FinalType = cast<PointerType>(FinalType)->getElementType();
7059 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7060 FinalType, F.getCallingConv(), F.isVarArg());
7061 for (unsigned Value = 0, NumValues = ValueVTs.size();
7062 Value != NumValues; ++Value) {
7063 EVT VT = ValueVTs[Value];
7064 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7065 ISD::ArgFlagsTy Flags;
7066 unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
7068 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7070 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7072 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7074 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7076 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7078 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7079 Flags.setInAlloca();
7080 // Set the byval flag for CCAssignFn callbacks that don't know about
7081 // inalloca. This way we can know how many bytes we should've allocated
7082 // and how many bytes a callee cleanup function will pop. If we port
7083 // inalloca to more targets, we'll have to add custom inalloca handling
7084 // in the various CC lowering callbacks.
7087 if (Flags.isByVal() || Flags.isInAlloca()) {
7088 PointerType *Ty = cast<PointerType>(I->getType());
7089 Type *ElementTy = Ty->getElementType();
7090 Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
7091 // For ByVal, alignment should be passed from FE. BE will guess if
7092 // this info is not there but there are cases it cannot get right.
7093 unsigned FrameAlign;
7094 if (F.getParamAlignment(Idx))
7095 FrameAlign = F.getParamAlignment(Idx);
7097 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7098 Flags.setByValAlign(FrameAlign);
7100 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7103 Flags.setInConsecutiveRegs();
7104 Flags.setOrigAlign(OriginalAlignment);
7106 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7107 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7108 for (unsigned i = 0; i != NumRegs; ++i) {
7109 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7110 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7111 if (NumRegs > 1 && i == 0)
7112 MyFlags.Flags.setSplit();
7113 // if it isn't first piece, alignment must be 1
7115 MyFlags.Flags.setOrigAlign(1);
7116 Ins.push_back(MyFlags);
7118 if (NeedsRegBlock && Value == NumValues - 1)
7119 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
7120 PartBase += VT.getStoreSize();
7124 // Call the target to set up the argument values.
7125 SmallVector<SDValue, 8> InVals;
7126 SDValue NewRoot = TLI->LowerFormalArguments(
7127 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7129 // Verify that the target's LowerFormalArguments behaved as expected.
7130 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7131 "LowerFormalArguments didn't return a valid chain!");
7132 assert(InVals.size() == Ins.size() &&
7133 "LowerFormalArguments didn't emit the correct number of values!");
7135 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7136 assert(InVals[i].getNode() &&
7137 "LowerFormalArguments emitted a null value!");
7138 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7139 "LowerFormalArguments emitted a value with the wrong type!");
7143 // Update the DAG with the new chain value resulting from argument lowering.
7144 DAG.setRoot(NewRoot);
7146 // Set up the argument values.
7149 if (!FuncInfo->CanLowerReturn) {
7150 // Create a virtual register for the sret pointer, and put in a copy
7151 // from the sret argument into it.
7152 SmallVector<EVT, 1> ValueVTs;
7153 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7154 MVT VT = ValueVTs[0].getSimpleVT();
7155 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7156 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7157 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7158 RegVT, VT, nullptr, AssertOp);
7160 MachineFunction& MF = SDB->DAG.getMachineFunction();
7161 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7162 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7163 FuncInfo->DemoteRegister = SRetReg;
7165 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7166 DAG.setRoot(NewRoot);
7168 // i indexes lowered arguments. Bump it past the hidden sret argument.
7169 // Idx indexes LLVM arguments. Don't touch it.
7173 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7175 SmallVector<SDValue, 4> ArgValues;
7176 SmallVector<EVT, 4> ValueVTs;
7177 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7178 unsigned NumValues = ValueVTs.size();
7180 // If this argument is unused then remember its value. It is used to generate
7181 // debugging information.
7182 if (I->use_empty() && NumValues) {
7183 SDB->setUnusedArgValue(I, InVals[i]);
7185 // Also remember any frame index for use in FastISel.
7186 if (FrameIndexSDNode *FI =
7187 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7188 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7191 for (unsigned Val = 0; Val != NumValues; ++Val) {
7192 EVT VT = ValueVTs[Val];
7193 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7194 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7196 if (!I->use_empty()) {
7197 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7198 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7199 AssertOp = ISD::AssertSext;
7200 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7201 AssertOp = ISD::AssertZext;
7203 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7204 NumParts, PartVT, VT,
7205 nullptr, AssertOp));
7211 // We don't need to do anything else for unused arguments.
7212 if (ArgValues.empty())
7215 // Note down frame index.
7216 if (FrameIndexSDNode *FI =
7217 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7218 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7220 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7221 SDB->getCurSDLoc());
7223 SDB->setValue(I, Res);
7224 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7225 if (LoadSDNode *LNode =
7226 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7227 if (FrameIndexSDNode *FI =
7228 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7229 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7232 // If this argument is live outside of the entry block, insert a copy from
7233 // wherever we got it to the vreg that other BB's will reference it as.
7234 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7235 // If we can, though, try to skip creating an unnecessary vreg.
7236 // FIXME: This isn't very clean... it would be nice to make this more
7237 // general. It's also subtly incompatible with the hacks FastISel
7239 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7240 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7241 FuncInfo->ValueMap[I] = Reg;
7245 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7246 FuncInfo->InitializeRegForValue(I);
7247 SDB->CopyToExportRegsIfNeeded(I);
7251 assert(i == InVals.size() && "Argument register count mismatch!");
7253 // Finally, if the target has anything special to do, allow it to do so.
7254 EmitFunctionEntryCode();
7257 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7258 /// ensure constants are generated when needed. Remember the virtual registers
7259 /// that need to be added to the Machine PHI nodes as input. We cannot just
7260 /// directly add them, because expansion might result in multiple MBB's for one
7261 /// BB. As such, the start of the BB might correspond to a different MBB than
7265 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7266 const TerminatorInst *TI = LLVMBB->getTerminator();
7268 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7270 // Check PHI nodes in successors that expect a value to be available from this
7272 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7273 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7274 if (!isa<PHINode>(SuccBB->begin())) continue;
7275 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7277 // If this terminator has multiple identical successors (common for
7278 // switches), only handle each succ once.
7279 if (!SuccsHandled.insert(SuccMBB).second)
7282 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7284 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7285 // nodes and Machine PHI nodes, but the incoming operands have not been
7287 for (BasicBlock::const_iterator I = SuccBB->begin();
7288 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7289 // Ignore dead phi's.
7290 if (PN->use_empty()) continue;
7293 if (PN->getType()->isEmptyTy())
7297 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7299 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7300 unsigned &RegOut = ConstantsOut[C];
7302 RegOut = FuncInfo.CreateRegs(C->getType());
7303 CopyValueToVirtualRegister(C, RegOut);
7307 DenseMap<const Value *, unsigned>::iterator I =
7308 FuncInfo.ValueMap.find(PHIOp);
7309 if (I != FuncInfo.ValueMap.end())
7312 assert(isa<AllocaInst>(PHIOp) &&
7313 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7314 "Didn't codegen value into a register!??");
7315 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7316 CopyValueToVirtualRegister(PHIOp, Reg);
7320 // Remember that this register needs to added to the machine PHI node as
7321 // the input for this MBB.
7322 SmallVector<EVT, 4> ValueVTs;
7323 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7324 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
7325 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7326 EVT VT = ValueVTs[vti];
7327 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7328 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7329 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7330 Reg += NumRegisters;
7335 ConstantsOut.clear();
7338 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7341 SelectionDAGBuilder::StackProtectorDescriptor::
7342 AddSuccessorMBB(const BasicBlock *BB,
7343 MachineBasicBlock *ParentMBB,
7345 MachineBasicBlock *SuccMBB) {
7346 // If SuccBB has not been created yet, create it.
7348 MachineFunction *MF = ParentMBB->getParent();
7349 MachineFunction::iterator BBI = ParentMBB;
7350 SuccMBB = MF->CreateMachineBasicBlock(BB);
7351 MF->insert(++BBI, SuccMBB);
7353 // Add it as a successor of ParentMBB.
7354 ParentMBB->addSuccessor(
7355 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));
7359 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
7360 MachineFunction::iterator I = MBB;
7361 if (++I == FuncInfo.MF->end())
7366 /// During lowering new call nodes can be created (such as memset, etc.).
7367 /// Those will become new roots of the current DAG, but complications arise
7368 /// when they are tail calls. In such cases, the call lowering will update
7369 /// the root, but the builder still needs to know that a tail call has been
7370 /// lowered in order to avoid generating an additional return.
7371 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
7372 // If the node is null, we do have a tail call.
7373 if (MaybeTC.getNode() != nullptr)
7374 DAG.setRoot(MaybeTC);
7379 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
7380 unsigned *TotalCases, unsigned First,
7382 assert(Last >= First);
7383 assert(TotalCases[Last] >= TotalCases[First]);
7385 APInt LowCase = Clusters[First].Low->getValue();
7386 APInt HighCase = Clusters[Last].High->getValue();
7387 assert(LowCase.getBitWidth() == HighCase.getBitWidth());
7389 // FIXME: A range of consecutive cases has 100% density, but only requires one
7390 // comparison to lower. We should discriminate against such consecutive ranges
7393 uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
7394 uint64_t Range = Diff + 1;
7397 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
7399 assert(NumCases < UINT64_MAX / 100);
7400 assert(Range >= NumCases);
7402 return NumCases * 100 >= Range * MinJumpTableDensity;
7405 static inline bool areJTsAllowed(const TargetLowering &TLI) {
7406 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
7407 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
7410 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters,
7411 unsigned First, unsigned Last,
7412 const SwitchInst *SI,
7413 MachineBasicBlock *DefaultMBB,
7414 CaseCluster &JTCluster) {
7415 assert(First <= Last);
7417 uint32_t Weight = 0;
7418 unsigned NumCmps = 0;
7419 std::vector<MachineBasicBlock*> Table;
7420 DenseMap<MachineBasicBlock*, uint32_t> JTWeights;
7421 for (unsigned I = First; I <= Last; ++I) {
7422 assert(Clusters[I].Kind == CC_Range);
7423 Weight += Clusters[I].Weight;
7424 assert(Weight >= Clusters[I].Weight && "Weight overflow!");
7425 APInt Low = Clusters[I].Low->getValue();
7426 APInt High = Clusters[I].High->getValue();
7427 NumCmps += (Low == High) ? 1 : 2;
7429 // Fill the gap between this and the previous cluster.
7430 APInt PreviousHigh = Clusters[I - 1].High->getValue();
7431 assert(PreviousHigh.slt(Low));
7432 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
7433 for (uint64_t J = 0; J < Gap; J++)
7434 Table.push_back(DefaultMBB);
7436 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
7437 for (uint64_t J = 0; J < ClusterSize; ++J)
7438 Table.push_back(Clusters[I].MBB);
7439 JTWeights[Clusters[I].MBB] += Clusters[I].Weight;
7442 unsigned NumDests = JTWeights.size();
7443 if (isSuitableForBitTests(NumDests, NumCmps,
7444 Clusters[First].Low->getValue(),
7445 Clusters[Last].High->getValue())) {
7446 // Clusters[First..Last] should be lowered as bit tests instead.
7450 // Create the MBB that will load from and jump through the table.
7451 // Note: We create it here, but it's not inserted into the function yet.
7452 MachineFunction *CurMF = FuncInfo.MF;
7453 MachineBasicBlock *JumpTableMBB =
7454 CurMF->CreateMachineBasicBlock(SI->getParent());
7456 // Add successors. Note: use table order for determinism.
7457 SmallPtrSet<MachineBasicBlock *, 8> Done;
7458 for (MachineBasicBlock *Succ : Table) {
7459 if (Done.count(Succ))
7461 addSuccessorWithWeight(JumpTableMBB, Succ, JTWeights[Succ]);
7465 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7466 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
7467 ->createJumpTableIndex(Table);
7469 // Set up the jump table info.
7470 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
7471 JumpTableHeader JTH(Clusters[First].Low->getValue(),
7472 Clusters[Last].High->getValue(), SI->getCondition(),
7474 JTCases.push_back(JumpTableBlock(JTH, JT));
7476 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
7477 JTCases.size() - 1, Weight);
7481 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
7482 const SwitchInst *SI,
7483 MachineBasicBlock *DefaultMBB) {
7485 // Clusters must be non-empty, sorted, and only contain Range clusters.
7486 assert(!Clusters.empty());
7487 for (CaseCluster &C : Clusters)
7488 assert(C.Kind == CC_Range);
7489 for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
7490 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
7493 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7494 if (!areJTsAllowed(TLI))
7497 const int64_t N = Clusters.size();
7498 const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries();
7500 // Split Clusters into minimum number of dense partitions. The algorithm uses
7501 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
7502 // for the Case Statement'" (1994), but builds the MinPartitions array in
7503 // reverse order to make it easier to reconstruct the partitions in ascending
7504 // order. In the choice between two optimal partitionings, it picks the one
7505 // which yields more jump tables.
7507 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
7508 SmallVector<unsigned, 8> MinPartitions(N);
7509 // LastElement[i] is the last element of the partition starting at i.
7510 SmallVector<unsigned, 8> LastElement(N);
7511 // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1].
7512 SmallVector<unsigned, 8> NumTables(N);
7513 // TotalCases[i]: Total nbr of cases in Clusters[0..i].
7514 SmallVector<unsigned, 8> TotalCases(N);
7516 for (unsigned i = 0; i < N; ++i) {
7517 APInt Hi = Clusters[i].High->getValue();
7518 APInt Lo = Clusters[i].Low->getValue();
7519 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
7521 TotalCases[i] += TotalCases[i - 1];
7524 // Base case: There is only one way to partition Clusters[N-1].
7525 MinPartitions[N - 1] = 1;
7526 LastElement[N - 1] = N - 1;
7527 assert(MinJumpTableSize > 1);
7528 NumTables[N - 1] = 0;
7530 // Note: loop indexes are signed to avoid underflow.
7531 for (int64_t i = N - 2; i >= 0; i--) {
7532 // Find optimal partitioning of Clusters[i..N-1].
7533 // Baseline: Put Clusters[i] into a partition on its own.
7534 MinPartitions[i] = MinPartitions[i + 1] + 1;
7536 NumTables[i] = NumTables[i + 1];
7538 // Search for a solution that results in fewer partitions.
7539 for (int64_t j = N - 1; j > i; j--) {
7540 // Try building a partition from Clusters[i..j].
7541 if (isDense(Clusters, &TotalCases[0], i, j)) {
7542 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
7543 bool IsTable = j - i + 1 >= MinJumpTableSize;
7544 unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]);
7546 // If this j leads to fewer partitions, or same number of partitions
7547 // with more lookup tables, it is a better partitioning.
7548 if (NumPartitions < MinPartitions[i] ||
7549 (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) {
7550 MinPartitions[i] = NumPartitions;
7552 NumTables[i] = Tables;
7558 // Iterate over the partitions, replacing some with jump tables in-place.
7559 unsigned DstIndex = 0;
7560 for (unsigned First = 0, Last; First < N; First = Last + 1) {
7561 Last = LastElement[First];
7562 assert(Last >= First);
7563 assert(DstIndex <= First);
7564 unsigned NumClusters = Last - First + 1;
7566 CaseCluster JTCluster;
7567 if (NumClusters >= MinJumpTableSize &&
7568 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
7569 Clusters[DstIndex++] = JTCluster;
7571 for (unsigned I = First; I <= Last; ++I)
7572 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
7575 Clusters.resize(DstIndex);
7578 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
7579 // FIXME: Using the pointer type doesn't seem ideal.
7580 uint64_t BW = DAG.getTargetLoweringInfo().getPointerTy().getSizeInBits();
7581 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
7585 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
7588 const APInt &High) {
7589 // FIXME: I don't think NumCmps is the correct metric: a single case and a
7590 // range of cases both require only one branch to lower. Just looking at the
7591 // number of clusters and destinations should be enough to decide whether to
7594 // To lower a range with bit tests, the range must fit the bitwidth of a
7596 if (!rangeFitsInWord(Low, High))
7599 // Decide whether it's profitable to lower this range with bit tests. Each
7600 // destination requires a bit test and branch, and there is an overall range
7601 // check branch. For a small number of clusters, separate comparisons might be
7602 // cheaper, and for many destinations, splitting the range might be better.
7603 return (NumDests == 1 && NumCmps >= 3) ||
7604 (NumDests == 2 && NumCmps >= 5) ||
7605 (NumDests == 3 && NumCmps >= 6);
7608 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
7609 unsigned First, unsigned Last,
7610 const SwitchInst *SI,
7611 CaseCluster &BTCluster) {
7612 assert(First <= Last);
7616 BitVector Dests(FuncInfo.MF->getNumBlockIDs());
7617 unsigned NumCmps = 0;
7618 for (int64_t I = First; I <= Last; ++I) {
7619 assert(Clusters[I].Kind == CC_Range);
7620 Dests.set(Clusters[I].MBB->getNumber());
7621 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
7623 unsigned NumDests = Dests.count();
7625 APInt Low = Clusters[First].Low->getValue();
7626 APInt High = Clusters[Last].High->getValue();
7627 assert(Low.slt(High));
7629 if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
7635 const int BitWidth =
7636 DAG.getTargetLoweringInfo().getPointerTy().getSizeInBits();
7637 assert((High - Low + 1).sle(BitWidth) && "Case range must fit in bit mask!");
7639 if (Low.isNonNegative() && High.slt(BitWidth)) {
7640 // Optimize the case where all the case values fit in a
7641 // word without having to subtract minValue. In this case,
7642 // we can optimize away the subtraction.
7643 LowBound = APInt::getNullValue(Low.getBitWidth());
7647 CmpRange = High - Low;
7651 uint32_t TotalWeight = 0;
7652 for (unsigned i = First; i <= Last; ++i) {
7653 // Find the CaseBits for this destination.
7655 for (j = 0; j < CBV.size(); ++j)
7656 if (CBV[j].BB == Clusters[i].MBB)
7658 if (j == CBV.size())
7659 CBV.push_back(CaseBits(0, Clusters[i].MBB, 0, 0));
7660 CaseBits *CB = &CBV[j];
7662 // Update Mask, Bits and ExtraWeight.
7663 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
7664 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
7665 for (uint64_t j = Lo; j <= Hi; ++j) {
7666 CB->Mask |= 1ULL << j;
7669 CB->ExtraWeight += Clusters[i].Weight;
7670 TotalWeight += Clusters[i].Weight;
7671 assert(TotalWeight >= Clusters[i].Weight && "Weight overflow!");
7675 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
7676 // Sort by weight first, number of bits second.
7677 if (a.ExtraWeight != b.ExtraWeight)
7678 return a.ExtraWeight > b.ExtraWeight;
7679 return a.Bits > b.Bits;
7682 for (auto &CB : CBV) {
7683 MachineBasicBlock *BitTestBB =
7684 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
7685 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraWeight));
7687 BitTestCases.push_back(BitTestBlock(LowBound, CmpRange, SI->getCondition(),
7688 -1U, MVT::Other, false, nullptr,
7689 nullptr, std::move(BTI)));
7691 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
7692 BitTestCases.size() - 1, TotalWeight);
7696 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
7697 const SwitchInst *SI) {
7698 // Partition Clusters into as few subsets as possible, where each subset has a
7699 // range that fits in a machine word and has <= 3 unique destinations.
7702 // Clusters must be sorted and contain Range or JumpTable clusters.
7703 assert(!Clusters.empty());
7704 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
7705 for (const CaseCluster &C : Clusters)
7706 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
7707 for (unsigned i = 1; i < Clusters.size(); ++i)
7708 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
7711 // If target does not have legal shift left, do not emit bit tests at all.
7712 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7713 EVT PTy = TLI.getPointerTy();
7714 if (!TLI.isOperationLegal(ISD::SHL, PTy))
7717 int BitWidth = PTy.getSizeInBits();
7718 const int64_t N = Clusters.size();
7720 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
7721 SmallVector<unsigned, 8> MinPartitions(N);
7722 // LastElement[i] is the last element of the partition starting at i.
7723 SmallVector<unsigned, 8> LastElement(N);
7725 // FIXME: This might not be the best algorithm for finding bit test clusters.
7727 // Base case: There is only one way to partition Clusters[N-1].
7728 MinPartitions[N - 1] = 1;
7729 LastElement[N - 1] = N - 1;
7731 // Note: loop indexes are signed to avoid underflow.
7732 for (int64_t i = N - 2; i >= 0; --i) {
7733 // Find optimal partitioning of Clusters[i..N-1].
7734 // Baseline: Put Clusters[i] into a partition on its own.
7735 MinPartitions[i] = MinPartitions[i + 1] + 1;
7738 // Search for a solution that results in fewer partitions.
7739 // Note: the search is limited by BitWidth, reducing time complexity.
7740 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
7741 // Try building a partition from Clusters[i..j].
7744 if (!rangeFitsInWord(Clusters[i].Low->getValue(),
7745 Clusters[j].High->getValue()))
7748 // Check nbr of destinations and cluster types.
7749 // FIXME: This works, but doesn't seem very efficient.
7750 bool RangesOnly = true;
7751 BitVector Dests(FuncInfo.MF->getNumBlockIDs());
7752 for (int64_t k = i; k <= j; k++) {
7753 if (Clusters[k].Kind != CC_Range) {
7757 Dests.set(Clusters[k].MBB->getNumber());
7759 if (!RangesOnly || Dests.count() > 3)
7762 // Check if it's a better partition.
7763 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
7764 if (NumPartitions < MinPartitions[i]) {
7765 // Found a better partition.
7766 MinPartitions[i] = NumPartitions;
7772 // Iterate over the partitions, replacing with bit-test clusters in-place.
7773 unsigned DstIndex = 0;
7774 for (unsigned First = 0, Last; First < N; First = Last + 1) {
7775 Last = LastElement[First];
7776 assert(First <= Last);
7777 assert(DstIndex <= First);
7779 CaseCluster BitTestCluster;
7780 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
7781 Clusters[DstIndex++] = BitTestCluster;
7783 for (unsigned I = First; I <= Last; ++I)
7784 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
7787 Clusters.resize(DstIndex);
7790 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
7791 MachineBasicBlock *SwitchMBB,
7792 MachineBasicBlock *DefaultMBB) {
7793 MachineFunction *CurMF = FuncInfo.MF;
7794 MachineBasicBlock *NextMBB = nullptr;
7795 MachineFunction::iterator BBI = W.MBB;
7796 if (++BBI != FuncInfo.MF->end())
7799 unsigned Size = W.LastCluster - W.FirstCluster + 1;
7801 BranchProbabilityInfo *BPI = FuncInfo.BPI;
7803 if (Size == 2 && W.MBB == SwitchMBB) {
7804 // If any two of the cases has the same destination, and if one value
7805 // is the same as the other, but has one bit unset that the other has set,
7806 // use bit manipulation to do two compares at once. For example:
7807 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
7808 // TODO: This could be extended to merge any 2 cases in switches with 3
7810 // TODO: Handle cases where W.CaseBB != SwitchBB.
7811 CaseCluster &Small = *W.FirstCluster;
7812 CaseCluster &Big = *W.LastCluster;
7814 if (Small.Low == Small.High && Big.Low == Big.High &&
7815 Small.MBB == Big.MBB) {
7816 const APInt &SmallValue = Small.Low->getValue();
7817 const APInt &BigValue = Big.Low->getValue();
7819 // Check that there is only one bit different.
7820 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
7821 (SmallValue | BigValue) == BigValue) {
7822 // Isolate the common bit.
7823 APInt CommonBit = BigValue & ~SmallValue;
7824 assert((SmallValue | CommonBit) == BigValue &&
7825 CommonBit.countPopulation() == 1 && "Not a common bit?");
7827 SDValue CondLHS = getValue(Cond);
7828 EVT VT = CondLHS.getValueType();
7829 SDLoc DL = getCurSDLoc();
7831 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
7832 DAG.getConstant(CommonBit, DL, VT));
7833 SDValue Cond = DAG.getSetCC(DL, MVT::i1, Or,
7834 DAG.getConstant(BigValue, DL, VT),
7837 // Update successor info.
7838 // Both Small and Big will jump to Small.BB, so we sum up the weights.
7839 addSuccessorWithWeight(SwitchMBB, Small.MBB, Small.Weight + Big.Weight);
7840 addSuccessorWithWeight(
7841 SwitchMBB, DefaultMBB,
7842 // The default destination is the first successor in IR.
7843 BPI ? BPI->getEdgeWeight(SwitchMBB->getBasicBlock(), (unsigned)0)
7846 // Insert the true branch.
7848 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
7849 DAG.getBasicBlock(Small.MBB));
7850 // Insert the false branch.
7851 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
7852 DAG.getBasicBlock(DefaultMBB));
7854 DAG.setRoot(BrCond);
7860 if (TM.getOptLevel() != CodeGenOpt::None) {
7861 // Order cases by weight so the most likely case will be checked first.
7862 std::sort(W.FirstCluster, W.LastCluster + 1,
7863 [](const CaseCluster &a, const CaseCluster &b) {
7864 return a.Weight > b.Weight;
7867 // Rearrange the case blocks so that the last one falls through if possible
7868 // without without changing the order of weights.
7869 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
7871 if (I->Weight > W.LastCluster->Weight)
7873 if (I->Kind == CC_Range && I->MBB == NextMBB) {
7874 std::swap(*I, *W.LastCluster);
7880 // Compute total weight.
7881 uint32_t UnhandledWeights = 0;
7882 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) {
7883 UnhandledWeights += I->Weight;
7884 assert(UnhandledWeights >= I->Weight && "Weight overflow!");
7887 MachineBasicBlock *CurMBB = W.MBB;
7888 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
7889 MachineBasicBlock *Fallthrough;
7890 if (I == W.LastCluster) {
7891 // For the last cluster, fall through to the default destination.
7892 Fallthrough = DefaultMBB;
7894 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
7895 CurMF->insert(BBI, Fallthrough);
7896 // Put Cond in a virtual register to make it available from the new blocks.
7897 ExportFromCurrentBlock(Cond);
7901 case CC_JumpTable: {
7902 // FIXME: Optimize away range check based on pivot comparisons.
7903 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
7904 JumpTable *JT = &JTCases[I->JTCasesIndex].second;
7906 // The jump block hasn't been inserted yet; insert it here.
7907 MachineBasicBlock *JumpMBB = JT->MBB;
7908 CurMF->insert(BBI, JumpMBB);
7909 addSuccessorWithWeight(CurMBB, Fallthrough);
7910 addSuccessorWithWeight(CurMBB, JumpMBB);
7912 // The jump table header will be inserted in our current block, do the
7913 // range check, and fall through to our fallthrough block.
7914 JTH->HeaderBB = CurMBB;
7915 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
7917 // If we're in the right place, emit the jump table header right now.
7918 if (CurMBB == SwitchMBB) {
7919 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
7920 JTH->Emitted = true;
7925 // FIXME: Optimize away range check based on pivot comparisons.
7926 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
7928 // The bit test blocks haven't been inserted yet; insert them here.
7929 for (BitTestCase &BTC : BTB->Cases)
7930 CurMF->insert(BBI, BTC.ThisBB);
7932 // Fill in fields of the BitTestBlock.
7933 BTB->Parent = CurMBB;
7934 BTB->Default = Fallthrough;
7936 // If we're in the right place, emit the bit test header header right now.
7937 if (CurMBB ==SwitchMBB) {
7938 visitBitTestHeader(*BTB, SwitchMBB);
7939 BTB->Emitted = true;
7944 const Value *RHS, *LHS, *MHS;
7946 if (I->Low == I->High) {
7947 // Check Cond == I->Low.
7953 // Check I->Low <= Cond <= I->High.
7960 // The false weight is the sum of all unhandled cases.
7961 UnhandledWeights -= I->Weight;
7962 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Weight,
7965 if (CurMBB == SwitchMBB)
7966 visitSwitchCase(CB, SwitchMBB);
7968 SwitchCases.push_back(CB);
7973 CurMBB = Fallthrough;
7977 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
7978 const SwitchWorkListItem &W,
7980 MachineBasicBlock *SwitchMBB) {
7981 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
7982 "Clusters not sorted?");
7984 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
7985 assert(NumClusters >= 2 && "Too small to split!");
7987 // FIXME: When we have profile info, we might want to balance the tree based
7988 // on weights instead of node count.
7990 CaseClusterIt PivotCluster = W.FirstCluster + NumClusters / 2;
7991 CaseClusterIt FirstLeft = W.FirstCluster;
7992 CaseClusterIt LastLeft = PivotCluster - 1;
7993 CaseClusterIt FirstRight = PivotCluster;
7994 CaseClusterIt LastRight = W.LastCluster;
7995 const ConstantInt *Pivot = PivotCluster->Low;
7997 // New blocks will be inserted immediately after the current one.
7998 MachineFunction::iterator BBI = W.MBB;
8001 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
8002 // we can branch to its destination directly if it's squeezed exactly in
8003 // between the known lower bound and Pivot - 1.
8004 MachineBasicBlock *LeftMBB;
8005 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
8006 FirstLeft->Low == W.GE &&
8007 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
8008 LeftMBB = FirstLeft->MBB;
8010 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8011 FuncInfo.MF->insert(BBI, LeftMBB);
8012 WorkList.push_back({LeftMBB, FirstLeft, LastLeft, W.GE, Pivot});
8013 // Put Cond in a virtual register to make it available from the new blocks.
8014 ExportFromCurrentBlock(Cond);
8017 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
8018 // single cluster, RHS.Low == Pivot, and we can branch to its destination
8019 // directly if RHS.High equals the current upper bound.
8020 MachineBasicBlock *RightMBB;
8021 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
8022 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
8023 RightMBB = FirstRight->MBB;
8025 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8026 FuncInfo.MF->insert(BBI, RightMBB);
8027 WorkList.push_back({RightMBB, FirstRight, LastRight, Pivot, W.LT});
8028 // Put Cond in a virtual register to make it available from the new blocks.
8029 ExportFromCurrentBlock(Cond);
8032 // Create the CaseBlock record that will be used to lower the branch.
8033 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB);
8035 if (W.MBB == SwitchMBB)
8036 visitSwitchCase(CB, SwitchMBB);
8038 SwitchCases.push_back(CB);
8041 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
8042 // Extract cases from the switch.
8043 BranchProbabilityInfo *BPI = FuncInfo.BPI;
8044 CaseClusterVector Clusters;
8045 Clusters.reserve(SI.getNumCases());
8046 for (auto I : SI.cases()) {
8047 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
8048 const ConstantInt *CaseVal = I.getCaseValue();
8049 uint32_t Weight = 0; // FIXME: Use 1 instead?
8051 Weight = BPI->getEdgeWeight(SI.getParent(), I.getSuccessorIndex());
8052 assert(Weight <= UINT32_MAX / SI.getNumSuccessors());
8054 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Weight));
8057 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
8059 if (TM.getOptLevel() != CodeGenOpt::None) {
8060 // Cluster adjacent cases with the same destination.
8061 sortAndRangeify(Clusters);
8063 // Replace an unreachable default with the most popular destination.
8064 // FIXME: Exploit unreachable default more aggressively.
8065 bool UnreachableDefault =
8066 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
8067 if (UnreachableDefault && !Clusters.empty()) {
8068 DenseMap<const BasicBlock *, unsigned> Popularity;
8069 unsigned MaxPop = 0;
8070 const BasicBlock *MaxBB = nullptr;
8071 for (auto I : SI.cases()) {
8072 const BasicBlock *BB = I.getCaseSuccessor();
8073 if (++Popularity[BB] > MaxPop) {
8074 MaxPop = Popularity[BB];
8079 assert(MaxPop > 0 && MaxBB);
8080 DefaultMBB = FuncInfo.MBBMap[MaxBB];
8082 // Remove cases that were pointing to the destination that is now the
8084 CaseClusterVector New;
8085 New.reserve(Clusters.size());
8086 for (CaseCluster &CC : Clusters) {
8087 if (CC.MBB != DefaultMBB)
8090 Clusters = std::move(New);
8094 // If there is only the default destination, jump there directly.
8095 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
8096 if (Clusters.empty()) {
8097 SwitchMBB->addSuccessor(DefaultMBB);
8098 if (DefaultMBB != NextBlock(SwitchMBB)) {
8099 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
8100 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
8105 if (TM.getOptLevel() != CodeGenOpt::None) {
8106 findJumpTables(Clusters, &SI, DefaultMBB);
8107 findBitTestClusters(Clusters, &SI);
8112 dbgs() << "Case clusters: ";
8113 for (const CaseCluster &C : Clusters) {
8114 if (C.Kind == CC_JumpTable) dbgs() << "JT:";
8115 if (C.Kind == CC_BitTests) dbgs() << "BT:";
8117 C.Low->getValue().print(dbgs(), true);
8118 if (C.Low != C.High) {
8120 C.High->getValue().print(dbgs(), true);
8127 assert(!Clusters.empty());
8128 SwitchWorkList WorkList;
8129 CaseClusterIt First = Clusters.begin();
8130 CaseClusterIt Last = Clusters.end() - 1;
8131 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr});
8133 while (!WorkList.empty()) {
8134 SwitchWorkListItem W = WorkList.back();
8135 WorkList.pop_back();
8136 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
8138 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) {
8139 // For optimized builds, lower large range as a balanced binary tree.
8140 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
8144 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);