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/ValueTracking.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GCMetadata.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/StackMaps.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugInfo.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/Statepoint.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetFrameLowering.h"
57 #include "llvm/Target/TargetInstrInfo.h"
58 #include "llvm/Target/TargetIntrinsicInfo.h"
59 #include "llvm/Target/TargetLibraryInfo.h"
60 #include "llvm/Target/TargetLowering.h"
61 #include "llvm/Target/TargetOptions.h"
62 #include "llvm/Target/TargetSelectionDAGInfo.h"
63 #include "llvm/Target/TargetSubtargetInfo.h"
67 #define DEBUG_TYPE "isel"
69 /// LimitFloatPrecision - Generate low-precision inline sequences for
70 /// some float libcalls (6, 8 or 12 bits).
71 static unsigned LimitFloatPrecision;
73 static cl::opt<unsigned, true>
74 LimitFPPrecision("limit-float-precision",
75 cl::desc("Generate low-precision inline sequences "
76 "for some float libcalls"),
77 cl::location(LimitFloatPrecision),
80 // Limit the width of DAG chains. This is important in general to prevent
81 // prevent DAG-based analysis from blowing up. For example, alias analysis and
82 // load clustering may not complete in reasonable time. It is difficult to
83 // recognize and avoid this situation within each individual analysis, and
84 // future analyses are likely to have the same behavior. Limiting DAG width is
85 // the safe approach, and will be especially important with global DAGs.
87 // MaxParallelChains default is arbitrarily high to avoid affecting
88 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
89 // sequence over this should have been converted to llvm.memcpy by the
90 // frontend. It easy to induce this behavior with .ll code such as:
91 // %buffer = alloca [4096 x i8]
92 // %data = load [4096 x i8]* %argPtr
93 // store [4096 x i8] %data, [4096 x i8]* %buffer
94 static const unsigned MaxParallelChains = 64;
96 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
97 const SDValue *Parts, unsigned NumParts,
98 MVT PartVT, EVT ValueVT, const Value *V);
100 /// getCopyFromParts - Create a value that contains the specified legal parts
101 /// combined into the value they represent. If the parts combine to a type
102 /// larger then ValueVT then AssertOp can be used to specify whether the extra
103 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
104 /// (ISD::AssertSext).
105 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
106 const SDValue *Parts,
107 unsigned NumParts, MVT PartVT, EVT ValueVT,
109 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
110 if (ValueVT.isVector())
111 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
114 assert(NumParts > 0 && "No parts to assemble!");
115 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
116 SDValue Val = Parts[0];
119 // Assemble the value from multiple parts.
120 if (ValueVT.isInteger()) {
121 unsigned PartBits = PartVT.getSizeInBits();
122 unsigned ValueBits = ValueVT.getSizeInBits();
124 // Assemble the power of 2 part.
125 unsigned RoundParts = NumParts & (NumParts - 1) ?
126 1 << Log2_32(NumParts) : NumParts;
127 unsigned RoundBits = PartBits * RoundParts;
128 EVT RoundVT = RoundBits == ValueBits ?
129 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
132 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
134 if (RoundParts > 2) {
135 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
137 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
138 RoundParts / 2, PartVT, HalfVT, V);
140 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
141 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
144 if (TLI.isBigEndian())
147 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
149 if (RoundParts < NumParts) {
150 // Assemble the trailing non-power-of-2 part.
151 unsigned OddParts = NumParts - RoundParts;
152 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
153 Hi = getCopyFromParts(DAG, DL,
154 Parts + RoundParts, OddParts, PartVT, OddVT, V);
156 // Combine the round and odd parts.
158 if (TLI.isBigEndian())
160 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
161 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
162 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
163 DAG.getConstant(Lo.getValueType().getSizeInBits(),
164 TLI.getPointerTy()));
165 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
166 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
168 } else if (PartVT.isFloatingPoint()) {
169 // FP split into multiple FP parts (for ppcf128)
170 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
173 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
174 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
175 if (TLI.hasBigEndianPartOrdering(ValueVT))
177 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
179 // FP split into integer parts (soft fp)
180 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
181 !PartVT.isVector() && "Unexpected split");
182 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
183 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
187 // There is now one part, held in Val. Correct it to match ValueVT.
188 EVT PartEVT = Val.getValueType();
190 if (PartEVT == ValueVT)
193 if (PartEVT.isInteger() && ValueVT.isInteger()) {
194 if (ValueVT.bitsLT(PartEVT)) {
195 // For a truncate, see if we have any information to
196 // indicate whether the truncated bits will always be
197 // zero or sign-extension.
198 if (AssertOp != ISD::DELETED_NODE)
199 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
200 DAG.getValueType(ValueVT));
201 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
203 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
206 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
207 // FP_ROUND's are always exact here.
208 if (ValueVT.bitsLT(Val.getValueType()))
209 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
210 DAG.getTargetConstant(1, TLI.getPointerTy()));
212 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
215 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
216 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
218 llvm_unreachable("Unknown mismatch!");
221 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
222 const Twine &ErrMsg) {
223 const Instruction *I = dyn_cast_or_null<Instruction>(V);
225 return Ctx.emitError(ErrMsg);
227 const char *AsmError = ", possible invalid constraint for vector type";
228 if (const CallInst *CI = dyn_cast<CallInst>(I))
229 if (isa<InlineAsm>(CI->getCalledValue()))
230 return Ctx.emitError(I, ErrMsg + AsmError);
232 return Ctx.emitError(I, ErrMsg);
235 /// getCopyFromPartsVector - Create a value that contains the specified legal
236 /// parts combined into the value they represent. If the parts combine to a
237 /// type larger then ValueVT then AssertOp can be used to specify whether the
238 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
239 /// ValueVT (ISD::AssertSext).
240 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
241 const SDValue *Parts, unsigned NumParts,
242 MVT PartVT, EVT ValueVT, const Value *V) {
243 assert(ValueVT.isVector() && "Not a vector value");
244 assert(NumParts > 0 && "No parts to assemble!");
245 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
246 SDValue Val = Parts[0];
248 // Handle a multi-element vector.
252 unsigned NumIntermediates;
254 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
255 NumIntermediates, RegisterVT);
256 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
257 NumParts = NumRegs; // Silence a compiler warning.
258 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
259 assert(RegisterVT == Parts[0].getSimpleValueType() &&
260 "Part type doesn't match part!");
262 // Assemble the parts into intermediate operands.
263 SmallVector<SDValue, 8> Ops(NumIntermediates);
264 if (NumIntermediates == NumParts) {
265 // If the register was not expanded, truncate or copy the value,
267 for (unsigned i = 0; i != NumParts; ++i)
268 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
269 PartVT, IntermediateVT, V);
270 } else if (NumParts > 0) {
271 // If the intermediate type was expanded, build the intermediate
272 // operands from the parts.
273 assert(NumParts % NumIntermediates == 0 &&
274 "Must expand into a divisible number of parts!");
275 unsigned Factor = NumParts / NumIntermediates;
276 for (unsigned i = 0; i != NumIntermediates; ++i)
277 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
278 PartVT, IntermediateVT, V);
281 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
282 // intermediate operands.
283 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
288 // There is now one part, held in Val. Correct it to match ValueVT.
289 EVT PartEVT = Val.getValueType();
291 if (PartEVT == ValueVT)
294 if (PartEVT.isVector()) {
295 // If the element type of the source/dest vectors are the same, but the
296 // parts vector has more elements than the value vector, then we have a
297 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
299 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
300 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
301 "Cannot narrow, it would be a lossy transformation");
302 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
303 DAG.getConstant(0, TLI.getVectorIdxTy()));
306 // Vector/Vector bitcast.
307 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
308 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
310 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
311 "Cannot handle this kind of promotion");
312 // Promoted vector extract
313 bool Smaller = ValueVT.bitsLE(PartEVT);
314 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
319 // Trivial bitcast if the types are the same size and the destination
320 // vector type is legal.
321 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
322 TLI.isTypeLegal(ValueVT))
323 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
325 // Handle cases such as i8 -> <1 x i1>
326 if (ValueVT.getVectorNumElements() != 1) {
327 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
328 "non-trivial scalar-to-vector conversion");
329 return DAG.getUNDEF(ValueVT);
332 if (ValueVT.getVectorNumElements() == 1 &&
333 ValueVT.getVectorElementType() != PartEVT) {
334 bool Smaller = ValueVT.bitsLE(PartEVT);
335 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
336 DL, ValueVT.getScalarType(), Val);
339 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
342 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
343 SDValue Val, SDValue *Parts, unsigned NumParts,
344 MVT PartVT, const Value *V);
346 /// getCopyToParts - Create a series of nodes that contain the specified value
347 /// split into legal parts. If the parts contain more bits than Val, then, for
348 /// integers, ExtendKind can be used to specify how to generate the extra bits.
349 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
350 SDValue Val, SDValue *Parts, unsigned NumParts,
351 MVT PartVT, const Value *V,
352 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
353 EVT ValueVT = Val.getValueType();
355 // Handle the vector case separately.
356 if (ValueVT.isVector())
357 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
359 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
360 unsigned PartBits = PartVT.getSizeInBits();
361 unsigned OrigNumParts = NumParts;
362 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
367 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
368 EVT PartEVT = PartVT;
369 if (PartEVT == ValueVT) {
370 assert(NumParts == 1 && "No-op copy with multiple parts!");
375 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
376 // If the parts cover more bits than the value has, promote the value.
377 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
378 assert(NumParts == 1 && "Do not know what to promote to!");
379 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
381 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
382 ValueVT.isInteger() &&
383 "Unknown mismatch!");
384 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
385 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
386 if (PartVT == MVT::x86mmx)
387 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
389 } else if (PartBits == ValueVT.getSizeInBits()) {
390 // Different types of the same size.
391 assert(NumParts == 1 && PartEVT != ValueVT);
392 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
393 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
394 // If the parts cover less bits than value has, truncate the value.
395 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
396 ValueVT.isInteger() &&
397 "Unknown mismatch!");
398 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
399 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
400 if (PartVT == MVT::x86mmx)
401 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
404 // The value may have changed - recompute ValueVT.
405 ValueVT = Val.getValueType();
406 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
407 "Failed to tile the value with PartVT!");
410 if (PartEVT != ValueVT)
411 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
412 "scalar-to-vector conversion failed");
418 // Expand the value into multiple parts.
419 if (NumParts & (NumParts - 1)) {
420 // The number of parts is not a power of 2. Split off and copy the tail.
421 assert(PartVT.isInteger() && ValueVT.isInteger() &&
422 "Do not know what to expand to!");
423 unsigned RoundParts = 1 << Log2_32(NumParts);
424 unsigned RoundBits = RoundParts * PartBits;
425 unsigned OddParts = NumParts - RoundParts;
426 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
427 DAG.getIntPtrConstant(RoundBits));
428 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
430 if (TLI.isBigEndian())
431 // The odd parts were reversed by getCopyToParts - unreverse them.
432 std::reverse(Parts + RoundParts, Parts + NumParts);
434 NumParts = RoundParts;
435 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
436 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
439 // The number of parts is a power of 2. Repeatedly bisect the value using
441 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
442 EVT::getIntegerVT(*DAG.getContext(),
443 ValueVT.getSizeInBits()),
446 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
447 for (unsigned i = 0; i < NumParts; i += StepSize) {
448 unsigned ThisBits = StepSize * PartBits / 2;
449 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
450 SDValue &Part0 = Parts[i];
451 SDValue &Part1 = Parts[i+StepSize/2];
453 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
454 ThisVT, Part0, DAG.getIntPtrConstant(1));
455 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
456 ThisVT, Part0, DAG.getIntPtrConstant(0));
458 if (ThisBits == PartBits && ThisVT != PartVT) {
459 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
460 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
465 if (TLI.isBigEndian())
466 std::reverse(Parts, Parts + OrigNumParts);
470 /// getCopyToPartsVector - Create a series of nodes that contain the specified
471 /// value split into legal parts.
472 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
473 SDValue Val, SDValue *Parts, unsigned NumParts,
474 MVT PartVT, const Value *V) {
475 EVT ValueVT = Val.getValueType();
476 assert(ValueVT.isVector() && "Not a vector");
477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
480 EVT PartEVT = PartVT;
481 if (PartEVT == ValueVT) {
483 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
484 // Bitconvert vector->vector case.
485 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
486 } else if (PartVT.isVector() &&
487 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
488 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
489 EVT ElementVT = PartVT.getVectorElementType();
490 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
492 SmallVector<SDValue, 16> Ops;
493 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
494 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
495 ElementVT, Val, DAG.getConstant(i,
496 TLI.getVectorIdxTy())));
498 for (unsigned i = ValueVT.getVectorNumElements(),
499 e = PartVT.getVectorNumElements(); i != e; ++i)
500 Ops.push_back(DAG.getUNDEF(ElementVT));
502 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
504 // FIXME: Use CONCAT for 2x -> 4x.
506 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
507 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
508 } else if (PartVT.isVector() &&
509 PartEVT.getVectorElementType().bitsGE(
510 ValueVT.getVectorElementType()) &&
511 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
513 // Promoted vector extract
514 bool Smaller = PartEVT.bitsLE(ValueVT);
515 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
518 // Vector -> scalar conversion.
519 assert(ValueVT.getVectorNumElements() == 1 &&
520 "Only trivial vector-to-scalar conversions should get here!");
521 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
522 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
524 bool Smaller = ValueVT.bitsLE(PartVT);
525 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
533 // Handle a multi-element vector.
536 unsigned NumIntermediates;
537 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
539 NumIntermediates, RegisterVT);
540 unsigned NumElements = ValueVT.getVectorNumElements();
542 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
543 NumParts = NumRegs; // Silence a compiler warning.
544 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
546 // Split the vector into intermediate operands.
547 SmallVector<SDValue, 8> Ops(NumIntermediates);
548 for (unsigned i = 0; i != NumIntermediates; ++i) {
549 if (IntermediateVT.isVector())
550 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
552 DAG.getConstant(i * (NumElements / NumIntermediates),
553 TLI.getVectorIdxTy()));
555 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
557 DAG.getConstant(i, TLI.getVectorIdxTy()));
560 // Split the intermediate operands into legal parts.
561 if (NumParts == NumIntermediates) {
562 // If the register was not expanded, promote or copy the value,
564 for (unsigned i = 0; i != NumParts; ++i)
565 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
566 } else if (NumParts > 0) {
567 // If the intermediate type was expanded, split each the value into
569 assert(NumParts % NumIntermediates == 0 &&
570 "Must expand into a divisible number of parts!");
571 unsigned Factor = NumParts / NumIntermediates;
572 for (unsigned i = 0; i != NumIntermediates; ++i)
573 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
578 /// RegsForValue - This struct represents the registers (physical or virtual)
579 /// that a particular set of values is assigned, and the type information
580 /// about the value. The most common situation is to represent one value at a
581 /// time, but struct or array values are handled element-wise as multiple
582 /// values. The splitting of aggregates is performed recursively, so that we
583 /// never have aggregate-typed registers. The values at this point do not
584 /// necessarily have legal types, so each value may require one or more
585 /// registers of some legal type.
587 struct RegsForValue {
588 /// ValueVTs - The value types of the values, which may not be legal, and
589 /// may need be promoted or synthesized from one or more registers.
591 SmallVector<EVT, 4> ValueVTs;
593 /// RegVTs - The value types of the registers. This is the same size as
594 /// ValueVTs and it records, for each value, what the type of the assigned
595 /// register or registers are. (Individual values are never synthesized
596 /// from more than one type of register.)
598 /// With virtual registers, the contents of RegVTs is redundant with TLI's
599 /// getRegisterType member function, however when with physical registers
600 /// it is necessary to have a separate record of the types.
602 SmallVector<MVT, 4> RegVTs;
604 /// Regs - This list holds the registers assigned to the values.
605 /// Each legal or promoted value requires one register, and each
606 /// expanded value requires multiple registers.
608 SmallVector<unsigned, 4> Regs;
612 RegsForValue(const SmallVector<unsigned, 4> ®s,
613 MVT regvt, EVT valuevt)
614 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
616 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
617 unsigned Reg, Type *Ty) {
618 ComputeValueVTs(tli, Ty, ValueVTs);
620 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
621 EVT ValueVT = ValueVTs[Value];
622 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
623 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
624 for (unsigned i = 0; i != NumRegs; ++i)
625 Regs.push_back(Reg + i);
626 RegVTs.push_back(RegisterVT);
631 /// append - Add the specified values to this one.
632 void append(const RegsForValue &RHS) {
633 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
634 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
635 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
638 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
639 /// this value and returns the result as a ValueVTs value. This uses
640 /// Chain/Flag as the input and updates them for the output Chain/Flag.
641 /// If the Flag pointer is NULL, no flag is used.
642 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
644 SDValue &Chain, SDValue *Flag,
645 const Value *V = nullptr) const;
647 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
648 /// specified value into the registers specified by this object. This uses
649 /// Chain/Flag as the input and updates them for the output Chain/Flag.
650 /// If the Flag pointer is NULL, no flag is used.
652 getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
653 SDValue *Flag, const Value *V,
654 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
656 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
657 /// operand list. This adds the code marker, matching input operand index
658 /// (if applicable), and includes the number of values added into it.
659 void AddInlineAsmOperands(unsigned Kind,
660 bool HasMatching, unsigned MatchingIdx,
662 std::vector<SDValue> &Ops) const;
666 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
667 /// this value and returns the result as a ValueVT value. This uses
668 /// Chain/Flag as the input and updates them for the output Chain/Flag.
669 /// If the Flag pointer is NULL, no flag is used.
670 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
671 FunctionLoweringInfo &FuncInfo,
673 SDValue &Chain, SDValue *Flag,
674 const Value *V) const {
675 // A Value with type {} or [0 x %t] needs no registers.
676 if (ValueVTs.empty())
679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
681 // Assemble the legal parts into the final values.
682 SmallVector<SDValue, 4> Values(ValueVTs.size());
683 SmallVector<SDValue, 8> Parts;
684 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
685 // Copy the legal parts from the registers.
686 EVT ValueVT = ValueVTs[Value];
687 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
688 MVT RegisterVT = RegVTs[Value];
690 Parts.resize(NumRegs);
691 for (unsigned i = 0; i != NumRegs; ++i) {
694 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
696 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
697 *Flag = P.getValue(2);
700 Chain = P.getValue(1);
703 // If the source register was virtual and if we know something about it,
704 // add an assert node.
705 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
706 !RegisterVT.isInteger() || RegisterVT.isVector())
709 const FunctionLoweringInfo::LiveOutInfo *LOI =
710 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
714 unsigned RegSize = RegisterVT.getSizeInBits();
715 unsigned NumSignBits = LOI->NumSignBits;
716 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
718 if (NumZeroBits == RegSize) {
719 // The current value is a zero.
720 // Explicitly express that as it would be easier for
721 // optimizations to kick in.
722 Parts[i] = DAG.getConstant(0, RegisterVT);
726 // FIXME: We capture more information than the dag can represent. For
727 // now, just use the tightest assertzext/assertsext possible.
729 EVT FromVT(MVT::Other);
730 if (NumSignBits == RegSize)
731 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
732 else if (NumZeroBits >= RegSize-1)
733 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
734 else if (NumSignBits > RegSize-8)
735 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
736 else if (NumZeroBits >= RegSize-8)
737 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
738 else if (NumSignBits > RegSize-16)
739 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
740 else if (NumZeroBits >= RegSize-16)
741 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
742 else if (NumSignBits > RegSize-32)
743 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
744 else if (NumZeroBits >= RegSize-32)
745 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
749 // Add an assertion node.
750 assert(FromVT != MVT::Other);
751 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
752 RegisterVT, P, DAG.getValueType(FromVT));
755 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
756 NumRegs, RegisterVT, ValueVT, V);
761 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
764 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
765 /// specified value into the registers specified by this object. This uses
766 /// Chain/Flag as the input and updates them for the output Chain/Flag.
767 /// If the Flag pointer is NULL, no flag is used.
768 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
769 SDValue &Chain, SDValue *Flag, const Value *V,
770 ISD::NodeType PreferredExtendType) const {
771 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
772 ISD::NodeType ExtendKind = PreferredExtendType;
774 // Get the list of the values's legal parts.
775 unsigned NumRegs = Regs.size();
776 SmallVector<SDValue, 8> Parts(NumRegs);
777 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
778 EVT ValueVT = ValueVTs[Value];
779 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
780 MVT RegisterVT = RegVTs[Value];
782 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
783 ExtendKind = ISD::ZERO_EXTEND;
785 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
786 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
790 // Copy the parts into the registers.
791 SmallVector<SDValue, 8> Chains(NumRegs);
792 for (unsigned i = 0; i != NumRegs; ++i) {
795 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
797 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
798 *Flag = Part.getValue(1);
801 Chains[i] = Part.getValue(0);
804 if (NumRegs == 1 || Flag)
805 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
806 // flagged to it. That is the CopyToReg nodes and the user are considered
807 // a single scheduling unit. If we create a TokenFactor and return it as
808 // chain, then the TokenFactor is both a predecessor (operand) of the
809 // user as well as a successor (the TF operands are flagged to the user).
810 // c1, f1 = CopyToReg
811 // c2, f2 = CopyToReg
812 // c3 = TokenFactor c1, c2
815 Chain = Chains[NumRegs-1];
817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
820 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
821 /// operand list. This adds the code marker and includes the number of
822 /// values added into it.
823 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
824 unsigned MatchingIdx,
826 std::vector<SDValue> &Ops) const {
827 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
829 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
831 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
832 else if (!Regs.empty() &&
833 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
834 // Put the register class of the virtual registers in the flag word. That
835 // way, later passes can recompute register class constraints for inline
836 // assembly as well as normal instructions.
837 // Don't do this for tied operands that can use the regclass information
839 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
840 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
841 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
844 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
847 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
848 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
849 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
850 MVT RegisterVT = RegVTs[Value];
851 for (unsigned i = 0; i != NumRegs; ++i) {
852 assert(Reg < Regs.size() && "Mismatch in # registers expected");
853 unsigned TheReg = Regs[Reg++];
854 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
856 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
857 // If we clobbered the stack pointer, MFI should know about it.
858 assert(DAG.getMachineFunction().getFrameInfo()->
859 hasInlineAsmWithSPAdjust());
865 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
866 const TargetLibraryInfo *li) {
870 DL = DAG.getSubtarget().getDataLayout();
871 Context = DAG.getContext();
872 LPadToCallSiteMap.clear();
875 /// clear - Clear out the current SelectionDAG and the associated
876 /// state and prepare this SelectionDAGBuilder object to be used
877 /// for a new block. This doesn't clear out information about
878 /// additional blocks that are needed to complete switch lowering
879 /// or PHI node updating; that information is cleared out as it is
881 void SelectionDAGBuilder::clear() {
883 UnusedArgNodeMap.clear();
884 PendingLoads.clear();
885 PendingExports.clear();
888 SDNodeOrder = LowestSDNodeOrder;
889 StatepointLowering.clear();
892 /// clearDanglingDebugInfo - Clear the dangling debug information
893 /// map. This function is separated from the clear so that debug
894 /// information that is dangling in a basic block can be properly
895 /// resolved in a different basic block. This allows the
896 /// SelectionDAG to resolve dangling debug information attached
898 void SelectionDAGBuilder::clearDanglingDebugInfo() {
899 DanglingDebugInfoMap.clear();
902 /// getRoot - Return the current virtual root of the Selection DAG,
903 /// flushing any PendingLoad items. This must be done before emitting
904 /// a store or any other node that may need to be ordered after any
905 /// prior load instructions.
907 SDValue SelectionDAGBuilder::getRoot() {
908 if (PendingLoads.empty())
909 return DAG.getRoot();
911 if (PendingLoads.size() == 1) {
912 SDValue Root = PendingLoads[0];
914 PendingLoads.clear();
918 // Otherwise, we have to make a token factor node.
919 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
921 PendingLoads.clear();
926 /// getControlRoot - Similar to getRoot, but instead of flushing all the
927 /// PendingLoad items, flush all the PendingExports items. It is necessary
928 /// to do this before emitting a terminator instruction.
930 SDValue SelectionDAGBuilder::getControlRoot() {
931 SDValue Root = DAG.getRoot();
933 if (PendingExports.empty())
936 // Turn all of the CopyToReg chains into one factored node.
937 if (Root.getOpcode() != ISD::EntryToken) {
938 unsigned i = 0, e = PendingExports.size();
939 for (; i != e; ++i) {
940 assert(PendingExports[i].getNode()->getNumOperands() > 1);
941 if (PendingExports[i].getNode()->getOperand(0) == Root)
942 break; // Don't add the root if we already indirectly depend on it.
946 PendingExports.push_back(Root);
949 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
951 PendingExports.clear();
956 void SelectionDAGBuilder::visit(const Instruction &I) {
957 // Set up outgoing PHI node register values before emitting the terminator.
958 if (isa<TerminatorInst>(&I))
959 HandlePHINodesInSuccessorBlocks(I.getParent());
965 visit(I.getOpcode(), I);
967 if (!isa<TerminatorInst>(&I) && !HasTailCall)
968 CopyToExportRegsIfNeeded(&I);
973 void SelectionDAGBuilder::visitPHI(const PHINode &) {
974 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
977 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
978 // Note: this doesn't use InstVisitor, because it has to work with
979 // ConstantExpr's in addition to instructions.
981 default: llvm_unreachable("Unknown instruction type encountered!");
982 // Build the switch statement using the Instruction.def file.
983 #define HANDLE_INST(NUM, OPCODE, CLASS) \
984 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
985 #include "llvm/IR/Instruction.def"
989 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
990 // generate the debug data structures now that we've seen its definition.
991 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
993 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
995 const DbgValueInst *DI = DDI.getDI();
996 DebugLoc dl = DDI.getdl();
997 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
998 MDNode *Variable = DI->getVariable();
999 MDNode *Expr = DI->getExpression();
1000 uint64_t Offset = DI->getOffset();
1001 // A dbg.value for an alloca is always indirect.
1002 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
1004 if (Val.getNode()) {
1005 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1007 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1008 IsIndirect, Offset, dl, DbgSDNodeOrder);
1009 DAG.AddDbgValue(SDV, Val.getNode(), false);
1012 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1013 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1017 /// getValue - Return an SDValue for the given Value.
1018 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1019 // If we already have an SDValue for this value, use it. It's important
1020 // to do this first, so that we don't create a CopyFromReg if we already
1021 // have a regular SDValue.
1022 SDValue &N = NodeMap[V];
1023 if (N.getNode()) return N;
1025 // If there's a virtual register allocated and initialized for this
1027 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1028 if (It != FuncInfo.ValueMap.end()) {
1029 unsigned InReg = It->second;
1030 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
1032 SDValue Chain = DAG.getEntryNode();
1033 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1034 resolveDanglingDebugInfo(V, N);
1038 // Otherwise create a new SDValue and remember it.
1039 SDValue Val = getValueImpl(V);
1041 resolveDanglingDebugInfo(V, Val);
1045 /// getNonRegisterValue - Return an SDValue for the given Value, but
1046 /// don't look in FuncInfo.ValueMap for a virtual register.
1047 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1048 // If we already have an SDValue for this value, use it.
1049 SDValue &N = NodeMap[V];
1050 if (N.getNode()) return N;
1052 // Otherwise create a new SDValue and remember it.
1053 SDValue Val = getValueImpl(V);
1055 resolveDanglingDebugInfo(V, Val);
1059 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1060 /// Create an SDValue for the given value.
1061 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1062 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1064 if (const Constant *C = dyn_cast<Constant>(V)) {
1065 EVT VT = TLI.getValueType(V->getType(), true);
1067 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1068 return DAG.getConstant(*CI, VT);
1070 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1071 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1073 if (isa<ConstantPointerNull>(C)) {
1074 unsigned AS = V->getType()->getPointerAddressSpace();
1075 return DAG.getConstant(0, TLI.getPointerTy(AS));
1078 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1079 return DAG.getConstantFP(*CFP, VT);
1081 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1082 return DAG.getUNDEF(VT);
1084 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1085 visit(CE->getOpcode(), *CE);
1086 SDValue N1 = NodeMap[V];
1087 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1091 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1092 SmallVector<SDValue, 4> Constants;
1093 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1095 SDNode *Val = getValue(*OI).getNode();
1096 // If the operand is an empty aggregate, there are no values.
1098 // Add each leaf value from the operand to the Constants list
1099 // to form a flattened list of all the values.
1100 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1101 Constants.push_back(SDValue(Val, i));
1104 return DAG.getMergeValues(Constants, getCurSDLoc());
1107 if (const ConstantDataSequential *CDS =
1108 dyn_cast<ConstantDataSequential>(C)) {
1109 SmallVector<SDValue, 4> Ops;
1110 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1111 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1112 // Add each leaf value from the operand to the Constants list
1113 // to form a flattened list of all the values.
1114 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1115 Ops.push_back(SDValue(Val, i));
1118 if (isa<ArrayType>(CDS->getType()))
1119 return DAG.getMergeValues(Ops, getCurSDLoc());
1120 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1124 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1125 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1126 "Unknown struct or array constant!");
1128 SmallVector<EVT, 4> ValueVTs;
1129 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1130 unsigned NumElts = ValueVTs.size();
1132 return SDValue(); // empty struct
1133 SmallVector<SDValue, 4> Constants(NumElts);
1134 for (unsigned i = 0; i != NumElts; ++i) {
1135 EVT EltVT = ValueVTs[i];
1136 if (isa<UndefValue>(C))
1137 Constants[i] = DAG.getUNDEF(EltVT);
1138 else if (EltVT.isFloatingPoint())
1139 Constants[i] = DAG.getConstantFP(0, EltVT);
1141 Constants[i] = DAG.getConstant(0, EltVT);
1144 return DAG.getMergeValues(Constants, getCurSDLoc());
1147 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1148 return DAG.getBlockAddress(BA, VT);
1150 VectorType *VecTy = cast<VectorType>(V->getType());
1151 unsigned NumElements = VecTy->getNumElements();
1153 // Now that we know the number and type of the elements, get that number of
1154 // elements into the Ops array based on what kind of constant it is.
1155 SmallVector<SDValue, 16> Ops;
1156 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1157 for (unsigned i = 0; i != NumElements; ++i)
1158 Ops.push_back(getValue(CV->getOperand(i)));
1160 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1161 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1164 if (EltVT.isFloatingPoint())
1165 Op = DAG.getConstantFP(0, EltVT);
1167 Op = DAG.getConstant(0, EltVT);
1168 Ops.assign(NumElements, Op);
1171 // Create a BUILD_VECTOR node.
1172 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1175 // If this is a static alloca, generate it as the frameindex instead of
1177 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1178 DenseMap<const AllocaInst*, int>::iterator SI =
1179 FuncInfo.StaticAllocaMap.find(AI);
1180 if (SI != FuncInfo.StaticAllocaMap.end())
1181 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1184 // If this is an instruction which fast-isel has deferred, select it now.
1185 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1186 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1187 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1188 SDValue Chain = DAG.getEntryNode();
1189 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1192 llvm_unreachable("Can't get register for value!");
1195 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1197 SDValue Chain = getControlRoot();
1198 SmallVector<ISD::OutputArg, 8> Outs;
1199 SmallVector<SDValue, 8> OutVals;
1201 if (!FuncInfo.CanLowerReturn) {
1202 unsigned DemoteReg = FuncInfo.DemoteRegister;
1203 const Function *F = I.getParent()->getParent();
1205 // Emit a store of the return value through the virtual register.
1206 // Leave Outs empty so that LowerReturn won't try to load return
1207 // registers the usual way.
1208 SmallVector<EVT, 1> PtrValueVTs;
1209 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1212 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1213 SDValue RetOp = getValue(I.getOperand(0));
1215 SmallVector<EVT, 4> ValueVTs;
1216 SmallVector<uint64_t, 4> Offsets;
1217 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1218 unsigned NumValues = ValueVTs.size();
1220 SmallVector<SDValue, 4> Chains(NumValues);
1221 for (unsigned i = 0; i != NumValues; ++i) {
1222 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1223 RetPtr.getValueType(), RetPtr,
1224 DAG.getIntPtrConstant(Offsets[i]));
1226 DAG.getStore(Chain, getCurSDLoc(),
1227 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1228 // FIXME: better loc info would be nice.
1229 Add, MachinePointerInfo(), false, false, 0);
1232 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1233 MVT::Other, Chains);
1234 } else if (I.getNumOperands() != 0) {
1235 SmallVector<EVT, 4> ValueVTs;
1236 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1237 unsigned NumValues = ValueVTs.size();
1239 SDValue RetOp = getValue(I.getOperand(0));
1240 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1241 EVT VT = ValueVTs[j];
1243 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1245 const Function *F = I.getParent()->getParent();
1246 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1248 ExtendKind = ISD::SIGN_EXTEND;
1249 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1251 ExtendKind = ISD::ZERO_EXTEND;
1253 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1254 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1256 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1257 MVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1258 SmallVector<SDValue, 4> Parts(NumParts);
1259 getCopyToParts(DAG, getCurSDLoc(),
1260 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1261 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1263 // 'inreg' on function refers to return value
1264 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1265 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1269 // Propagate extension type if any
1270 if (ExtendKind == ISD::SIGN_EXTEND)
1272 else if (ExtendKind == ISD::ZERO_EXTEND)
1275 for (unsigned i = 0; i < NumParts; ++i) {
1276 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1277 VT, /*isfixed=*/true, 0, 0));
1278 OutVals.push_back(Parts[i]);
1284 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1285 CallingConv::ID CallConv =
1286 DAG.getMachineFunction().getFunction()->getCallingConv();
1287 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1288 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1290 // Verify that the target's LowerReturn behaved as expected.
1291 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1292 "LowerReturn didn't return a valid chain!");
1294 // Update the DAG with the new chain value resulting from return lowering.
1298 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1299 /// created for it, emit nodes to copy the value into the virtual
1301 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1303 if (V->getType()->isEmptyTy())
1306 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1307 if (VMI != FuncInfo.ValueMap.end()) {
1308 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1309 CopyValueToVirtualRegister(V, VMI->second);
1313 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1314 /// the current basic block, add it to ValueMap now so that we'll get a
1316 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1317 // No need to export constants.
1318 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1320 // Already exported?
1321 if (FuncInfo.isExportedInst(V)) return;
1323 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1324 CopyValueToVirtualRegister(V, Reg);
1327 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1328 const BasicBlock *FromBB) {
1329 // The operands of the setcc have to be in this block. We don't know
1330 // how to export them from some other block.
1331 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1332 // Can export from current BB.
1333 if (VI->getParent() == FromBB)
1336 // Is already exported, noop.
1337 return FuncInfo.isExportedInst(V);
1340 // If this is an argument, we can export it if the BB is the entry block or
1341 // if it is already exported.
1342 if (isa<Argument>(V)) {
1343 if (FromBB == &FromBB->getParent()->getEntryBlock())
1346 // Otherwise, can only export this if it is already exported.
1347 return FuncInfo.isExportedInst(V);
1350 // Otherwise, constants can always be exported.
1354 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1355 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1356 const MachineBasicBlock *Dst) const {
1357 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1360 const BasicBlock *SrcBB = Src->getBasicBlock();
1361 const BasicBlock *DstBB = Dst->getBasicBlock();
1362 return BPI->getEdgeWeight(SrcBB, DstBB);
1365 void SelectionDAGBuilder::
1366 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1367 uint32_t Weight /* = 0 */) {
1369 Weight = getEdgeWeight(Src, Dst);
1370 Src->addSuccessor(Dst, Weight);
1374 static bool InBlock(const Value *V, const BasicBlock *BB) {
1375 if (const Instruction *I = dyn_cast<Instruction>(V))
1376 return I->getParent() == BB;
1380 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1381 /// This function emits a branch and is used at the leaves of an OR or an
1382 /// AND operator tree.
1385 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1386 MachineBasicBlock *TBB,
1387 MachineBasicBlock *FBB,
1388 MachineBasicBlock *CurBB,
1389 MachineBasicBlock *SwitchBB,
1392 const BasicBlock *BB = CurBB->getBasicBlock();
1394 // If the leaf of the tree is a comparison, merge the condition into
1396 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1397 // The operands of the cmp have to be in this block. We don't know
1398 // how to export them from some other block. If this is the first block
1399 // of the sequence, no exporting is needed.
1400 if (CurBB == SwitchBB ||
1401 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1402 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1403 ISD::CondCode Condition;
1404 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1405 Condition = getICmpCondCode(IC->getPredicate());
1406 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1407 Condition = getFCmpCondCode(FC->getPredicate());
1408 if (TM.Options.NoNaNsFPMath)
1409 Condition = getFCmpCodeWithoutNaN(Condition);
1411 Condition = ISD::SETEQ; // silence warning.
1412 llvm_unreachable("Unknown compare instruction");
1415 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1416 TBB, FBB, CurBB, TWeight, FWeight);
1417 SwitchCases.push_back(CB);
1422 // Create a CaseBlock record representing this branch.
1423 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1424 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1425 SwitchCases.push_back(CB);
1428 /// Scale down both weights to fit into uint32_t.
1429 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1430 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1431 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1432 NewTrue = NewTrue / Scale;
1433 NewFalse = NewFalse / Scale;
1436 /// FindMergedConditions - If Cond is an expression like
1437 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1438 MachineBasicBlock *TBB,
1439 MachineBasicBlock *FBB,
1440 MachineBasicBlock *CurBB,
1441 MachineBasicBlock *SwitchBB,
1442 unsigned Opc, uint32_t TWeight,
1444 // If this node is not part of the or/and tree, emit it as a branch.
1445 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1446 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1447 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1448 BOp->getParent() != CurBB->getBasicBlock() ||
1449 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1450 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1451 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1456 // Create TmpBB after CurBB.
1457 MachineFunction::iterator BBI = CurBB;
1458 MachineFunction &MF = DAG.getMachineFunction();
1459 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1460 CurBB->getParent()->insert(++BBI, TmpBB);
1462 if (Opc == Instruction::Or) {
1463 // Codegen X | Y as:
1472 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1473 // The requirement is that
1474 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1475 // = TrueProb for orignal BB.
1476 // Assuming the orignal weights are A and B, one choice is to set BB1's
1477 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1479 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1480 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1481 // TmpBB, but the math is more complicated.
1483 uint64_t NewTrueWeight = TWeight;
1484 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1485 ScaleWeights(NewTrueWeight, NewFalseWeight);
1486 // Emit the LHS condition.
1487 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1488 NewTrueWeight, NewFalseWeight);
1490 NewTrueWeight = TWeight;
1491 NewFalseWeight = 2 * (uint64_t)FWeight;
1492 ScaleWeights(NewTrueWeight, NewFalseWeight);
1493 // Emit the RHS condition into TmpBB.
1494 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1495 NewTrueWeight, NewFalseWeight);
1497 assert(Opc == Instruction::And && "Unknown merge op!");
1498 // Codegen X & Y as:
1506 // This requires creation of TmpBB after CurBB.
1508 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1509 // The requirement is that
1510 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1511 // = FalseProb for orignal BB.
1512 // Assuming the orignal weights are A and B, one choice is to set BB1's
1513 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1515 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1517 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1518 uint64_t NewFalseWeight = FWeight;
1519 ScaleWeights(NewTrueWeight, NewFalseWeight);
1520 // Emit the LHS condition.
1521 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1522 NewTrueWeight, NewFalseWeight);
1524 NewTrueWeight = 2 * (uint64_t)TWeight;
1525 NewFalseWeight = FWeight;
1526 ScaleWeights(NewTrueWeight, NewFalseWeight);
1527 // Emit the RHS condition into TmpBB.
1528 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1529 NewTrueWeight, NewFalseWeight);
1533 /// If the set of cases should be emitted as a series of branches, return true.
1534 /// If we should emit this as a bunch of and/or'd together conditions, return
1537 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1538 if (Cases.size() != 2) return true;
1540 // If this is two comparisons of the same values or'd or and'd together, they
1541 // will get folded into a single comparison, so don't emit two blocks.
1542 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1543 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1544 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1545 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1549 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1550 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1551 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1552 Cases[0].CC == Cases[1].CC &&
1553 isa<Constant>(Cases[0].CmpRHS) &&
1554 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1555 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1557 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1564 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1565 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1567 // Update machine-CFG edges.
1568 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1570 // Figure out which block is immediately after the current one.
1571 MachineBasicBlock *NextBlock = nullptr;
1572 MachineFunction::iterator BBI = BrMBB;
1573 if (++BBI != FuncInfo.MF->end())
1576 if (I.isUnconditional()) {
1577 // Update machine-CFG edges.
1578 BrMBB->addSuccessor(Succ0MBB);
1580 // If this is not a fall-through branch or optimizations are switched off,
1582 if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
1583 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1584 MVT::Other, getControlRoot(),
1585 DAG.getBasicBlock(Succ0MBB)));
1590 // If this condition is one of the special cases we handle, do special stuff
1592 const Value *CondVal = I.getCondition();
1593 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1595 // If this is a series of conditions that are or'd or and'd together, emit
1596 // this as a sequence of branches instead of setcc's with and/or operations.
1597 // As long as jumps are not expensive, this should improve performance.
1598 // For example, instead of something like:
1611 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1612 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1613 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1614 BOp->getOpcode() == Instruction::Or)) {
1615 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1616 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1617 getEdgeWeight(BrMBB, Succ1MBB));
1618 // If the compares in later blocks need to use values not currently
1619 // exported from this block, export them now. This block should always
1620 // be the first entry.
1621 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1623 // Allow some cases to be rejected.
1624 if (ShouldEmitAsBranches(SwitchCases)) {
1625 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1626 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1627 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1630 // Emit the branch for this block.
1631 visitSwitchCase(SwitchCases[0], BrMBB);
1632 SwitchCases.erase(SwitchCases.begin());
1636 // Okay, we decided not to do this, remove any inserted MBB's and clear
1638 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1639 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1641 SwitchCases.clear();
1645 // Create a CaseBlock record representing this branch.
1646 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1647 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1649 // Use visitSwitchCase to actually insert the fast branch sequence for this
1651 visitSwitchCase(CB, BrMBB);
1654 /// visitSwitchCase - Emits the necessary code to represent a single node in
1655 /// the binary search tree resulting from lowering a switch instruction.
1656 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1657 MachineBasicBlock *SwitchBB) {
1659 SDValue CondLHS = getValue(CB.CmpLHS);
1660 SDLoc dl = getCurSDLoc();
1662 // Build the setcc now.
1664 // Fold "(X == true)" to X and "(X == false)" to !X to
1665 // handle common cases produced by branch lowering.
1666 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1667 CB.CC == ISD::SETEQ)
1669 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1670 CB.CC == ISD::SETEQ) {
1671 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1672 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1674 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1676 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1678 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1679 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1681 SDValue CmpOp = getValue(CB.CmpMHS);
1682 EVT VT = CmpOp.getValueType();
1684 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1685 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1688 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1689 VT, CmpOp, DAG.getConstant(Low, VT));
1690 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1691 DAG.getConstant(High-Low, VT), ISD::SETULE);
1695 // Update successor info
1696 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1697 // TrueBB and FalseBB are always different unless the incoming IR is
1698 // degenerate. This only happens when running llc on weird IR.
1699 if (CB.TrueBB != CB.FalseBB)
1700 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1702 // Set NextBlock to be the MBB immediately after the current one, if any.
1703 // This is used to avoid emitting unnecessary branches to the next block.
1704 MachineBasicBlock *NextBlock = nullptr;
1705 MachineFunction::iterator BBI = SwitchBB;
1706 if (++BBI != FuncInfo.MF->end())
1709 // If the lhs block is the next block, invert the condition so that we can
1710 // fall through to the lhs instead of the rhs block.
1711 if (CB.TrueBB == NextBlock) {
1712 std::swap(CB.TrueBB, CB.FalseBB);
1713 SDValue True = DAG.getConstant(1, Cond.getValueType());
1714 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1717 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1718 MVT::Other, getControlRoot(), Cond,
1719 DAG.getBasicBlock(CB.TrueBB));
1721 // Insert the false branch. Do this even if it's a fall through branch,
1722 // this makes it easier to do DAG optimizations which require inverting
1723 // the branch condition.
1724 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1725 DAG.getBasicBlock(CB.FalseBB));
1727 DAG.setRoot(BrCond);
1730 /// visitJumpTable - Emit JumpTable node in the current MBB
1731 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1732 // Emit the code for the jump table
1733 assert(JT.Reg != -1U && "Should lower JT Header first!");
1734 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1735 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1737 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1738 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1739 MVT::Other, Index.getValue(1),
1741 DAG.setRoot(BrJumpTable);
1744 /// visitJumpTableHeader - This function emits necessary code to produce index
1745 /// in the JumpTable from switch case.
1746 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1747 JumpTableHeader &JTH,
1748 MachineBasicBlock *SwitchBB) {
1749 // Subtract the lowest switch case value from the value being switched on and
1750 // conditional branch to default mbb if the result is greater than the
1751 // difference between smallest and largest cases.
1752 SDValue SwitchOp = getValue(JTH.SValue);
1753 EVT VT = SwitchOp.getValueType();
1754 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1755 DAG.getConstant(JTH.First, VT));
1757 // The SDNode we just created, which holds the value being switched on minus
1758 // the smallest case value, needs to be copied to a virtual register so it
1759 // can be used as an index into the jump table in a subsequent basic block.
1760 // This value may be smaller or larger than the target's pointer type, and
1761 // therefore require extension or truncating.
1762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1763 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
1765 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1766 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1767 JumpTableReg, SwitchOp);
1768 JT.Reg = JumpTableReg;
1770 // Emit the range check for the jump table, and branch to the default block
1771 // for the switch statement if the value being switched on exceeds the largest
1772 // case in the switch.
1774 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1775 Sub.getValueType()),
1776 Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
1778 // Set NextBlock to be the MBB immediately after the current one, if any.
1779 // This is used to avoid emitting unnecessary branches to the next block.
1780 MachineBasicBlock *NextBlock = nullptr;
1781 MachineFunction::iterator BBI = SwitchBB;
1783 if (++BBI != FuncInfo.MF->end())
1786 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1787 MVT::Other, CopyTo, CMP,
1788 DAG.getBasicBlock(JT.Default));
1790 if (JT.MBB != NextBlock)
1791 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1792 DAG.getBasicBlock(JT.MBB));
1794 DAG.setRoot(BrCond);
1797 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1798 /// tail spliced into a stack protector check success bb.
1800 /// For a high level explanation of how this fits into the stack protector
1801 /// generation see the comment on the declaration of class
1802 /// StackProtectorDescriptor.
1803 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1804 MachineBasicBlock *ParentBB) {
1806 // First create the loads to the guard/stack slot for the comparison.
1807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1808 EVT PtrTy = TLI.getPointerTy();
1810 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1811 int FI = MFI->getStackProtectorIndex();
1813 const Value *IRGuard = SPD.getGuard();
1814 SDValue GuardPtr = getValue(IRGuard);
1815 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1818 TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1822 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1823 // guard value from the virtual register holding the value. Otherwise, emit a
1824 // volatile load to retrieve the stack guard value.
1825 unsigned GuardReg = SPD.getGuardReg();
1827 if (GuardReg && TLI.useLoadStackGuardNode())
1828 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1831 Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1832 GuardPtr, MachinePointerInfo(IRGuard, 0),
1833 true, false, false, Align);
1835 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1837 MachinePointerInfo::getFixedStack(FI),
1838 true, false, false, Align);
1840 // Perform the comparison via a subtract/getsetcc.
1841 EVT VT = Guard.getValueType();
1842 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1845 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1846 Sub.getValueType()),
1847 Sub, DAG.getConstant(0, VT), ISD::SETNE);
1849 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1850 // branch to failure MBB.
1851 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1852 MVT::Other, StackSlot.getOperand(0),
1853 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1854 // Otherwise branch to success MBB.
1855 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1857 DAG.getBasicBlock(SPD.getSuccessMBB()));
1862 /// Codegen the failure basic block for a stack protector check.
1864 /// A failure stack protector machine basic block consists simply of a call to
1865 /// __stack_chk_fail().
1867 /// For a high level explanation of how this fits into the stack protector
1868 /// generation see the comment on the declaration of class
1869 /// StackProtectorDescriptor.
1871 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1872 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1874 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1875 nullptr, 0, false, getCurSDLoc(), false, false).second;
1879 /// visitBitTestHeader - This function emits necessary code to produce value
1880 /// suitable for "bit tests"
1881 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1882 MachineBasicBlock *SwitchBB) {
1883 // Subtract the minimum value
1884 SDValue SwitchOp = getValue(B.SValue);
1885 EVT VT = SwitchOp.getValueType();
1886 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1887 DAG.getConstant(B.First, VT));
1890 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1892 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1893 Sub.getValueType()),
1894 Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
1896 // Determine the type of the test operands.
1897 bool UsePtrType = false;
1898 if (!TLI.isTypeLegal(VT))
1901 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1902 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1903 // Switch table case range are encoded into series of masks.
1904 // Just use pointer type, it's guaranteed to fit.
1910 VT = TLI.getPointerTy();
1911 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1914 B.RegVT = VT.getSimpleVT();
1915 B.Reg = FuncInfo.CreateReg(B.RegVT);
1916 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1919 // Set NextBlock to be the MBB immediately after the current one, if any.
1920 // This is used to avoid emitting unnecessary branches to the next block.
1921 MachineBasicBlock *NextBlock = nullptr;
1922 MachineFunction::iterator BBI = SwitchBB;
1923 if (++BBI != FuncInfo.MF->end())
1926 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1928 addSuccessorWithWeight(SwitchBB, B.Default);
1929 addSuccessorWithWeight(SwitchBB, MBB);
1931 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1932 MVT::Other, CopyTo, RangeCmp,
1933 DAG.getBasicBlock(B.Default));
1935 if (MBB != NextBlock)
1936 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1937 DAG.getBasicBlock(MBB));
1939 DAG.setRoot(BrRange);
1942 /// visitBitTestCase - this function produces one "bit test"
1943 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1944 MachineBasicBlock* NextMBB,
1945 uint32_t BranchWeightToNext,
1948 MachineBasicBlock *SwitchBB) {
1950 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1953 unsigned PopCount = CountPopulation_64(B.Mask);
1954 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1955 if (PopCount == 1) {
1956 // Testing for a single bit; just compare the shift count with what it
1957 // would need to be to shift a 1 bit in that position.
1959 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1960 DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
1961 } else if (PopCount == BB.Range) {
1962 // There is only one zero bit in the range, test for it directly.
1964 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1965 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), ISD::SETNE);
1967 // Make desired shift
1968 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1969 DAG.getConstant(1, VT), ShiftOp);
1971 // Emit bit tests and jumps
1972 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1973 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1974 Cmp = DAG.getSetCC(getCurSDLoc(),
1975 TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1976 DAG.getConstant(0, VT), ISD::SETNE);
1979 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1980 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1981 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1982 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1984 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1985 MVT::Other, getControlRoot(),
1986 Cmp, DAG.getBasicBlock(B.TargetBB));
1988 // Set NextBlock to be the MBB immediately after the current one, if any.
1989 // This is used to avoid emitting unnecessary branches to the next block.
1990 MachineBasicBlock *NextBlock = nullptr;
1991 MachineFunction::iterator BBI = SwitchBB;
1992 if (++BBI != FuncInfo.MF->end())
1995 if (NextMBB != NextBlock)
1996 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1997 DAG.getBasicBlock(NextMBB));
2002 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2003 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2005 // Retrieve successors.
2006 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2007 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2009 const Value *Callee(I.getCalledValue());
2010 const Function *Fn = dyn_cast<Function>(Callee);
2011 if (isa<InlineAsm>(Callee))
2013 else if (Fn && Fn->isIntrinsic()) {
2014 switch (Fn->getIntrinsicID()) {
2016 llvm_unreachable("Cannot invoke this intrinsic");
2017 case Intrinsic::donothing:
2018 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2020 case Intrinsic::experimental_patchpoint_void:
2021 case Intrinsic::experimental_patchpoint_i64:
2022 visitPatchpoint(&I, LandingPad);
2026 LowerCallTo(&I, getValue(Callee), false, LandingPad);
2028 // If the value of the invoke is used outside of its defining block, make it
2029 // available as a virtual register.
2030 CopyToExportRegsIfNeeded(&I);
2032 // Update successor info
2033 addSuccessorWithWeight(InvokeMBB, Return);
2034 addSuccessorWithWeight(InvokeMBB, LandingPad);
2036 // Drop into normal successor.
2037 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2038 MVT::Other, getControlRoot(),
2039 DAG.getBasicBlock(Return)));
2042 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2043 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2046 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2047 assert(FuncInfo.MBB->isLandingPad() &&
2048 "Call to landingpad not in landing pad!");
2050 MachineBasicBlock *MBB = FuncInfo.MBB;
2051 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2052 AddLandingPadInfo(LP, MMI, MBB);
2054 // If there aren't registers to copy the values into (e.g., during SjLj
2055 // exceptions), then don't bother to create these DAG nodes.
2056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2057 if (TLI.getExceptionPointerRegister() == 0 &&
2058 TLI.getExceptionSelectorRegister() == 0)
2061 SmallVector<EVT, 2> ValueVTs;
2062 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
2063 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2065 // Get the two live-in registers as SDValues. The physregs have already been
2066 // copied into virtual registers.
2068 Ops[0] = DAG.getZExtOrTrunc(
2069 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2070 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2071 getCurSDLoc(), ValueVTs[0]);
2072 Ops[1] = DAG.getZExtOrTrunc(
2073 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2074 FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2075 getCurSDLoc(), ValueVTs[1]);
2078 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2079 DAG.getVTList(ValueVTs), Ops);
2083 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2084 /// small case ranges).
2085 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2086 CaseRecVector& WorkList,
2088 MachineBasicBlock *Default,
2089 MachineBasicBlock *SwitchBB) {
2090 // Size is the number of Cases represented by this range.
2091 size_t Size = CR.Range.second - CR.Range.first;
2095 // Get the MachineFunction which holds the current MBB. This is used when
2096 // inserting any additional MBBs necessary to represent the switch.
2097 MachineFunction *CurMF = FuncInfo.MF;
2099 // Figure out which block is immediately after the current one.
2100 MachineBasicBlock *NextBlock = nullptr;
2101 MachineFunction::iterator BBI = CR.CaseBB;
2103 if (++BBI != FuncInfo.MF->end())
2106 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2107 // If any two of the cases has the same destination, and if one value
2108 // is the same as the other, but has one bit unset that the other has set,
2109 // use bit manipulation to do two compares at once. For example:
2110 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2111 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2112 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2113 if (Size == 2 && CR.CaseBB == SwitchBB) {
2114 Case &Small = *CR.Range.first;
2115 Case &Big = *(CR.Range.second-1);
2117 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2118 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2119 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2121 // Check that there is only one bit different.
2122 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2123 (SmallValue | BigValue) == BigValue) {
2124 // Isolate the common bit.
2125 APInt CommonBit = BigValue & ~SmallValue;
2126 assert((SmallValue | CommonBit) == BigValue &&
2127 CommonBit.countPopulation() == 1 && "Not a common bit?");
2129 SDValue CondLHS = getValue(SV);
2130 EVT VT = CondLHS.getValueType();
2131 SDLoc DL = getCurSDLoc();
2133 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2134 DAG.getConstant(CommonBit, VT));
2135 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2136 Or, DAG.getConstant(BigValue, VT),
2139 // Update successor info.
2140 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2141 addSuccessorWithWeight(SwitchBB, Small.BB,
2142 Small.ExtraWeight + Big.ExtraWeight);
2143 addSuccessorWithWeight(SwitchBB, Default,
2144 // The default destination is the first successor in IR.
2145 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2147 // Insert the true branch.
2148 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2149 getControlRoot(), Cond,
2150 DAG.getBasicBlock(Small.BB));
2152 // Insert the false branch.
2153 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2154 DAG.getBasicBlock(Default));
2156 DAG.setRoot(BrCond);
2162 // Order cases by weight so the most likely case will be checked first.
2163 uint32_t UnhandledWeights = 0;
2165 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2166 uint32_t IWeight = I->ExtraWeight;
2167 UnhandledWeights += IWeight;
2168 for (CaseItr J = CR.Range.first; J < I; ++J) {
2169 uint32_t JWeight = J->ExtraWeight;
2170 if (IWeight > JWeight)
2175 // Rearrange the case blocks so that the last one falls through if possible.
2176 Case &BackCase = *(CR.Range.second-1);
2178 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2179 // The last case block won't fall through into 'NextBlock' if we emit the
2180 // branches in this order. See if rearranging a case value would help.
2181 // We start at the bottom as it's the case with the least weight.
2182 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2183 if (I->BB == NextBlock) {
2184 std::swap(*I, BackCase);
2189 // Create a CaseBlock record representing a conditional branch to
2190 // the Case's target mbb if the value being switched on SV is equal
2192 MachineBasicBlock *CurBlock = CR.CaseBB;
2193 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2194 MachineBasicBlock *FallThrough;
2196 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2197 CurMF->insert(BBI, FallThrough);
2199 // Put SV in a virtual register to make it available from the new blocks.
2200 ExportFromCurrentBlock(SV);
2202 // If the last case doesn't match, go to the default block.
2203 FallThrough = Default;
2206 const Value *RHS, *LHS, *MHS;
2208 if (I->High == I->Low) {
2209 // This is just small small case range :) containing exactly 1 case
2211 LHS = SV; RHS = I->High; MHS = nullptr;
2214 LHS = I->Low; MHS = SV; RHS = I->High;
2217 // The false weight should be sum of all un-handled cases.
2218 UnhandledWeights -= I->ExtraWeight;
2219 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2221 /* trueweight */ I->ExtraWeight,
2222 /* falseweight */ UnhandledWeights);
2224 // If emitting the first comparison, just call visitSwitchCase to emit the
2225 // code into the current block. Otherwise, push the CaseBlock onto the
2226 // vector to be later processed by SDISel, and insert the node's MBB
2227 // before the next MBB.
2228 if (CurBlock == SwitchBB)
2229 visitSwitchCase(CB, SwitchBB);
2231 SwitchCases.push_back(CB);
2233 CurBlock = FallThrough;
2239 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2240 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2241 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
2244 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2245 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2246 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2247 return (LastExt - FirstExt + 1ULL);
2250 /// handleJTSwitchCase - Emit jumptable for current switch case range
2251 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2252 CaseRecVector &WorkList,
2254 MachineBasicBlock *Default,
2255 MachineBasicBlock *SwitchBB) {
2256 Case& FrontCase = *CR.Range.first;
2257 Case& BackCase = *(CR.Range.second-1);
2259 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2260 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2262 APInt TSize(First.getBitWidth(), 0);
2263 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2266 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2267 if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
2270 APInt Range = ComputeRange(First, Last);
2271 // The density is TSize / Range. Require at least 40%.
2272 // It should not be possible for IntTSize to saturate for sane code, but make
2273 // sure we handle Range saturation correctly.
2274 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2275 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2276 if (IntTSize * 10 < IntRange * 4)
2279 DEBUG(dbgs() << "Lowering jump table\n"
2280 << "First entry: " << First << ". Last entry: " << Last << '\n'
2281 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2283 // Get the MachineFunction which holds the current MBB. This is used when
2284 // inserting any additional MBBs necessary to represent the switch.
2285 MachineFunction *CurMF = FuncInfo.MF;
2287 // Figure out which block is immediately after the current one.
2288 MachineFunction::iterator BBI = CR.CaseBB;
2291 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2293 // Create a new basic block to hold the code for loading the address
2294 // of the jump table, and jumping to it. Update successor information;
2295 // we will either branch to the default case for the switch, or the jump
2297 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2298 CurMF->insert(BBI, JumpTableBB);
2300 addSuccessorWithWeight(CR.CaseBB, Default);
2301 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2303 // Build a vector of destination BBs, corresponding to each target
2304 // of the jump table. If the value of the jump table slot corresponds to
2305 // a case statement, push the case's BB onto the vector, otherwise, push
2307 std::vector<MachineBasicBlock*> DestBBs;
2309 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2310 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2311 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2313 if (Low.sle(TEI) && TEI.sle(High)) {
2314 DestBBs.push_back(I->BB);
2318 DestBBs.push_back(Default);
2322 // Calculate weight for each unique destination in CR.
2323 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2325 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2326 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2327 DestWeights.find(I->BB);
2328 if (Itr != DestWeights.end())
2329 Itr->second += I->ExtraWeight;
2331 DestWeights[I->BB] = I->ExtraWeight;
2334 // Update successor info. Add one edge to each unique successor.
2335 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2336 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2337 E = DestBBs.end(); I != E; ++I) {
2338 if (!SuccsHandled[(*I)->getNumber()]) {
2339 SuccsHandled[(*I)->getNumber()] = true;
2340 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2341 DestWeights.find(*I);
2342 addSuccessorWithWeight(JumpTableBB, *I,
2343 Itr != DestWeights.end() ? Itr->second : 0);
2347 // Create a jump table index for this jump table.
2348 unsigned JTEncoding = TLI.getJumpTableEncoding();
2349 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2350 ->createJumpTableIndex(DestBBs);
2352 // Set the jump table information so that we can codegen it as a second
2353 // MachineBasicBlock
2354 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2355 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2356 if (CR.CaseBB == SwitchBB)
2357 visitJumpTableHeader(JT, JTH, SwitchBB);
2359 JTCases.push_back(JumpTableBlock(JTH, JT));
2363 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2365 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2366 CaseRecVector& WorkList,
2368 MachineBasicBlock* SwitchBB) {
2369 // Get the MachineFunction which holds the current MBB. This is used when
2370 // inserting any additional MBBs necessary to represent the switch.
2371 MachineFunction *CurMF = FuncInfo.MF;
2373 // Figure out which block is immediately after the current one.
2374 MachineFunction::iterator BBI = CR.CaseBB;
2377 Case& FrontCase = *CR.Range.first;
2378 Case& BackCase = *(CR.Range.second-1);
2379 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2381 // Size is the number of Cases represented by this range.
2382 unsigned Size = CR.Range.second - CR.Range.first;
2384 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2385 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2387 CaseItr Pivot = CR.Range.first + Size/2;
2389 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2390 // (heuristically) allow us to emit JumpTable's later.
2391 APInt TSize(First.getBitWidth(), 0);
2392 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2396 APInt LSize = FrontCase.size();
2397 APInt RSize = TSize-LSize;
2398 DEBUG(dbgs() << "Selecting best pivot: \n"
2399 << "First: " << First << ", Last: " << Last <<'\n'
2400 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2401 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2403 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2404 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2405 APInt Range = ComputeRange(LEnd, RBegin);
2406 assert((Range - 2ULL).isNonNegative() &&
2407 "Invalid case distance");
2408 // Use volatile double here to avoid excess precision issues on some hosts,
2409 // e.g. that use 80-bit X87 registers.
2410 volatile double LDensity =
2411 (double)LSize.roundToDouble() /
2412 (LEnd - First + 1ULL).roundToDouble();
2413 volatile double RDensity =
2414 (double)RSize.roundToDouble() /
2415 (Last - RBegin + 1ULL).roundToDouble();
2416 volatile double Metric = Range.logBase2()*(LDensity+RDensity);
2417 // Should always split in some non-trivial place
2418 DEBUG(dbgs() <<"=>Step\n"
2419 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2420 << "LDensity: " << LDensity
2421 << ", RDensity: " << RDensity << '\n'
2422 << "Metric: " << Metric << '\n');
2423 if (FMetric < Metric) {
2426 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2434 if (areJTsAllowed(TLI)) {
2435 // If our case is dense we *really* should handle it earlier!
2436 assert((FMetric > 0) && "Should handle dense range earlier!");
2438 Pivot = CR.Range.first + Size/2;
2441 CaseRange LHSR(CR.Range.first, Pivot);
2442 CaseRange RHSR(Pivot, CR.Range.second);
2443 const Constant *C = Pivot->Low;
2444 MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
2446 // We know that we branch to the LHS if the Value being switched on is
2447 // less than the Pivot value, C. We use this to optimize our binary
2448 // tree a bit, by recognizing that if SV is greater than or equal to the
2449 // LHS's Case Value, and that Case Value is exactly one less than the
2450 // Pivot's Value, then we can branch directly to the LHS's Target,
2451 // rather than creating a leaf node for it.
2452 if ((LHSR.second - LHSR.first) == 1 &&
2453 LHSR.first->High == CR.GE &&
2454 cast<ConstantInt>(C)->getValue() ==
2455 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2456 TrueBB = LHSR.first->BB;
2458 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2459 CurMF->insert(BBI, TrueBB);
2460 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2462 // Put SV in a virtual register to make it available from the new blocks.
2463 ExportFromCurrentBlock(SV);
2466 // Similar to the optimization above, if the Value being switched on is
2467 // known to be less than the Constant CR.LT, and the current Case Value
2468 // is CR.LT - 1, then we can branch directly to the target block for
2469 // the current Case Value, rather than emitting a RHS leaf node for it.
2470 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2471 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2472 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2473 FalseBB = RHSR.first->BB;
2475 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2476 CurMF->insert(BBI, FalseBB);
2477 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2479 // Put SV in a virtual register to make it available from the new blocks.
2480 ExportFromCurrentBlock(SV);
2483 // Create a CaseBlock record representing a conditional branch to
2484 // the LHS node if the value being switched on SV is less than C.
2485 // Otherwise, branch to LHS.
2486 CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
2488 if (CR.CaseBB == SwitchBB)
2489 visitSwitchCase(CB, SwitchBB);
2491 SwitchCases.push_back(CB);
2496 /// handleBitTestsSwitchCase - if current case range has few destination and
2497 /// range span less, than machine word bitwidth, encode case range into series
2498 /// of masks and emit bit tests with these masks.
2499 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2500 CaseRecVector& WorkList,
2502 MachineBasicBlock* Default,
2503 MachineBasicBlock* SwitchBB) {
2504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2505 EVT PTy = TLI.getPointerTy();
2506 unsigned IntPtrBits = PTy.getSizeInBits();
2508 Case& FrontCase = *CR.Range.first;
2509 Case& BackCase = *(CR.Range.second-1);
2511 // Get the MachineFunction which holds the current MBB. This is used when
2512 // inserting any additional MBBs necessary to represent the switch.
2513 MachineFunction *CurMF = FuncInfo.MF;
2515 // If target does not have legal shift left, do not emit bit tests at all.
2516 if (!TLI.isOperationLegal(ISD::SHL, PTy))
2520 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2521 // Single case counts one, case range - two.
2522 numCmps += (I->Low == I->High ? 1 : 2);
2525 // Count unique destinations
2526 SmallSet<MachineBasicBlock*, 4> Dests;
2527 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2528 Dests.insert(I->BB);
2529 if (Dests.size() > 3)
2530 // Don't bother the code below, if there are too much unique destinations
2533 DEBUG(dbgs() << "Total number of unique destinations: "
2534 << Dests.size() << '\n'
2535 << "Total number of comparisons: " << numCmps << '\n');
2537 // Compute span of values.
2538 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2539 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2540 APInt cmpRange = maxValue - minValue;
2542 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2543 << "Low bound: " << minValue << '\n'
2544 << "High bound: " << maxValue << '\n');
2546 if (cmpRange.uge(IntPtrBits) ||
2547 (!(Dests.size() == 1 && numCmps >= 3) &&
2548 !(Dests.size() == 2 && numCmps >= 5) &&
2549 !(Dests.size() >= 3 && numCmps >= 6)))
2552 DEBUG(dbgs() << "Emitting bit tests\n");
2553 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2555 // Optimize the case where all the case values fit in a
2556 // word without having to subtract minValue. In this case,
2557 // we can optimize away the subtraction.
2558 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2559 cmpRange = maxValue;
2561 lowBound = minValue;
2564 CaseBitsVector CasesBits;
2565 unsigned i, count = 0;
2567 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2568 MachineBasicBlock* Dest = I->BB;
2569 for (i = 0; i < count; ++i)
2570 if (Dest == CasesBits[i].BB)
2574 assert((count < 3) && "Too much destinations to test!");
2575 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2579 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2580 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2582 uint64_t lo = (lowValue - lowBound).getZExtValue();
2583 uint64_t hi = (highValue - lowBound).getZExtValue();
2584 CasesBits[i].ExtraWeight += I->ExtraWeight;
2586 for (uint64_t j = lo; j <= hi; j++) {
2587 CasesBits[i].Mask |= 1ULL << j;
2588 CasesBits[i].Bits++;
2592 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2596 // Figure out which block is immediately after the current one.
2597 MachineFunction::iterator BBI = CR.CaseBB;
2600 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2602 DEBUG(dbgs() << "Cases:\n");
2603 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2604 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2605 << ", Bits: " << CasesBits[i].Bits
2606 << ", BB: " << CasesBits[i].BB << '\n');
2608 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2609 CurMF->insert(BBI, CaseBB);
2610 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2612 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2614 // Put SV in a virtual register to make it available from the new blocks.
2615 ExportFromCurrentBlock(SV);
2618 BitTestBlock BTB(lowBound, cmpRange, SV,
2619 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2620 CR.CaseBB, Default, std::move(BTC));
2622 if (CR.CaseBB == SwitchBB)
2623 visitBitTestHeader(BTB, SwitchBB);
2625 BitTestCases.push_back(std::move(BTB));
2630 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2631 void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2632 const SwitchInst& SI) {
2633 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2634 // Start with "simple" cases.
2635 for (SwitchInst::ConstCaseIt i : SI.cases()) {
2636 const BasicBlock *SuccBB = i.getCaseSuccessor();
2637 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2639 uint32_t ExtraWeight =
2640 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2642 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2643 SMBB, ExtraWeight));
2645 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2647 // Merge case into clusters
2648 if (Cases.size() >= 2)
2649 // Must recompute end() each iteration because it may be
2650 // invalidated by erase if we hold on to it
2651 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
2652 J != Cases.end(); ) {
2653 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2654 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2655 MachineBasicBlock* nextBB = J->BB;
2656 MachineBasicBlock* currentBB = I->BB;
2658 // If the two neighboring cases go to the same destination, merge them
2659 // into a single case.
2660 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2662 I->ExtraWeight += J->ExtraWeight;
2671 for (auto &I : Cases)
2672 // A range counts double, since it requires two compares.
2673 numCmps += I.Low != I.High ? 2 : 1;
2675 dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2676 << ". Total compares: " << numCmps << '\n';
2680 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2681 MachineBasicBlock *Last) {
2683 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2684 if (JTCases[i].first.HeaderBB == First)
2685 JTCases[i].first.HeaderBB = Last;
2687 // Update BitTestCases.
2688 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2689 if (BitTestCases[i].Parent == First)
2690 BitTestCases[i].Parent = Last;
2693 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2694 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2696 // Figure out which block is immediately after the current one.
2697 MachineBasicBlock *NextBlock = nullptr;
2698 if (SwitchMBB + 1 != FuncInfo.MF->end())
2699 NextBlock = SwitchMBB + 1;
2701 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2703 // If there is only the default destination, branch to it if it is not the
2704 // next basic block. Otherwise, just fall through.
2705 if (!SI.getNumCases()) {
2706 // Update machine-CFG edges.
2707 SwitchMBB->addSuccessor(Default);
2709 // If this is not a fall-through branch, emit the branch.
2710 if (Default != NextBlock)
2711 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2712 MVT::Other, getControlRoot(),
2713 DAG.getBasicBlock(Default)));
2718 // If there are any non-default case statements, create a vector of Cases
2719 // representing each one, and sort the vector so that we can efficiently
2720 // create a binary search tree from them.
2722 Clusterify(Cases, SI);
2724 // Get the Value to be switched on and default basic blocks, which will be
2725 // inserted into CaseBlock records, representing basic blocks in the binary
2727 const Value *SV = SI.getCondition();
2729 // Push the initial CaseRec onto the worklist
2730 CaseRecVector WorkList;
2731 WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
2732 CaseRange(Cases.begin(),Cases.end())));
2734 while (!WorkList.empty()) {
2735 // Grab a record representing a case range to process off the worklist
2736 CaseRec CR = WorkList.back();
2737 WorkList.pop_back();
2739 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2742 // If the range has few cases (two or less) emit a series of specific
2744 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2747 // If the switch has more than N blocks, and is at least 40% dense, and the
2748 // target supports indirect branches, then emit a jump table rather than
2749 // lowering the switch to a binary tree of conditional branches.
2750 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2751 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2754 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2755 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2756 handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
2760 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2761 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2763 // Update machine-CFG edges with unique successors.
2764 SmallSet<BasicBlock*, 32> Done;
2765 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2766 BasicBlock *BB = I.getSuccessor(i);
2767 bool Inserted = Done.insert(BB).second;
2771 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2772 addSuccessorWithWeight(IndirectBrMBB, Succ);
2775 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2776 MVT::Other, getControlRoot(),
2777 getValue(I.getAddress())));
2780 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2781 if (DAG.getTarget().Options.TrapUnreachable)
2782 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2785 void SelectionDAGBuilder::visitFSub(const User &I) {
2786 // -0.0 - X --> fneg
2787 Type *Ty = I.getType();
2788 if (isa<Constant>(I.getOperand(0)) &&
2789 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2790 SDValue Op2 = getValue(I.getOperand(1));
2791 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2792 Op2.getValueType(), Op2));
2796 visitBinary(I, ISD::FSUB);
2799 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2800 SDValue Op1 = getValue(I.getOperand(0));
2801 SDValue Op2 = getValue(I.getOperand(1));
2806 if (const OverflowingBinaryOperator *OFBinOp =
2807 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2808 nuw = OFBinOp->hasNoUnsignedWrap();
2809 nsw = OFBinOp->hasNoSignedWrap();
2811 if (const PossiblyExactOperator *ExactOp =
2812 dyn_cast<const PossiblyExactOperator>(&I))
2813 exact = ExactOp->isExact();
2815 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2816 Op1, Op2, nuw, nsw, exact);
2817 setValue(&I, BinNodeValue);
2820 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2821 SDValue Op1 = getValue(I.getOperand(0));
2822 SDValue Op2 = getValue(I.getOperand(1));
2825 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2827 // Coerce the shift amount to the right type if we can.
2828 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2829 unsigned ShiftSize = ShiftTy.getSizeInBits();
2830 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2831 SDLoc DL = getCurSDLoc();
2833 // If the operand is smaller than the shift count type, promote it.
2834 if (ShiftSize > Op2Size)
2835 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2837 // If the operand is larger than the shift count type but the shift
2838 // count type has enough bits to represent any shift value, truncate
2839 // it now. This is a common case and it exposes the truncate to
2840 // optimization early.
2841 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2842 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2843 // Otherwise we'll need to temporarily settle for some other convenient
2844 // type. Type legalization will make adjustments once the shiftee is split.
2846 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2853 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2855 if (const OverflowingBinaryOperator *OFBinOp =
2856 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2857 nuw = OFBinOp->hasNoUnsignedWrap();
2858 nsw = OFBinOp->hasNoSignedWrap();
2860 if (const PossiblyExactOperator *ExactOp =
2861 dyn_cast<const PossiblyExactOperator>(&I))
2862 exact = ExactOp->isExact();
2865 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2870 void SelectionDAGBuilder::visitSDiv(const User &I) {
2871 SDValue Op1 = getValue(I.getOperand(0));
2872 SDValue Op2 = getValue(I.getOperand(1));
2874 // Turn exact SDivs into multiplications.
2875 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2877 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2878 !isa<ConstantSDNode>(Op1) &&
2879 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2880 setValue(&I, DAG.getTargetLoweringInfo()
2881 .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
2883 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2887 void SelectionDAGBuilder::visitICmp(const User &I) {
2888 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2889 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2890 predicate = IC->getPredicate();
2891 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2892 predicate = ICmpInst::Predicate(IC->getPredicate());
2893 SDValue Op1 = getValue(I.getOperand(0));
2894 SDValue Op2 = getValue(I.getOperand(1));
2895 ISD::CondCode Opcode = getICmpCondCode(predicate);
2897 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2898 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2901 void SelectionDAGBuilder::visitFCmp(const User &I) {
2902 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2903 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2904 predicate = FC->getPredicate();
2905 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2906 predicate = FCmpInst::Predicate(FC->getPredicate());
2907 SDValue Op1 = getValue(I.getOperand(0));
2908 SDValue Op2 = getValue(I.getOperand(1));
2909 ISD::CondCode Condition = getFCmpCondCode(predicate);
2910 if (TM.Options.NoNaNsFPMath)
2911 Condition = getFCmpCodeWithoutNaN(Condition);
2912 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2913 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2916 void SelectionDAGBuilder::visitSelect(const User &I) {
2917 SmallVector<EVT, 4> ValueVTs;
2918 ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
2919 unsigned NumValues = ValueVTs.size();
2920 if (NumValues == 0) return;
2922 SmallVector<SDValue, 4> Values(NumValues);
2923 SDValue Cond = getValue(I.getOperand(0));
2924 SDValue TrueVal = getValue(I.getOperand(1));
2925 SDValue FalseVal = getValue(I.getOperand(2));
2926 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2927 ISD::VSELECT : ISD::SELECT;
2929 for (unsigned i = 0; i != NumValues; ++i)
2930 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2931 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2933 SDValue(TrueVal.getNode(),
2934 TrueVal.getResNo() + i),
2935 SDValue(FalseVal.getNode(),
2936 FalseVal.getResNo() + i));
2938 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2939 DAG.getVTList(ValueVTs), Values));
2942 void SelectionDAGBuilder::visitTrunc(const User &I) {
2943 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2944 SDValue N = getValue(I.getOperand(0));
2945 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2946 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2949 void SelectionDAGBuilder::visitZExt(const User &I) {
2950 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2951 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2952 SDValue N = getValue(I.getOperand(0));
2953 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2954 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2957 void SelectionDAGBuilder::visitSExt(const User &I) {
2958 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2959 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2960 SDValue N = getValue(I.getOperand(0));
2961 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2962 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2965 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2966 // FPTrunc is never a no-op cast, no need to check
2967 SDValue N = getValue(I.getOperand(0));
2968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2969 EVT DestVT = TLI.getValueType(I.getType());
2970 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
2971 DAG.getTargetConstant(0, TLI.getPointerTy())));
2974 void SelectionDAGBuilder::visitFPExt(const User &I) {
2975 // FPExt is never a no-op cast, no need to check
2976 SDValue N = getValue(I.getOperand(0));
2977 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2978 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2981 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2982 // FPToUI is never a no-op cast, no need to check
2983 SDValue N = getValue(I.getOperand(0));
2984 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2985 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2988 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2989 // FPToSI is never a no-op cast, no need to check
2990 SDValue N = getValue(I.getOperand(0));
2991 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2992 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2995 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2996 // UIToFP is never a no-op cast, no need to check
2997 SDValue N = getValue(I.getOperand(0));
2998 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2999 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3002 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3003 // SIToFP is never a no-op cast, no need to check
3004 SDValue N = getValue(I.getOperand(0));
3005 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3006 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3009 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3010 // What to do depends on the size of the integer and the size of the pointer.
3011 // We can either truncate, zero extend, or no-op, accordingly.
3012 SDValue N = getValue(I.getOperand(0));
3013 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3014 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3017 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3018 // What to do depends on the size of the integer and the size of the pointer.
3019 // We can either truncate, zero extend, or no-op, accordingly.
3020 SDValue N = getValue(I.getOperand(0));
3021 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3022 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3025 void SelectionDAGBuilder::visitBitCast(const User &I) {
3026 SDValue N = getValue(I.getOperand(0));
3027 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3029 // BitCast assures us that source and destination are the same size so this is
3030 // either a BITCAST or a no-op.
3031 if (DestVT != N.getValueType())
3032 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
3033 DestVT, N)); // convert types.
3034 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3035 // might fold any kind of constant expression to an integer constant and that
3036 // is not what we are looking for. Only regcognize a bitcast of a genuine
3037 // constant integer as an opaque constant.
3038 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3039 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3042 setValue(&I, N); // noop cast.
3045 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3046 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3047 const Value *SV = I.getOperand(0);
3048 SDValue N = getValue(SV);
3049 EVT DestVT = TLI.getValueType(I.getType());
3051 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3052 unsigned DestAS = I.getType()->getPointerAddressSpace();
3054 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3055 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3060 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3061 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3062 SDValue InVec = getValue(I.getOperand(0));
3063 SDValue InVal = getValue(I.getOperand(1));
3064 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3065 getCurSDLoc(), TLI.getVectorIdxTy());
3066 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3067 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
3070 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3071 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3072 SDValue InVec = getValue(I.getOperand(0));
3073 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3074 getCurSDLoc(), TLI.getVectorIdxTy());
3075 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3076 TLI.getValueType(I.getType()), InVec, InIdx));
3079 // Utility for visitShuffleVector - Return true if every element in Mask,
3080 // beginning from position Pos and ending in Pos+Size, falls within the
3081 // specified sequential range [L, L+Pos). or is undef.
3082 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
3083 unsigned Pos, unsigned Size, int Low) {
3084 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3085 if (Mask[i] >= 0 && Mask[i] != Low)
3090 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3091 SDValue Src1 = getValue(I.getOperand(0));
3092 SDValue Src2 = getValue(I.getOperand(1));
3094 SmallVector<int, 8> Mask;
3095 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3096 unsigned MaskNumElts = Mask.size();
3098 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3099 EVT VT = TLI.getValueType(I.getType());
3100 EVT SrcVT = Src1.getValueType();
3101 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3103 if (SrcNumElts == MaskNumElts) {
3104 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3109 // Normalize the shuffle vector since mask and vector length don't match.
3110 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3111 // Mask is longer than the source vectors and is a multiple of the source
3112 // vectors. We can use concatenate vector to make the mask and vectors
3114 if (SrcNumElts*2 == MaskNumElts) {
3115 // First check for Src1 in low and Src2 in high
3116 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3117 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3118 // The shuffle is concatenating two vectors together.
3119 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3123 // Then check for Src2 in low and Src1 in high
3124 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3125 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3126 // The shuffle is concatenating two vectors together.
3127 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3133 // Pad both vectors with undefs to make them the same length as the mask.
3134 unsigned NumConcat = MaskNumElts / SrcNumElts;
3135 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3136 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3137 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3139 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3140 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3144 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3145 getCurSDLoc(), VT, MOps1);
3146 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3147 getCurSDLoc(), VT, MOps2);
3149 // Readjust mask for new input vector length.
3150 SmallVector<int, 8> MappedOps;
3151 for (unsigned i = 0; i != MaskNumElts; ++i) {
3153 if (Idx >= (int)SrcNumElts)
3154 Idx -= SrcNumElts - MaskNumElts;
3155 MappedOps.push_back(Idx);
3158 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3163 if (SrcNumElts > MaskNumElts) {
3164 // Analyze the access pattern of the vector to see if we can extract
3165 // two subvectors and do the shuffle. The analysis is done by calculating
3166 // the range of elements the mask access on both vectors.
3167 int MinRange[2] = { static_cast<int>(SrcNumElts),
3168 static_cast<int>(SrcNumElts)};
3169 int MaxRange[2] = {-1, -1};
3171 for (unsigned i = 0; i != MaskNumElts; ++i) {
3177 if (Idx >= (int)SrcNumElts) {
3181 if (Idx > MaxRange[Input])
3182 MaxRange[Input] = Idx;
3183 if (Idx < MinRange[Input])
3184 MinRange[Input] = Idx;
3187 // Check if the access is smaller than the vector size and can we find
3188 // a reasonable extract index.
3189 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3191 int StartIdx[2]; // StartIdx to extract from
3192 for (unsigned Input = 0; Input < 2; ++Input) {
3193 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3194 RangeUse[Input] = 0; // Unused
3195 StartIdx[Input] = 0;
3199 // Find a good start index that is a multiple of the mask length. Then
3200 // see if the rest of the elements are in range.
3201 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3202 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3203 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3204 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3207 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3208 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3211 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3212 // Extract appropriate subvector and generate a vector shuffle
3213 for (unsigned Input = 0; Input < 2; ++Input) {
3214 SDValue &Src = Input == 0 ? Src1 : Src2;
3215 if (RangeUse[Input] == 0)
3216 Src = DAG.getUNDEF(VT);
3219 ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
3220 DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
3223 // Calculate new mask.
3224 SmallVector<int, 8> MappedOps;
3225 for (unsigned i = 0; i != MaskNumElts; ++i) {
3228 if (Idx < (int)SrcNumElts)
3231 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3233 MappedOps.push_back(Idx);
3236 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3242 // We can't use either concat vectors or extract subvectors so fall back to
3243 // replacing the shuffle with extract and build vector.
3244 // to insert and build vector.
3245 EVT EltVT = VT.getVectorElementType();
3246 EVT IdxVT = TLI.getVectorIdxTy();
3247 SmallVector<SDValue,8> Ops;
3248 for (unsigned i = 0; i != MaskNumElts; ++i) {
3253 Res = DAG.getUNDEF(EltVT);
3255 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3256 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3258 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3259 EltVT, Src, DAG.getConstant(Idx, IdxVT));
3265 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
3268 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3269 const Value *Op0 = I.getOperand(0);
3270 const Value *Op1 = I.getOperand(1);
3271 Type *AggTy = I.getType();
3272 Type *ValTy = Op1->getType();
3273 bool IntoUndef = isa<UndefValue>(Op0);
3274 bool FromUndef = isa<UndefValue>(Op1);
3276 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3278 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3279 SmallVector<EVT, 4> AggValueVTs;
3280 ComputeValueVTs(TLI, AggTy, AggValueVTs);
3281 SmallVector<EVT, 4> ValValueVTs;
3282 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3284 unsigned NumAggValues = AggValueVTs.size();
3285 unsigned NumValValues = ValValueVTs.size();
3286 SmallVector<SDValue, 4> Values(NumAggValues);
3288 // Ignore an insertvalue that produces an empty object
3289 if (!NumAggValues) {
3290 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3294 SDValue Agg = getValue(Op0);
3296 // Copy the beginning value(s) from the original aggregate.
3297 for (; i != LinearIndex; ++i)
3298 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3299 SDValue(Agg.getNode(), Agg.getResNo() + i);
3300 // Copy values from the inserted value(s).
3302 SDValue Val = getValue(Op1);
3303 for (; i != LinearIndex + NumValValues; ++i)
3304 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3305 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3307 // Copy remaining value(s) from the original aggregate.
3308 for (; i != NumAggValues; ++i)
3309 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3310 SDValue(Agg.getNode(), Agg.getResNo() + i);
3312 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3313 DAG.getVTList(AggValueVTs), Values));
3316 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3317 const Value *Op0 = I.getOperand(0);
3318 Type *AggTy = Op0->getType();
3319 Type *ValTy = I.getType();
3320 bool OutOfUndef = isa<UndefValue>(Op0);
3322 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3324 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3325 SmallVector<EVT, 4> ValValueVTs;
3326 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3328 unsigned NumValValues = ValValueVTs.size();
3330 // Ignore a extractvalue that produces an empty object
3331 if (!NumValValues) {
3332 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3336 SmallVector<SDValue, 4> Values(NumValValues);
3338 SDValue Agg = getValue(Op0);
3339 // Copy out the selected value(s).
3340 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3341 Values[i - LinearIndex] =
3343 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3344 SDValue(Agg.getNode(), Agg.getResNo() + i);
3346 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3347 DAG.getVTList(ValValueVTs), Values));
3350 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3351 Value *Op0 = I.getOperand(0);
3352 // Note that the pointer operand may be a vector of pointers. Take the scalar
3353 // element which holds a pointer.
3354 Type *Ty = Op0->getType()->getScalarType();
3355 unsigned AS = Ty->getPointerAddressSpace();
3356 SDValue N = getValue(Op0);
3358 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3360 const Value *Idx = *OI;
3361 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3362 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3365 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3366 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3367 DAG.getConstant(Offset, N.getValueType()));
3370 Ty = StTy->getElementType(Field);
3372 Ty = cast<SequentialType>(Ty)->getElementType();
3374 // If this is a constant subscript, handle it quickly.
3375 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3376 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3377 if (CI->isZero()) continue;
3379 DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3381 EVT PTy = TLI.getPointerTy(AS);
3382 unsigned PtrBits = PTy.getSizeInBits();
3384 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3385 DAG.getConstant(Offs, MVT::i64));
3387 OffsVal = DAG.getConstant(Offs, PTy);
3389 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3394 // N = N + Idx * ElementSize;
3396 APInt(TLI.getPointerSizeInBits(AS), DL->getTypeAllocSize(Ty));
3397 SDValue IdxN = getValue(Idx);
3399 // If the index is smaller or larger than intptr_t, truncate or extend
3401 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3403 // If this is a multiply by a power of two, turn it into a shl
3404 // immediately. This is a very common case.
3405 if (ElementSize != 1) {
3406 if (ElementSize.isPowerOf2()) {
3407 unsigned Amt = ElementSize.logBase2();
3408 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3409 N.getValueType(), IdxN,
3410 DAG.getConstant(Amt, IdxN.getValueType()));
3412 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3413 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3414 N.getValueType(), IdxN, Scale);
3418 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3419 N.getValueType(), N, IdxN);
3426 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3427 // If this is a fixed sized alloca in the entry block of the function,
3428 // allocate it statically on the stack.
3429 if (FuncInfo.StaticAllocaMap.count(&I))
3430 return; // getValue will auto-populate this.
3432 Type *Ty = I.getAllocatedType();
3433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3434 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
3436 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
3439 SDValue AllocSize = getValue(I.getArraySize());
3441 EVT IntPtr = TLI.getPointerTy();
3442 if (AllocSize.getValueType() != IntPtr)
3443 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3445 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3447 DAG.getConstant(TySize, IntPtr));
3449 // Handle alignment. If the requested alignment is less than or equal to
3450 // the stack alignment, ignore it. If the size is greater than or equal to
3451 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3452 unsigned StackAlign =
3453 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3454 if (Align <= StackAlign)
3457 // Round the size of the allocation up to the stack alignment size
3458 // by add SA-1 to the size.
3459 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3460 AllocSize.getValueType(), AllocSize,
3461 DAG.getIntPtrConstant(StackAlign-1));
3463 // Mask out the low bits for alignment purposes.
3464 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3465 AllocSize.getValueType(), AllocSize,
3466 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3468 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3469 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3470 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
3472 DAG.setRoot(DSA.getValue(1));
3474 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3477 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3479 return visitAtomicLoad(I);
3481 const Value *SV = I.getOperand(0);
3482 SDValue Ptr = getValue(SV);
3484 Type *Ty = I.getType();
3486 bool isVolatile = I.isVolatile();
3487 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3488 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3489 unsigned Alignment = I.getAlignment();
3492 I.getAAMetadata(AAInfo);
3493 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3495 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3496 SmallVector<EVT, 4> ValueVTs;
3497 SmallVector<uint64_t, 4> Offsets;
3498 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3499 unsigned NumValues = ValueVTs.size();
3504 bool ConstantMemory = false;
3505 if (isVolatile || NumValues > MaxParallelChains)
3506 // Serialize volatile loads with other side effects.
3508 else if (AA->pointsToConstantMemory(
3509 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
3510 // Do not serialize (non-volatile) loads of constant memory with anything.
3511 Root = DAG.getEntryNode();
3512 ConstantMemory = true;
3514 // Do not serialize non-volatile loads against each other.
3515 Root = DAG.getRoot();
3519 Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3521 SmallVector<SDValue, 4> Values(NumValues);
3522 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3524 EVT PtrVT = Ptr.getValueType();
3525 unsigned ChainI = 0;
3526 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3527 // Serializing loads here may result in excessive register pressure, and
3528 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3529 // could recover a bit by hoisting nodes upward in the chain by recognizing
3530 // they are side-effect free or do not alias. The optimizer should really
3531 // avoid this case by converting large object/array copies to llvm.memcpy
3532 // (MaxParallelChains should always remain as failsafe).
3533 if (ChainI == MaxParallelChains) {
3534 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3535 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3536 makeArrayRef(Chains.data(), ChainI));
3540 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3542 DAG.getConstant(Offsets[i], PtrVT));
3543 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3544 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3545 isNonTemporal, isInvariant, Alignment, AAInfo,
3549 Chains[ChainI] = L.getValue(1);
3552 if (!ConstantMemory) {
3553 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3554 makeArrayRef(Chains.data(), ChainI));
3558 PendingLoads.push_back(Chain);
3561 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3562 DAG.getVTList(ValueVTs), Values));
3565 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3567 return visitAtomicStore(I);
3569 const Value *SrcV = I.getOperand(0);
3570 const Value *PtrV = I.getOperand(1);
3572 SmallVector<EVT, 4> ValueVTs;
3573 SmallVector<uint64_t, 4> Offsets;
3574 ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
3575 ValueVTs, &Offsets);
3576 unsigned NumValues = ValueVTs.size();
3580 // Get the lowered operands. Note that we do this after
3581 // checking if NumResults is zero, because with zero results
3582 // the operands won't have values in the map.
3583 SDValue Src = getValue(SrcV);
3584 SDValue Ptr = getValue(PtrV);
3586 SDValue Root = getRoot();
3587 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3589 EVT PtrVT = Ptr.getValueType();
3590 bool isVolatile = I.isVolatile();
3591 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3592 unsigned Alignment = I.getAlignment();
3595 I.getAAMetadata(AAInfo);
3597 unsigned ChainI = 0;
3598 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3599 // See visitLoad comments.
3600 if (ChainI == MaxParallelChains) {
3601 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3602 makeArrayRef(Chains.data(), ChainI));
3606 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3607 DAG.getConstant(Offsets[i], PtrVT));
3608 SDValue St = DAG.getStore(Root, getCurSDLoc(),
3609 SDValue(Src.getNode(), Src.getResNo() + i),
3610 Add, MachinePointerInfo(PtrV, Offsets[i]),
3611 isVolatile, isNonTemporal, Alignment, AAInfo);
3612 Chains[ChainI] = St;
3615 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3616 makeArrayRef(Chains.data(), ChainI));
3617 DAG.setRoot(StoreNode);
3620 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3621 SDLoc dl = getCurSDLoc();
3622 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3623 AtomicOrdering FailureOrder = I.getFailureOrdering();
3624 SynchronizationScope Scope = I.getSynchScope();
3626 SDValue InChain = getRoot();
3628 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3629 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3630 SDValue L = DAG.getAtomicCmpSwap(
3631 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3632 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3633 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3634 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3636 SDValue OutChain = L.getValue(2);
3639 DAG.setRoot(OutChain);
3642 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3643 SDLoc dl = getCurSDLoc();
3645 switch (I.getOperation()) {
3646 default: llvm_unreachable("Unknown atomicrmw operation");
3647 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3648 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3649 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3650 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3651 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3652 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3653 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3654 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3655 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3656 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3657 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3659 AtomicOrdering Order = I.getOrdering();
3660 SynchronizationScope Scope = I.getSynchScope();
3662 SDValue InChain = getRoot();
3665 DAG.getAtomic(NT, dl,
3666 getValue(I.getValOperand()).getSimpleValueType(),
3668 getValue(I.getPointerOperand()),
3669 getValue(I.getValOperand()),
3670 I.getPointerOperand(),
3671 /* Alignment=*/ 0, Order, Scope);
3673 SDValue OutChain = L.getValue(1);
3676 DAG.setRoot(OutChain);
3679 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3680 SDLoc dl = getCurSDLoc();
3681 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3684 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3685 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3686 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3689 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3690 SDLoc dl = getCurSDLoc();
3691 AtomicOrdering Order = I.getOrdering();
3692 SynchronizationScope Scope = I.getSynchScope();
3694 SDValue InChain = getRoot();
3696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3697 EVT VT = TLI.getValueType(I.getType());
3699 if (I.getAlignment() < VT.getSizeInBits() / 8)
3700 report_fatal_error("Cannot generate unaligned atomic load");
3702 MachineMemOperand *MMO =
3703 DAG.getMachineFunction().
3704 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3705 MachineMemOperand::MOVolatile |
3706 MachineMemOperand::MOLoad,
3708 I.getAlignment() ? I.getAlignment() :
3709 DAG.getEVTAlignment(VT));
3711 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3713 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3714 getValue(I.getPointerOperand()), MMO,
3717 SDValue OutChain = L.getValue(1);
3720 DAG.setRoot(OutChain);
3723 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3724 SDLoc dl = getCurSDLoc();
3726 AtomicOrdering Order = I.getOrdering();
3727 SynchronizationScope Scope = I.getSynchScope();
3729 SDValue InChain = getRoot();
3731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3732 EVT VT = TLI.getValueType(I.getValueOperand()->getType());
3734 if (I.getAlignment() < VT.getSizeInBits() / 8)
3735 report_fatal_error("Cannot generate unaligned atomic store");
3738 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3740 getValue(I.getPointerOperand()),
3741 getValue(I.getValueOperand()),
3742 I.getPointerOperand(), I.getAlignment(),
3745 DAG.setRoot(OutChain);
3748 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3750 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3751 unsigned Intrinsic) {
3752 bool HasChain = !I.doesNotAccessMemory();
3753 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3755 // Build the operand list.
3756 SmallVector<SDValue, 8> Ops;
3757 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3759 // We don't need to serialize loads against other loads.
3760 Ops.push_back(DAG.getRoot());
3762 Ops.push_back(getRoot());
3766 // Info is set by getTgtMemInstrinsic
3767 TargetLowering::IntrinsicInfo Info;
3768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3769 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3771 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3772 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3773 Info.opc == ISD::INTRINSIC_W_CHAIN)
3774 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
3776 // Add all operands of the call to the operand list.
3777 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3778 SDValue Op = getValue(I.getArgOperand(i));
3782 SmallVector<EVT, 4> ValueVTs;
3783 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3786 ValueVTs.push_back(MVT::Other);
3788 SDVTList VTs = DAG.getVTList(ValueVTs);
3792 if (IsTgtIntrinsic) {
3793 // This is target intrinsic that touches memory
3794 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3795 VTs, Ops, Info.memVT,
3796 MachinePointerInfo(Info.ptrVal, Info.offset),
3797 Info.align, Info.vol,
3798 Info.readMem, Info.writeMem, Info.size);
3799 } else if (!HasChain) {
3800 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3801 } else if (!I.getType()->isVoidTy()) {
3802 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3804 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3808 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3810 PendingLoads.push_back(Chain);
3815 if (!I.getType()->isVoidTy()) {
3816 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3817 EVT VT = TLI.getValueType(PTy);
3818 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3821 setValue(&I, Result);
3825 /// GetSignificand - Get the significand and build it into a floating-point
3826 /// number with exponent of 1:
3828 /// Op = (Op & 0x007fffff) | 0x3f800000;
3830 /// where Op is the hexadecimal representation of floating point value.
3832 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3833 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3834 DAG.getConstant(0x007fffff, MVT::i32));
3835 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3836 DAG.getConstant(0x3f800000, MVT::i32));
3837 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3840 /// GetExponent - Get the exponent:
3842 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3844 /// where Op is the hexadecimal representation of floating point value.
3846 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3848 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3849 DAG.getConstant(0x7f800000, MVT::i32));
3850 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3851 DAG.getConstant(23, TLI.getPointerTy()));
3852 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3853 DAG.getConstant(127, MVT::i32));
3854 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3857 /// getF32Constant - Get 32-bit floating point constant.
3859 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3860 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3864 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3865 /// limited-precision mode.
3866 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3867 const TargetLowering &TLI) {
3868 if (Op.getValueType() == MVT::f32 &&
3869 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3871 // Put the exponent in the right bit position for later addition to the
3874 // #define LOG2OFe 1.4426950f
3875 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3876 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3877 getF32Constant(DAG, 0x3fb8aa3b));
3878 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3880 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3881 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3882 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3884 // IntegerPartOfX <<= 23;
3885 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3886 DAG.getConstant(23, TLI.getPointerTy()));
3888 SDValue TwoToFracPartOfX;
3889 if (LimitFloatPrecision <= 6) {
3890 // For floating-point precision of 6:
3892 // TwoToFractionalPartOfX =
3894 // (0.735607626f + 0.252464424f * x) * x;
3896 // error 0.0144103317, which is 6 bits
3897 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3898 getF32Constant(DAG, 0x3e814304));
3899 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3900 getF32Constant(DAG, 0x3f3c50c8));
3901 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3902 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3903 getF32Constant(DAG, 0x3f7f5e7e));
3904 } else if (LimitFloatPrecision <= 12) {
3905 // For floating-point precision of 12:
3907 // TwoToFractionalPartOfX =
3910 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3912 // 0.000107046256 error, which is 13 to 14 bits
3913 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3914 getF32Constant(DAG, 0x3da235e3));
3915 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3916 getF32Constant(DAG, 0x3e65b8f3));
3917 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3918 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3919 getF32Constant(DAG, 0x3f324b07));
3920 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3921 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3922 getF32Constant(DAG, 0x3f7ff8fd));
3923 } else { // LimitFloatPrecision <= 18
3924 // For floating-point precision of 18:
3926 // TwoToFractionalPartOfX =
3930 // (0.554906021e-1f +
3931 // (0.961591928e-2f +
3932 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3934 // error 2.47208000*10^(-7), which is better than 18 bits
3935 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3936 getF32Constant(DAG, 0x3924b03e));
3937 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3938 getF32Constant(DAG, 0x3ab24b87));
3939 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3940 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3941 getF32Constant(DAG, 0x3c1d8c17));
3942 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3943 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3944 getF32Constant(DAG, 0x3d634a1d));
3945 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3946 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3947 getF32Constant(DAG, 0x3e75fe14));
3948 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3949 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3950 getF32Constant(DAG, 0x3f317234));
3951 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3952 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3953 getF32Constant(DAG, 0x3f800000));
3956 // Add the exponent into the result in integer domain.
3957 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
3958 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3959 DAG.getNode(ISD::ADD, dl, MVT::i32,
3960 t13, IntegerPartOfX));
3963 // No special expansion.
3964 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
3967 /// expandLog - Lower a log intrinsic. Handles the special sequences for
3968 /// limited-precision mode.
3969 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3970 const TargetLowering &TLI) {
3971 if (Op.getValueType() == MVT::f32 &&
3972 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3973 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3975 // Scale the exponent by log(2) [0.69314718f].
3976 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3977 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3978 getF32Constant(DAG, 0x3f317218));
3980 // Get the significand and build it into a floating-point number with
3982 SDValue X = GetSignificand(DAG, Op1, dl);
3984 SDValue LogOfMantissa;
3985 if (LimitFloatPrecision <= 6) {
3986 // For floating-point precision of 6:
3990 // (1.4034025f - 0.23903021f * x) * x;
3992 // error 0.0034276066, which is better than 8 bits
3993 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3994 getF32Constant(DAG, 0xbe74c456));
3995 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3996 getF32Constant(DAG, 0x3fb3a2b1));
3997 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3998 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3999 getF32Constant(DAG, 0x3f949a29));
4000 } else if (LimitFloatPrecision <= 12) {
4001 // For floating-point precision of 12:
4007 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4009 // error 0.000061011436, which is 14 bits
4010 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4011 getF32Constant(DAG, 0xbd67b6d6));
4012 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4013 getF32Constant(DAG, 0x3ee4f4b8));
4014 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4015 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4016 getF32Constant(DAG, 0x3fbc278b));
4017 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4018 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4019 getF32Constant(DAG, 0x40348e95));
4020 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4021 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4022 getF32Constant(DAG, 0x3fdef31a));
4023 } else { // LimitFloatPrecision <= 18
4024 // For floating-point precision of 18:
4032 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4034 // error 0.0000023660568, which is better than 18 bits
4035 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4036 getF32Constant(DAG, 0xbc91e5ac));
4037 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4038 getF32Constant(DAG, 0x3e4350aa));
4039 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4040 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4041 getF32Constant(DAG, 0x3f60d3e3));
4042 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4043 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4044 getF32Constant(DAG, 0x4011cdf0));
4045 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4046 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4047 getF32Constant(DAG, 0x406cfd1c));
4048 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4049 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4050 getF32Constant(DAG, 0x408797cb));
4051 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4052 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4053 getF32Constant(DAG, 0x4006dcab));
4056 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4059 // No special expansion.
4060 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4063 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4064 /// limited-precision mode.
4065 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4066 const TargetLowering &TLI) {
4067 if (Op.getValueType() == MVT::f32 &&
4068 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4069 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4071 // Get the exponent.
4072 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4074 // Get the significand and build it into a floating-point number with
4076 SDValue X = GetSignificand(DAG, Op1, dl);
4078 // Different possible minimax approximations of significand in
4079 // floating-point for various degrees of accuracy over [1,2].
4080 SDValue Log2ofMantissa;
4081 if (LimitFloatPrecision <= 6) {
4082 // For floating-point precision of 6:
4084 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4086 // error 0.0049451742, which is more than 7 bits
4087 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4088 getF32Constant(DAG, 0xbeb08fe0));
4089 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4090 getF32Constant(DAG, 0x40019463));
4091 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4092 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4093 getF32Constant(DAG, 0x3fd6633d));
4094 } else if (LimitFloatPrecision <= 12) {
4095 // For floating-point precision of 12:
4101 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4103 // error 0.0000876136000, which is better than 13 bits
4104 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4105 getF32Constant(DAG, 0xbda7262e));
4106 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4107 getF32Constant(DAG, 0x3f25280b));
4108 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4109 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4110 getF32Constant(DAG, 0x4007b923));
4111 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4112 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4113 getF32Constant(DAG, 0x40823e2f));
4114 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4115 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4116 getF32Constant(DAG, 0x4020d29c));
4117 } else { // LimitFloatPrecision <= 18
4118 // For floating-point precision of 18:
4127 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4129 // error 0.0000018516, which is better than 18 bits
4130 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4131 getF32Constant(DAG, 0xbcd2769e));
4132 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4133 getF32Constant(DAG, 0x3e8ce0b9));
4134 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4135 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4136 getF32Constant(DAG, 0x3fa22ae7));
4137 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4138 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4139 getF32Constant(DAG, 0x40525723));
4140 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4141 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4142 getF32Constant(DAG, 0x40aaf200));
4143 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4144 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4145 getF32Constant(DAG, 0x40c39dad));
4146 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4147 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4148 getF32Constant(DAG, 0x4042902c));
4151 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4154 // No special expansion.
4155 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4158 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4159 /// limited-precision mode.
4160 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4161 const TargetLowering &TLI) {
4162 if (Op.getValueType() == MVT::f32 &&
4163 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4164 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4166 // Scale the exponent by log10(2) [0.30102999f].
4167 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4168 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4169 getF32Constant(DAG, 0x3e9a209a));
4171 // Get the significand and build it into a floating-point number with
4173 SDValue X = GetSignificand(DAG, Op1, dl);
4175 SDValue Log10ofMantissa;
4176 if (LimitFloatPrecision <= 6) {
4177 // For floating-point precision of 6:
4179 // Log10ofMantissa =
4181 // (0.60948995f - 0.10380950f * x) * x;
4183 // error 0.0014886165, which is 6 bits
4184 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4185 getF32Constant(DAG, 0xbdd49a13));
4186 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4187 getF32Constant(DAG, 0x3f1c0789));
4188 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4189 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4190 getF32Constant(DAG, 0x3f011300));
4191 } else if (LimitFloatPrecision <= 12) {
4192 // For floating-point precision of 12:
4194 // Log10ofMantissa =
4197 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4199 // error 0.00019228036, which is better than 12 bits
4200 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4201 getF32Constant(DAG, 0x3d431f31));
4202 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4203 getF32Constant(DAG, 0x3ea21fb2));
4204 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4205 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4206 getF32Constant(DAG, 0x3f6ae232));
4207 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4208 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4209 getF32Constant(DAG, 0x3f25f7c3));
4210 } else { // LimitFloatPrecision <= 18
4211 // For floating-point precision of 18:
4213 // Log10ofMantissa =
4218 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4220 // error 0.0000037995730, which is better than 18 bits
4221 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4222 getF32Constant(DAG, 0x3c5d51ce));
4223 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4224 getF32Constant(DAG, 0x3e00685a));
4225 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4226 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4227 getF32Constant(DAG, 0x3efb6798));
4228 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4229 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4230 getF32Constant(DAG, 0x3f88d192));
4231 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4232 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4233 getF32Constant(DAG, 0x3fc4316c));
4234 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4235 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4236 getF32Constant(DAG, 0x3f57ce70));
4239 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4242 // No special expansion.
4243 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4246 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4247 /// limited-precision mode.
4248 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4249 const TargetLowering &TLI) {
4250 if (Op.getValueType() == MVT::f32 &&
4251 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4252 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4254 // FractionalPartOfX = x - (float)IntegerPartOfX;
4255 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4256 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4258 // IntegerPartOfX <<= 23;
4259 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4260 DAG.getConstant(23, TLI.getPointerTy()));
4262 SDValue TwoToFractionalPartOfX;
4263 if (LimitFloatPrecision <= 6) {
4264 // For floating-point precision of 6:
4266 // TwoToFractionalPartOfX =
4268 // (0.735607626f + 0.252464424f * x) * x;
4270 // error 0.0144103317, which is 6 bits
4271 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4272 getF32Constant(DAG, 0x3e814304));
4273 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4274 getF32Constant(DAG, 0x3f3c50c8));
4275 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4276 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4277 getF32Constant(DAG, 0x3f7f5e7e));
4278 } else if (LimitFloatPrecision <= 12) {
4279 // For floating-point precision of 12:
4281 // TwoToFractionalPartOfX =
4284 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4286 // error 0.000107046256, which is 13 to 14 bits
4287 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4288 getF32Constant(DAG, 0x3da235e3));
4289 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4290 getF32Constant(DAG, 0x3e65b8f3));
4291 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4292 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4293 getF32Constant(DAG, 0x3f324b07));
4294 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4295 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4296 getF32Constant(DAG, 0x3f7ff8fd));
4297 } else { // LimitFloatPrecision <= 18
4298 // For floating-point precision of 18:
4300 // TwoToFractionalPartOfX =
4304 // (0.554906021e-1f +
4305 // (0.961591928e-2f +
4306 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4307 // error 2.47208000*10^(-7), which is better than 18 bits
4308 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4309 getF32Constant(DAG, 0x3924b03e));
4310 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4311 getF32Constant(DAG, 0x3ab24b87));
4312 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4313 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4314 getF32Constant(DAG, 0x3c1d8c17));
4315 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4316 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4317 getF32Constant(DAG, 0x3d634a1d));
4318 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4319 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4320 getF32Constant(DAG, 0x3e75fe14));
4321 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4322 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4323 getF32Constant(DAG, 0x3f317234));
4324 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4325 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4326 getF32Constant(DAG, 0x3f800000));
4329 // Add the exponent into the result in integer domain.
4330 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4331 TwoToFractionalPartOfX);
4332 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4333 DAG.getNode(ISD::ADD, dl, MVT::i32,
4334 t13, IntegerPartOfX));
4337 // No special expansion.
4338 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4341 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4342 /// limited-precision mode with x == 10.0f.
4343 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4344 SelectionDAG &DAG, const TargetLowering &TLI) {
4345 bool IsExp10 = false;
4346 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4347 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4348 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4350 IsExp10 = LHSC->isExactlyValue(Ten);
4355 // Put the exponent in the right bit position for later addition to the
4358 // #define LOG2OF10 3.3219281f
4359 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4360 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4361 getF32Constant(DAG, 0x40549a78));
4362 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4364 // FractionalPartOfX = x - (float)IntegerPartOfX;
4365 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4366 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4368 // IntegerPartOfX <<= 23;
4369 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4370 DAG.getConstant(23, TLI.getPointerTy()));
4372 SDValue TwoToFractionalPartOfX;
4373 if (LimitFloatPrecision <= 6) {
4374 // For floating-point precision of 6:
4376 // twoToFractionalPartOfX =
4378 // (0.735607626f + 0.252464424f * x) * x;
4380 // error 0.0144103317, which is 6 bits
4381 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4382 getF32Constant(DAG, 0x3e814304));
4383 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4384 getF32Constant(DAG, 0x3f3c50c8));
4385 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4386 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4387 getF32Constant(DAG, 0x3f7f5e7e));
4388 } else if (LimitFloatPrecision <= 12) {
4389 // For floating-point precision of 12:
4391 // TwoToFractionalPartOfX =
4394 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4396 // error 0.000107046256, which is 13 to 14 bits
4397 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4398 getF32Constant(DAG, 0x3da235e3));
4399 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4400 getF32Constant(DAG, 0x3e65b8f3));
4401 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4402 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4403 getF32Constant(DAG, 0x3f324b07));
4404 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4405 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4406 getF32Constant(DAG, 0x3f7ff8fd));
4407 } else { // LimitFloatPrecision <= 18
4408 // For floating-point precision of 18:
4410 // TwoToFractionalPartOfX =
4414 // (0.554906021e-1f +
4415 // (0.961591928e-2f +
4416 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4417 // error 2.47208000*10^(-7), which is better than 18 bits
4418 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4419 getF32Constant(DAG, 0x3924b03e));
4420 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4421 getF32Constant(DAG, 0x3ab24b87));
4422 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4423 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4424 getF32Constant(DAG, 0x3c1d8c17));
4425 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4426 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4427 getF32Constant(DAG, 0x3d634a1d));
4428 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4429 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4430 getF32Constant(DAG, 0x3e75fe14));
4431 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4432 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4433 getF32Constant(DAG, 0x3f317234));
4434 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4435 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4436 getF32Constant(DAG, 0x3f800000));
4439 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
4440 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4441 DAG.getNode(ISD::ADD, dl, MVT::i32,
4442 t13, IntegerPartOfX));
4445 // No special expansion.
4446 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4450 /// ExpandPowI - Expand a llvm.powi intrinsic.
4451 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4452 SelectionDAG &DAG) {
4453 // If RHS is a constant, we can expand this out to a multiplication tree,
4454 // otherwise we end up lowering to a call to __powidf2 (for example). When
4455 // optimizing for size, we only want to do this if the expansion would produce
4456 // a small number of multiplies, otherwise we do the full expansion.
4457 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4458 // Get the exponent as a positive value.
4459 unsigned Val = RHSC->getSExtValue();
4460 if ((int)Val < 0) Val = -Val;
4462 // powi(x, 0) -> 1.0
4464 return DAG.getConstantFP(1.0, LHS.getValueType());
4466 const Function *F = DAG.getMachineFunction().getFunction();
4467 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4468 Attribute::OptimizeForSize) ||
4469 // If optimizing for size, don't insert too many multiplies. This
4470 // inserts up to 5 multiplies.
4471 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4472 // We use the simple binary decomposition method to generate the multiply
4473 // sequence. There are more optimal ways to do this (for example,
4474 // powi(x,15) generates one more multiply than it should), but this has
4475 // the benefit of being both really simple and much better than a libcall.
4476 SDValue Res; // Logically starts equal to 1.0
4477 SDValue CurSquare = LHS;
4481 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4483 Res = CurSquare; // 1.0*CurSquare.
4486 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4487 CurSquare, CurSquare);
4491 // If the original was negative, invert the result, producing 1/(x*x*x).
4492 if (RHSC->getSExtValue() < 0)
4493 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4494 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4499 // Otherwise, expand to a libcall.
4500 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4503 // getTruncatedArgReg - Find underlying register used for an truncated
4505 static unsigned getTruncatedArgReg(const SDValue &N) {
4506 if (N.getOpcode() != ISD::TRUNCATE)
4509 const SDValue &Ext = N.getOperand(0);
4510 if (Ext.getOpcode() == ISD::AssertZext ||
4511 Ext.getOpcode() == ISD::AssertSext) {
4512 const SDValue &CFR = Ext.getOperand(0);
4513 if (CFR.getOpcode() == ISD::CopyFromReg)
4514 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4515 if (CFR.getOpcode() == ISD::TRUNCATE)
4516 return getTruncatedArgReg(CFR);
4521 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4522 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4523 /// At the end of instruction selection, they will be inserted to the entry BB.
4524 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V,
4526 MDNode *Expr, int64_t Offset,
4529 const Argument *Arg = dyn_cast<Argument>(V);
4533 MachineFunction &MF = DAG.getMachineFunction();
4534 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4536 // Ignore inlined function arguments here.
4537 DIVariable DV(Variable);
4538 if (DV.isInlinedFnArgument(MF.getFunction()))
4541 Optional<MachineOperand> Op;
4542 // Some arguments' frame index is recorded during argument lowering.
4543 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4544 Op = MachineOperand::CreateFI(FI);
4546 if (!Op && N.getNode()) {
4548 if (N.getOpcode() == ISD::CopyFromReg)
4549 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4551 Reg = getTruncatedArgReg(N);
4552 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4553 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4554 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4559 Op = MachineOperand::CreateReg(Reg, false);
4563 // Check if ValueMap has reg number.
4564 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4565 if (VMI != FuncInfo.ValueMap.end())
4566 Op = MachineOperand::CreateReg(VMI->second, false);
4569 if (!Op && N.getNode())
4570 // Check if frame index is available.
4571 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4572 if (FrameIndexSDNode *FINode =
4573 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4574 Op = MachineOperand::CreateFI(FINode->getIndex());
4580 FuncInfo.ArgDbgValues.push_back(
4581 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE),
4582 IsIndirect, Op->getReg(), Offset, Variable, Expr));
4584 FuncInfo.ArgDbgValues.push_back(
4585 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4588 .addMetadata(Variable)
4589 .addMetadata(Expr));
4594 // VisualStudio defines setjmp as _setjmp
4595 #if defined(_MSC_VER) && defined(setjmp) && \
4596 !defined(setjmp_undefined_for_msvc)
4597 # pragma push_macro("setjmp")
4599 # define setjmp_undefined_for_msvc
4602 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4603 /// we want to emit this as a call to a named external function, return the name
4604 /// otherwise lower it and return null.
4606 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4607 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4608 SDLoc sdl = getCurSDLoc();
4609 DebugLoc dl = getCurDebugLoc();
4612 switch (Intrinsic) {
4614 // By default, turn this into a target intrinsic node.
4615 visitTargetIntrinsic(I, Intrinsic);
4617 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4618 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4619 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
4620 case Intrinsic::returnaddress:
4621 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
4622 getValue(I.getArgOperand(0))));
4624 case Intrinsic::frameaddress:
4625 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4626 getValue(I.getArgOperand(0))));
4628 case Intrinsic::read_register: {
4629 Value *Reg = I.getArgOperand(0);
4630 SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
4631 EVT VT = TLI.getValueType(I.getType());
4632 setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
4635 case Intrinsic::write_register: {
4636 Value *Reg = I.getArgOperand(0);
4637 Value *RegValue = I.getArgOperand(1);
4638 SDValue Chain = getValue(RegValue).getOperand(0);
4639 SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
4640 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4641 RegName, getValue(RegValue)));
4644 case Intrinsic::setjmp:
4645 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4646 case Intrinsic::longjmp:
4647 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4648 case Intrinsic::memcpy: {
4649 // Assert for address < 256 since we support only user defined address
4651 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4653 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4655 "Unknown address space");
4656 SDValue Op1 = getValue(I.getArgOperand(0));
4657 SDValue Op2 = getValue(I.getArgOperand(1));
4658 SDValue Op3 = getValue(I.getArgOperand(2));
4659 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4661 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4662 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4663 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
4664 MachinePointerInfo(I.getArgOperand(0)),
4665 MachinePointerInfo(I.getArgOperand(1))));
4668 case Intrinsic::memset: {
4669 // Assert for address < 256 since we support only user defined address
4671 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4673 "Unknown address space");
4674 SDValue Op1 = getValue(I.getArgOperand(0));
4675 SDValue Op2 = getValue(I.getArgOperand(1));
4676 SDValue Op3 = getValue(I.getArgOperand(2));
4677 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4679 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4680 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4681 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4682 MachinePointerInfo(I.getArgOperand(0))));
4685 case Intrinsic::memmove: {
4686 // Assert for address < 256 since we support only user defined address
4688 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4690 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4692 "Unknown address space");
4693 SDValue Op1 = getValue(I.getArgOperand(0));
4694 SDValue Op2 = getValue(I.getArgOperand(1));
4695 SDValue Op3 = getValue(I.getArgOperand(2));
4696 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4698 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4699 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4700 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4701 MachinePointerInfo(I.getArgOperand(0)),
4702 MachinePointerInfo(I.getArgOperand(1))));
4705 case Intrinsic::dbg_declare: {
4706 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4707 MDNode *Variable = DI.getVariable();
4708 MDNode *Expression = DI.getExpression();
4709 const Value *Address = DI.getAddress();
4710 DIVariable DIVar(Variable);
4711 assert((!DIVar || DIVar.isVariable()) &&
4712 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4713 if (!Address || !DIVar) {
4714 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4718 // Check if address has undef value.
4719 if (isa<UndefValue>(Address) ||
4720 (Address->use_empty() && !isa<Argument>(Address))) {
4721 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4725 SDValue &N = NodeMap[Address];
4726 if (!N.getNode() && isa<Argument>(Address))
4727 // Check unused arguments map.
4728 N = UnusedArgNodeMap[Address];
4731 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4732 Address = BCI->getOperand(0);
4733 // Parameters are handled specially.
4735 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4736 isa<Argument>(Address));
4738 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4740 if (isParameter && !AI) {
4741 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4743 // Byval parameter. We have a frame index at this point.
4744 SDV = DAG.getFrameIndexDbgValue(
4745 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
4747 // Address is an argument, so try to emit its dbg value using
4748 // virtual register info from the FuncInfo.ValueMap.
4749 EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false, N);
4753 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4754 true, 0, dl, SDNodeOrder);
4756 // Can't do anything with other non-AI cases yet.
4757 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4758 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4759 DEBUG(Address->dump());
4762 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4764 // If Address is an argument then try to emit its dbg value using
4765 // virtual register info from the FuncInfo.ValueMap.
4766 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false,
4768 // If variable is pinned by a alloca in dominating bb then
4769 // use StaticAllocaMap.
4770 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4771 if (AI->getParent() != DI.getParent()) {
4772 DenseMap<const AllocaInst*, int>::iterator SI =
4773 FuncInfo.StaticAllocaMap.find(AI);
4774 if (SI != FuncInfo.StaticAllocaMap.end()) {
4775 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4776 0, dl, SDNodeOrder);
4777 DAG.AddDbgValue(SDV, nullptr, false);
4782 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4787 case Intrinsic::dbg_value: {
4788 const DbgValueInst &DI = cast<DbgValueInst>(I);
4789 DIVariable DIVar(DI.getVariable());
4790 assert((!DIVar || DIVar.isVariable()) &&
4791 "Variable in DbgValueInst should be either null or a DIVariable.");
4795 MDNode *Variable = DI.getVariable();
4796 MDNode *Expression = DI.getExpression();
4797 uint64_t Offset = DI.getOffset();
4798 const Value *V = DI.getValue();
4803 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4804 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4806 DAG.AddDbgValue(SDV, nullptr, false);
4808 // Do not use getValue() in here; we don't want to generate code at
4809 // this point if it hasn't been done yet.
4810 SDValue N = NodeMap[V];
4811 if (!N.getNode() && isa<Argument>(V))
4812 // Check unused arguments map.
4813 N = UnusedArgNodeMap[V];
4815 // A dbg.value for an alloca is always indirect.
4816 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
4817 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, Offset,
4819 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4820 IsIndirect, Offset, dl, SDNodeOrder);
4821 DAG.AddDbgValue(SDV, N.getNode(), false);
4823 } else if (!V->use_empty() ) {
4824 // Do not call getValue(V) yet, as we don't want to generate code.
4825 // Remember it for later.
4826 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4827 DanglingDebugInfoMap[V] = DDI;
4829 // We may expand this to cover more cases. One case where we have no
4830 // data available is an unreferenced parameter.
4831 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4835 // Build a debug info table entry.
4836 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4837 V = BCI->getOperand(0);
4838 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4839 // Don't handle byval struct arguments or VLAs, for example.
4841 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4842 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4845 DenseMap<const AllocaInst*, int>::iterator SI =
4846 FuncInfo.StaticAllocaMap.find(AI);
4847 if (SI == FuncInfo.StaticAllocaMap.end())
4848 return nullptr; // VLAs.
4852 case Intrinsic::eh_typeid_for: {
4853 // Find the type id for the given typeinfo.
4854 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4855 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4856 Res = DAG.getConstant(TypeID, MVT::i32);
4861 case Intrinsic::eh_return_i32:
4862 case Intrinsic::eh_return_i64:
4863 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4864 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4867 getValue(I.getArgOperand(0)),
4868 getValue(I.getArgOperand(1))));
4870 case Intrinsic::eh_unwind_init:
4871 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4873 case Intrinsic::eh_dwarf_cfa: {
4874 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4875 TLI.getPointerTy());
4876 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4877 CfaArg.getValueType(),
4878 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4879 CfaArg.getValueType()),
4881 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4882 DAG.getConstant(0, TLI.getPointerTy()));
4883 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4887 case Intrinsic::eh_sjlj_callsite: {
4888 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4889 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4890 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4891 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4893 MMI.setCurrentCallSite(CI->getZExtValue());
4896 case Intrinsic::eh_sjlj_functioncontext: {
4897 // Get and store the index of the function context.
4898 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4900 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4901 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4902 MFI->setFunctionContextIndex(FI);
4905 case Intrinsic::eh_sjlj_setjmp: {
4908 Ops[1] = getValue(I.getArgOperand(0));
4909 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4910 DAG.getVTList(MVT::i32, MVT::Other), Ops);
4911 setValue(&I, Op.getValue(0));
4912 DAG.setRoot(Op.getValue(1));
4915 case Intrinsic::eh_sjlj_longjmp: {
4916 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4917 getRoot(), getValue(I.getArgOperand(0))));
4921 case Intrinsic::x86_mmx_pslli_w:
4922 case Intrinsic::x86_mmx_pslli_d:
4923 case Intrinsic::x86_mmx_pslli_q:
4924 case Intrinsic::x86_mmx_psrli_w:
4925 case Intrinsic::x86_mmx_psrli_d:
4926 case Intrinsic::x86_mmx_psrli_q:
4927 case Intrinsic::x86_mmx_psrai_w:
4928 case Intrinsic::x86_mmx_psrai_d: {
4929 SDValue ShAmt = getValue(I.getArgOperand(1));
4930 if (isa<ConstantSDNode>(ShAmt)) {
4931 visitTargetIntrinsic(I, Intrinsic);
4934 unsigned NewIntrinsic = 0;
4935 EVT ShAmtVT = MVT::v2i32;
4936 switch (Intrinsic) {
4937 case Intrinsic::x86_mmx_pslli_w:
4938 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4940 case Intrinsic::x86_mmx_pslli_d:
4941 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4943 case Intrinsic::x86_mmx_pslli_q:
4944 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4946 case Intrinsic::x86_mmx_psrli_w:
4947 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4949 case Intrinsic::x86_mmx_psrli_d:
4950 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4952 case Intrinsic::x86_mmx_psrli_q:
4953 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4955 case Intrinsic::x86_mmx_psrai_w:
4956 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4958 case Intrinsic::x86_mmx_psrai_d:
4959 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4961 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4964 // The vector shift intrinsics with scalars uses 32b shift amounts but
4965 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4967 // We must do this early because v2i32 is not a legal type.
4970 ShOps[1] = DAG.getConstant(0, MVT::i32);
4971 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
4972 EVT DestVT = TLI.getValueType(I.getType());
4973 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4974 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4975 DAG.getConstant(NewIntrinsic, MVT::i32),
4976 getValue(I.getArgOperand(0)), ShAmt);
4980 case Intrinsic::x86_avx_vinsertf128_pd_256:
4981 case Intrinsic::x86_avx_vinsertf128_ps_256:
4982 case Intrinsic::x86_avx_vinsertf128_si_256:
4983 case Intrinsic::x86_avx2_vinserti128: {
4984 EVT DestVT = TLI.getValueType(I.getType());
4985 EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
4986 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4987 ElVT.getVectorNumElements();
4989 DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
4990 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
4991 DAG.getConstant(Idx, TLI.getVectorIdxTy()));
4995 case Intrinsic::x86_avx_vextractf128_pd_256:
4996 case Intrinsic::x86_avx_vextractf128_ps_256:
4997 case Intrinsic::x86_avx_vextractf128_si_256:
4998 case Intrinsic::x86_avx2_vextracti128: {
4999 EVT DestVT = TLI.getValueType(I.getType());
5000 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
5001 DestVT.getVectorNumElements();
5002 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
5003 getValue(I.getArgOperand(0)),
5004 DAG.getConstant(Idx, TLI.getVectorIdxTy()));
5008 case Intrinsic::convertff:
5009 case Intrinsic::convertfsi:
5010 case Intrinsic::convertfui:
5011 case Intrinsic::convertsif:
5012 case Intrinsic::convertuif:
5013 case Intrinsic::convertss:
5014 case Intrinsic::convertsu:
5015 case Intrinsic::convertus:
5016 case Intrinsic::convertuu: {
5017 ISD::CvtCode Code = ISD::CVT_INVALID;
5018 switch (Intrinsic) {
5019 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5020 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
5021 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5022 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5023 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5024 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5025 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
5026 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
5027 case Intrinsic::convertus: Code = ISD::CVT_US; break;
5028 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
5030 EVT DestVT = TLI.getValueType(I.getType());
5031 const Value *Op1 = I.getArgOperand(0);
5032 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
5033 DAG.getValueType(DestVT),
5034 DAG.getValueType(getValue(Op1).getValueType()),
5035 getValue(I.getArgOperand(1)),
5036 getValue(I.getArgOperand(2)),
5041 case Intrinsic::powi:
5042 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5043 getValue(I.getArgOperand(1)), DAG));
5045 case Intrinsic::log:
5046 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5048 case Intrinsic::log2:
5049 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5051 case Intrinsic::log10:
5052 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5054 case Intrinsic::exp:
5055 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5057 case Intrinsic::exp2:
5058 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5060 case Intrinsic::pow:
5061 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5062 getValue(I.getArgOperand(1)), DAG, TLI));
5064 case Intrinsic::sqrt:
5065 case Intrinsic::fabs:
5066 case Intrinsic::sin:
5067 case Intrinsic::cos:
5068 case Intrinsic::floor:
5069 case Intrinsic::ceil:
5070 case Intrinsic::trunc:
5071 case Intrinsic::rint:
5072 case Intrinsic::nearbyint:
5073 case Intrinsic::round: {
5075 switch (Intrinsic) {
5076 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5077 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5078 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5079 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5080 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5081 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5082 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5083 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5084 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5085 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5086 case Intrinsic::round: Opcode = ISD::FROUND; break;
5089 setValue(&I, DAG.getNode(Opcode, sdl,
5090 getValue(I.getArgOperand(0)).getValueType(),
5091 getValue(I.getArgOperand(0))));
5094 case Intrinsic::minnum:
5095 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
5096 getValue(I.getArgOperand(0)).getValueType(),
5097 getValue(I.getArgOperand(0)),
5098 getValue(I.getArgOperand(1))));
5100 case Intrinsic::maxnum:
5101 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
5102 getValue(I.getArgOperand(0)).getValueType(),
5103 getValue(I.getArgOperand(0)),
5104 getValue(I.getArgOperand(1))));
5106 case Intrinsic::copysign:
5107 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5108 getValue(I.getArgOperand(0)).getValueType(),
5109 getValue(I.getArgOperand(0)),
5110 getValue(I.getArgOperand(1))));
5112 case Intrinsic::fma:
5113 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5114 getValue(I.getArgOperand(0)).getValueType(),
5115 getValue(I.getArgOperand(0)),
5116 getValue(I.getArgOperand(1)),
5117 getValue(I.getArgOperand(2))));
5119 case Intrinsic::fmuladd: {
5120 EVT VT = TLI.getValueType(I.getType());
5121 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5122 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5123 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5124 getValue(I.getArgOperand(0)).getValueType(),
5125 getValue(I.getArgOperand(0)),
5126 getValue(I.getArgOperand(1)),
5127 getValue(I.getArgOperand(2))));
5129 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5130 getValue(I.getArgOperand(0)).getValueType(),
5131 getValue(I.getArgOperand(0)),
5132 getValue(I.getArgOperand(1)));
5133 SDValue Add = DAG.getNode(ISD::FADD, sdl,
5134 getValue(I.getArgOperand(0)).getValueType(),
5136 getValue(I.getArgOperand(2)));
5141 case Intrinsic::convert_to_fp16:
5142 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5143 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5144 getValue(I.getArgOperand(0)),
5145 DAG.getTargetConstant(0, MVT::i32))));
5147 case Intrinsic::convert_from_fp16:
5149 DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
5150 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5151 getValue(I.getArgOperand(0)))));
5153 case Intrinsic::pcmarker: {
5154 SDValue Tmp = getValue(I.getArgOperand(0));
5155 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5158 case Intrinsic::readcyclecounter: {
5159 SDValue Op = getRoot();
5160 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5161 DAG.getVTList(MVT::i64, MVT::Other), Op);
5163 DAG.setRoot(Res.getValue(1));
5166 case Intrinsic::bswap:
5167 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5168 getValue(I.getArgOperand(0)).getValueType(),
5169 getValue(I.getArgOperand(0))));
5171 case Intrinsic::cttz: {
5172 SDValue Arg = getValue(I.getArgOperand(0));
5173 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5174 EVT Ty = Arg.getValueType();
5175 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5179 case Intrinsic::ctlz: {
5180 SDValue Arg = getValue(I.getArgOperand(0));
5181 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5182 EVT Ty = Arg.getValueType();
5183 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5187 case Intrinsic::ctpop: {
5188 SDValue Arg = getValue(I.getArgOperand(0));
5189 EVT Ty = Arg.getValueType();
5190 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5193 case Intrinsic::stacksave: {
5194 SDValue Op = getRoot();
5195 Res = DAG.getNode(ISD::STACKSAVE, sdl,
5196 DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
5198 DAG.setRoot(Res.getValue(1));
5201 case Intrinsic::stackrestore: {
5202 Res = getValue(I.getArgOperand(0));
5203 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5206 case Intrinsic::stackprotector: {
5207 // Emit code into the DAG to store the stack guard onto the stack.
5208 MachineFunction &MF = DAG.getMachineFunction();
5209 MachineFrameInfo *MFI = MF.getFrameInfo();
5210 EVT PtrTy = TLI.getPointerTy();
5211 SDValue Src, Chain = getRoot();
5212 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
5213 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
5215 // See if Ptr is a bitcast. If it is, look through it and see if we can get
5216 // global variable __stack_chk_guard.
5218 if (const Operator *BC = dyn_cast<Operator>(Ptr))
5219 if (BC->getOpcode() == Instruction::BitCast)
5220 GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
5222 if (GV && TLI.useLoadStackGuardNode()) {
5223 // Emit a LOAD_STACK_GUARD node.
5224 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5226 MachinePointerInfo MPInfo(GV);
5227 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5228 unsigned Flags = MachineMemOperand::MOLoad |
5229 MachineMemOperand::MOInvariant;
5230 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5231 PtrTy.getSizeInBits() / 8,
5232 DAG.getEVTAlignment(PtrTy));
5233 Node->setMemRefs(MemRefs, MemRefs + 1);
5235 // Copy the guard value to a virtual register so that it can be
5236 // retrieved in the epilogue.
5237 Src = SDValue(Node, 0);
5238 const TargetRegisterClass *RC =
5239 TLI.getRegClassFor(Src.getSimpleValueType());
5240 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5242 SPDescriptor.setGuardReg(Reg);
5243 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5245 Src = getValue(I.getArgOperand(0)); // The guard's value.
5248 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5250 int FI = FuncInfo.StaticAllocaMap[Slot];
5251 MFI->setStackProtectorIndex(FI);
5253 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5255 // Store the stack protector onto the stack.
5256 Res = DAG.getStore(Chain, sdl, Src, FIN,
5257 MachinePointerInfo::getFixedStack(FI),
5263 case Intrinsic::objectsize: {
5264 // If we don't know by now, we're never going to know.
5265 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5267 assert(CI && "Non-constant type in __builtin_object_size?");
5269 SDValue Arg = getValue(I.getCalledValue());
5270 EVT Ty = Arg.getValueType();
5273 Res = DAG.getConstant(-1ULL, Ty);
5275 Res = DAG.getConstant(0, Ty);
5280 case Intrinsic::annotation:
5281 case Intrinsic::ptr_annotation:
5282 // Drop the intrinsic, but forward the value
5283 setValue(&I, getValue(I.getOperand(0)));
5285 case Intrinsic::assume:
5286 case Intrinsic::var_annotation:
5287 // Discard annotate attributes and assumptions
5290 case Intrinsic::init_trampoline: {
5291 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5295 Ops[1] = getValue(I.getArgOperand(0));
5296 Ops[2] = getValue(I.getArgOperand(1));
5297 Ops[3] = getValue(I.getArgOperand(2));
5298 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5299 Ops[5] = DAG.getSrcValue(F);
5301 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5306 case Intrinsic::adjust_trampoline: {
5307 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5309 getValue(I.getArgOperand(0))));
5312 case Intrinsic::gcroot:
5314 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5315 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5317 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5318 GFI->addStackRoot(FI->getIndex(), TypeMap);
5321 case Intrinsic::gcread:
5322 case Intrinsic::gcwrite:
5323 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5324 case Intrinsic::flt_rounds:
5325 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5328 case Intrinsic::expect: {
5329 // Just replace __builtin_expect(exp, c) with EXP.
5330 setValue(&I, getValue(I.getArgOperand(0)));
5334 case Intrinsic::debugtrap:
5335 case Intrinsic::trap: {
5336 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
5337 if (TrapFuncName.empty()) {
5338 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5339 ISD::TRAP : ISD::DEBUGTRAP;
5340 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5343 TargetLowering::ArgListTy Args;
5345 TargetLowering::CallLoweringInfo CLI(DAG);
5346 CLI.setDebugLoc(sdl).setChain(getRoot())
5347 .setCallee(CallingConv::C, I.getType(),
5348 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
5349 std::move(Args), 0);
5351 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5352 DAG.setRoot(Result.second);
5356 case Intrinsic::uadd_with_overflow:
5357 case Intrinsic::sadd_with_overflow:
5358 case Intrinsic::usub_with_overflow:
5359 case Intrinsic::ssub_with_overflow:
5360 case Intrinsic::umul_with_overflow:
5361 case Intrinsic::smul_with_overflow: {
5363 switch (Intrinsic) {
5364 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5365 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5366 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5367 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5368 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5369 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5370 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5372 SDValue Op1 = getValue(I.getArgOperand(0));
5373 SDValue Op2 = getValue(I.getArgOperand(1));
5375 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5376 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5379 case Intrinsic::prefetch: {
5381 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5383 Ops[1] = getValue(I.getArgOperand(0));
5384 Ops[2] = getValue(I.getArgOperand(1));
5385 Ops[3] = getValue(I.getArgOperand(2));
5386 Ops[4] = getValue(I.getArgOperand(3));
5387 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5388 DAG.getVTList(MVT::Other), Ops,
5389 EVT::getIntegerVT(*Context, 8),
5390 MachinePointerInfo(I.getArgOperand(0)),
5392 false, /* volatile */
5394 rw==1)); /* write */
5397 case Intrinsic::lifetime_start:
5398 case Intrinsic::lifetime_end: {
5399 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5400 // Stack coloring is not enabled in O0, discard region information.
5401 if (TM.getOptLevel() == CodeGenOpt::None)
5404 SmallVector<Value *, 4> Allocas;
5405 GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
5407 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5408 E = Allocas.end(); Object != E; ++Object) {
5409 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5411 // Could not find an Alloca.
5412 if (!LifetimeObject)
5415 // First check that the Alloca is static, otherwise it won't have a
5416 // valid frame index.
5417 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5418 if (SI == FuncInfo.StaticAllocaMap.end())
5421 int FI = SI->second;
5425 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
5426 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5428 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5433 case Intrinsic::invariant_start:
5434 // Discard region information.
5435 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
5437 case Intrinsic::invariant_end:
5438 // Discard region information.
5440 case Intrinsic::stackprotectorcheck: {
5441 // Do not actually emit anything for this basic block. Instead we initialize
5442 // the stack protector descriptor and export the guard variable so we can
5443 // access it in FinishBasicBlock.
5444 const BasicBlock *BB = I.getParent();
5445 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5446 ExportFromCurrentBlock(SPDescriptor.getGuard());
5448 // Flush our exports since we are going to process a terminator.
5449 (void)getControlRoot();
5452 case Intrinsic::clear_cache:
5453 return TLI.getClearCacheBuiltinName();
5454 case Intrinsic::donothing:
5457 case Intrinsic::experimental_stackmap: {
5461 case Intrinsic::experimental_patchpoint_void:
5462 case Intrinsic::experimental_patchpoint_i64: {
5463 visitPatchpoint(&I);
5466 case Intrinsic::experimental_gc_statepoint: {
5470 case Intrinsic::experimental_gc_result_int:
5471 case Intrinsic::experimental_gc_result_float:
5472 case Intrinsic::experimental_gc_result_ptr: {
5476 case Intrinsic::experimental_gc_relocate: {
5483 std::pair<SDValue, SDValue>
5484 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5485 MachineBasicBlock *LandingPad) {
5486 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5487 MCSymbol *BeginLabel = nullptr;
5490 // Insert a label before the invoke call to mark the try range. This can be
5491 // used to detect deletion of the invoke via the MachineModuleInfo.
5492 BeginLabel = MMI.getContext().CreateTempSymbol();
5494 // For SjLj, keep track of which landing pads go with which invokes
5495 // so as to maintain the ordering of pads in the LSDA.
5496 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5497 if (CallSiteIndex) {
5498 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5499 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5501 // Now that the call site is handled, stop tracking it.
5502 MMI.setCurrentCallSite(0);
5505 // Both PendingLoads and PendingExports must be flushed here;
5506 // this call might not return.
5508 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5510 CLI.setChain(getRoot());
5513 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
5514 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
5516 assert((CLI.IsTailCall || Result.second.getNode()) &&
5517 "Non-null chain expected with non-tail call!");
5518 assert((Result.second.getNode() || !Result.first.getNode()) &&
5519 "Null value expected with tail call!");
5521 if (!Result.second.getNode()) {
5522 // As a special case, a null chain means that a tail call has been emitted
5523 // and the DAG root is already updated.
5526 // Since there's no actual continuation from this block, nothing can be
5527 // relying on us setting vregs for them.
5528 PendingExports.clear();
5530 DAG.setRoot(Result.second);
5534 // Insert a label at the end of the invoke call to mark the try range. This
5535 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5536 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5537 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5539 // Inform MachineModuleInfo of range.
5540 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5546 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5548 MachineBasicBlock *LandingPad) {
5549 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5550 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5551 Type *RetTy = FTy->getReturnType();
5553 TargetLowering::ArgListTy Args;
5554 TargetLowering::ArgListEntry Entry;
5555 Args.reserve(CS.arg_size());
5557 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5559 const Value *V = *i;
5562 if (V->getType()->isEmptyTy())
5565 SDValue ArgNode = getValue(V);
5566 Entry.Node = ArgNode; Entry.Ty = V->getType();
5568 // Skip the first return-type Attribute to get to params.
5569 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5570 Args.push_back(Entry);
5573 // Check if target-independent constraints permit a tail call here.
5574 // Target-dependent constraints are checked within TLI->LowerCallTo.
5575 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5578 TargetLowering::CallLoweringInfo CLI(DAG);
5579 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5580 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5581 .setTailCall(isTailCall);
5582 std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
5584 if (Result.first.getNode())
5585 setValue(CS.getInstruction(), Result.first);
5588 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5589 /// value is equal or not-equal to zero.
5590 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5591 for (const User *U : V->users()) {
5592 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5593 if (IC->isEquality())
5594 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5595 if (C->isNullValue())
5597 // Unknown instruction.
5603 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5605 SelectionDAGBuilder &Builder) {
5607 // Check to see if this load can be trivially constant folded, e.g. if the
5608 // input is from a string literal.
5609 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5610 // Cast pointer to the type we really want to load.
5611 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5612 PointerType::getUnqual(LoadTy));
5614 if (const Constant *LoadCst =
5615 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5617 return Builder.getValue(LoadCst);
5620 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5621 // still constant memory, the input chain can be the entry node.
5623 bool ConstantMemory = false;
5625 // Do not serialize (non-volatile) loads of constant memory with anything.
5626 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5627 Root = Builder.DAG.getEntryNode();
5628 ConstantMemory = true;
5630 // Do not serialize non-volatile loads against each other.
5631 Root = Builder.DAG.getRoot();
5634 SDValue Ptr = Builder.getValue(PtrVal);
5635 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5636 Ptr, MachinePointerInfo(PtrVal),
5638 false /*nontemporal*/,
5639 false /*isinvariant*/, 1 /* align=1 */);
5641 if (!ConstantMemory)
5642 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5646 /// processIntegerCallValue - Record the value for an instruction that
5647 /// produces an integer result, converting the type where necessary.
5648 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5651 EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5653 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5655 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5656 setValue(&I, Value);
5659 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5660 /// If so, return true and lower it, otherwise return false and it will be
5661 /// lowered like a normal call.
5662 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5663 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5664 if (I.getNumArgOperands() != 3)
5667 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5668 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5669 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5670 !I.getType()->isIntegerTy())
5673 const Value *Size = I.getArgOperand(2);
5674 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5675 if (CSize && CSize->getZExtValue() == 0) {
5676 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5677 setValue(&I, DAG.getConstant(0, CallVT));
5681 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5682 std::pair<SDValue, SDValue> Res =
5683 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5684 getValue(LHS), getValue(RHS), getValue(Size),
5685 MachinePointerInfo(LHS),
5686 MachinePointerInfo(RHS));
5687 if (Res.first.getNode()) {
5688 processIntegerCallValue(I, Res.first, true);
5689 PendingLoads.push_back(Res.second);
5693 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5694 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5695 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5696 bool ActuallyDoIt = true;
5699 switch (CSize->getZExtValue()) {
5701 LoadVT = MVT::Other;
5703 ActuallyDoIt = false;
5707 LoadTy = Type::getInt16Ty(CSize->getContext());
5711 LoadTy = Type::getInt32Ty(CSize->getContext());
5715 LoadTy = Type::getInt64Ty(CSize->getContext());
5719 LoadVT = MVT::v4i32;
5720 LoadTy = Type::getInt32Ty(CSize->getContext());
5721 LoadTy = VectorType::get(LoadTy, 4);
5726 // This turns into unaligned loads. We only do this if the target natively
5727 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5728 // we'll only produce a small number of byte loads.
5730 // Require that we can find a legal MVT, and only do this if the target
5731 // supports unaligned loads of that type. Expanding into byte loads would
5733 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5734 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5735 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5736 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5737 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5738 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5739 // TODO: Check alignment of src and dest ptrs.
5740 if (!TLI.isTypeLegal(LoadVT) ||
5741 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5742 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5743 ActuallyDoIt = false;
5747 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5748 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5750 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5752 processIntegerCallValue(I, Res, false);
5761 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5762 /// form. If so, return true and lower it, otherwise return false and it
5763 /// will be lowered like a normal call.
5764 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5765 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5766 if (I.getNumArgOperands() != 3)
5769 const Value *Src = I.getArgOperand(0);
5770 const Value *Char = I.getArgOperand(1);
5771 const Value *Length = I.getArgOperand(2);
5772 if (!Src->getType()->isPointerTy() ||
5773 !Char->getType()->isIntegerTy() ||
5774 !Length->getType()->isIntegerTy() ||
5775 !I.getType()->isPointerTy())
5778 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5779 std::pair<SDValue, SDValue> Res =
5780 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5781 getValue(Src), getValue(Char), getValue(Length),
5782 MachinePointerInfo(Src));
5783 if (Res.first.getNode()) {
5784 setValue(&I, Res.first);
5785 PendingLoads.push_back(Res.second);
5792 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5793 /// optimized form. If so, return true and lower it, otherwise return false
5794 /// and it will be lowered like a normal call.
5795 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5796 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5797 if (I.getNumArgOperands() != 2)
5800 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5801 if (!Arg0->getType()->isPointerTy() ||
5802 !Arg1->getType()->isPointerTy() ||
5803 !I.getType()->isPointerTy())
5806 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5807 std::pair<SDValue, SDValue> Res =
5808 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5809 getValue(Arg0), getValue(Arg1),
5810 MachinePointerInfo(Arg0),
5811 MachinePointerInfo(Arg1), isStpcpy);
5812 if (Res.first.getNode()) {
5813 setValue(&I, Res.first);
5814 DAG.setRoot(Res.second);
5821 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5822 /// If so, return true and lower it, otherwise return false and it will be
5823 /// lowered like a normal call.
5824 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5825 // Verify that the prototype makes sense. int strcmp(void*,void*)
5826 if (I.getNumArgOperands() != 2)
5829 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5830 if (!Arg0->getType()->isPointerTy() ||
5831 !Arg1->getType()->isPointerTy() ||
5832 !I.getType()->isIntegerTy())
5835 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5836 std::pair<SDValue, SDValue> Res =
5837 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5838 getValue(Arg0), getValue(Arg1),
5839 MachinePointerInfo(Arg0),
5840 MachinePointerInfo(Arg1));
5841 if (Res.first.getNode()) {
5842 processIntegerCallValue(I, Res.first, true);
5843 PendingLoads.push_back(Res.second);
5850 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5851 /// form. If so, return true and lower it, otherwise return false and it
5852 /// will be lowered like a normal call.
5853 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5854 // Verify that the prototype makes sense. size_t strlen(char *)
5855 if (I.getNumArgOperands() != 1)
5858 const Value *Arg0 = I.getArgOperand(0);
5859 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5862 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5863 std::pair<SDValue, SDValue> Res =
5864 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5865 getValue(Arg0), MachinePointerInfo(Arg0));
5866 if (Res.first.getNode()) {
5867 processIntegerCallValue(I, Res.first, false);
5868 PendingLoads.push_back(Res.second);
5875 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5876 /// form. If so, return true and lower it, otherwise return false and it
5877 /// will be lowered like a normal call.
5878 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5879 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5880 if (I.getNumArgOperands() != 2)
5883 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5884 if (!Arg0->getType()->isPointerTy() ||
5885 !Arg1->getType()->isIntegerTy() ||
5886 !I.getType()->isIntegerTy())
5889 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5890 std::pair<SDValue, SDValue> Res =
5891 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5892 getValue(Arg0), getValue(Arg1),
5893 MachinePointerInfo(Arg0));
5894 if (Res.first.getNode()) {
5895 processIntegerCallValue(I, Res.first, false);
5896 PendingLoads.push_back(Res.second);
5903 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5904 /// operation (as expected), translate it to an SDNode with the specified opcode
5905 /// and return true.
5906 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5908 // Sanity check that it really is a unary floating-point call.
5909 if (I.getNumArgOperands() != 1 ||
5910 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5911 I.getType() != I.getArgOperand(0)->getType() ||
5912 !I.onlyReadsMemory())
5915 SDValue Tmp = getValue(I.getArgOperand(0));
5916 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5920 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
5921 /// operation (as expected), translate it to an SDNode with the specified opcode
5922 /// and return true.
5923 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5925 // Sanity check that it really is a binary floating-point call.
5926 if (I.getNumArgOperands() != 2 ||
5927 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5928 I.getType() != I.getArgOperand(0)->getType() ||
5929 I.getType() != I.getArgOperand(1)->getType() ||
5930 !I.onlyReadsMemory())
5933 SDValue Tmp0 = getValue(I.getArgOperand(0));
5934 SDValue Tmp1 = getValue(I.getArgOperand(1));
5935 EVT VT = Tmp0.getValueType();
5936 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5940 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5941 // Handle inline assembly differently.
5942 if (isa<InlineAsm>(I.getCalledValue())) {
5947 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5948 ComputeUsesVAFloatArgument(I, &MMI);
5950 const char *RenameFn = nullptr;
5951 if (Function *F = I.getCalledFunction()) {
5952 if (F->isDeclaration()) {
5953 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5954 if (unsigned IID = II->getIntrinsicID(F)) {
5955 RenameFn = visitIntrinsicCall(I, IID);
5960 if (unsigned IID = F->getIntrinsicID()) {
5961 RenameFn = visitIntrinsicCall(I, IID);
5967 // Check for well-known libc/libm calls. If the function is internal, it
5968 // can't be a library call.
5970 if (!F->hasLocalLinkage() && F->hasName() &&
5971 LibInfo->getLibFunc(F->getName(), Func) &&
5972 LibInfo->hasOptimizedCodeGen(Func)) {
5975 case LibFunc::copysign:
5976 case LibFunc::copysignf:
5977 case LibFunc::copysignl:
5978 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5979 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5980 I.getType() == I.getArgOperand(0)->getType() &&
5981 I.getType() == I.getArgOperand(1)->getType() &&
5982 I.onlyReadsMemory()) {
5983 SDValue LHS = getValue(I.getArgOperand(0));
5984 SDValue RHS = getValue(I.getArgOperand(1));
5985 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5986 LHS.getValueType(), LHS, RHS));
5991 case LibFunc::fabsf:
5992 case LibFunc::fabsl:
5993 if (visitUnaryFloatCall(I, ISD::FABS))
5997 case LibFunc::fminf:
5998 case LibFunc::fminl:
5999 if (visitBinaryFloatCall(I, ISD::FMINNUM))
6003 case LibFunc::fmaxf:
6004 case LibFunc::fmaxl:
6005 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6011 if (visitUnaryFloatCall(I, ISD::FSIN))
6017 if (visitUnaryFloatCall(I, ISD::FCOS))
6021 case LibFunc::sqrtf:
6022 case LibFunc::sqrtl:
6023 case LibFunc::sqrt_finite:
6024 case LibFunc::sqrtf_finite:
6025 case LibFunc::sqrtl_finite:
6026 if (visitUnaryFloatCall(I, ISD::FSQRT))
6029 case LibFunc::floor:
6030 case LibFunc::floorf:
6031 case LibFunc::floorl:
6032 if (visitUnaryFloatCall(I, ISD::FFLOOR))
6035 case LibFunc::nearbyint:
6036 case LibFunc::nearbyintf:
6037 case LibFunc::nearbyintl:
6038 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6042 case LibFunc::ceilf:
6043 case LibFunc::ceill:
6044 if (visitUnaryFloatCall(I, ISD::FCEIL))
6048 case LibFunc::rintf:
6049 case LibFunc::rintl:
6050 if (visitUnaryFloatCall(I, ISD::FRINT))
6053 case LibFunc::round:
6054 case LibFunc::roundf:
6055 case LibFunc::roundl:
6056 if (visitUnaryFloatCall(I, ISD::FROUND))
6059 case LibFunc::trunc:
6060 case LibFunc::truncf:
6061 case LibFunc::truncl:
6062 if (visitUnaryFloatCall(I, ISD::FTRUNC))
6066 case LibFunc::log2f:
6067 case LibFunc::log2l:
6068 if (visitUnaryFloatCall(I, ISD::FLOG2))
6072 case LibFunc::exp2f:
6073 case LibFunc::exp2l:
6074 if (visitUnaryFloatCall(I, ISD::FEXP2))
6077 case LibFunc::memcmp:
6078 if (visitMemCmpCall(I))
6081 case LibFunc::memchr:
6082 if (visitMemChrCall(I))
6085 case LibFunc::strcpy:
6086 if (visitStrCpyCall(I, false))
6089 case LibFunc::stpcpy:
6090 if (visitStrCpyCall(I, true))
6093 case LibFunc::strcmp:
6094 if (visitStrCmpCall(I))
6097 case LibFunc::strlen:
6098 if (visitStrLenCall(I))
6101 case LibFunc::strnlen:
6102 if (visitStrNLenCall(I))
6111 Callee = getValue(I.getCalledValue());
6113 Callee = DAG.getExternalSymbol(RenameFn,
6114 DAG.getTargetLoweringInfo().getPointerTy());
6116 // Check if we can potentially perform a tail call. More detailed checking is
6117 // be done within LowerCallTo, after more information about the call is known.
6118 LowerCallTo(&I, Callee, I.isTailCall());
6123 /// AsmOperandInfo - This contains information for each constraint that we are
6125 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6127 /// CallOperand - If this is the result output operand or a clobber
6128 /// this is null, otherwise it is the incoming operand to the CallInst.
6129 /// This gets modified as the asm is processed.
6130 SDValue CallOperand;
6132 /// AssignedRegs - If this is a register or register class operand, this
6133 /// contains the set of register corresponding to the operand.
6134 RegsForValue AssignedRegs;
6136 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6137 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6140 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6141 /// corresponds to. If there is no Value* for this operand, it returns
6143 EVT getCallOperandValEVT(LLVMContext &Context,
6144 const TargetLowering &TLI,
6145 const DataLayout *DL) const {
6146 if (!CallOperandVal) return MVT::Other;
6148 if (isa<BasicBlock>(CallOperandVal))
6149 return TLI.getPointerTy();
6151 llvm::Type *OpTy = CallOperandVal->getType();
6153 // FIXME: code duplicated from TargetLowering::ParseConstraints().
6154 // If this is an indirect operand, the operand is a pointer to the
6157 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6159 report_fatal_error("Indirect operand for inline asm not a pointer!");
6160 OpTy = PtrTy->getElementType();
6163 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6164 if (StructType *STy = dyn_cast<StructType>(OpTy))
6165 if (STy->getNumElements() == 1)
6166 OpTy = STy->getElementType(0);
6168 // If OpTy is not a single value, it may be a struct/union that we
6169 // can tile with integers.
6170 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6171 unsigned BitSize = DL->getTypeSizeInBits(OpTy);
6180 OpTy = IntegerType::get(Context, BitSize);
6185 return TLI.getValueType(OpTy, true);
6189 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6191 } // end anonymous namespace
6193 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6194 /// specified operand. We prefer to assign virtual registers, to allow the
6195 /// register allocator to handle the assignment process. However, if the asm
6196 /// uses features that we can't model on machineinstrs, we have SDISel do the
6197 /// allocation. This produces generally horrible, but correct, code.
6199 /// OpInfo describes the operand.
6201 static void GetRegistersForValue(SelectionDAG &DAG,
6202 const TargetLowering &TLI,
6204 SDISelAsmOperandInfo &OpInfo) {
6205 LLVMContext &Context = *DAG.getContext();
6207 MachineFunction &MF = DAG.getMachineFunction();
6208 SmallVector<unsigned, 4> Regs;
6210 // If this is a constraint for a single physreg, or a constraint for a
6211 // register class, find it.
6212 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
6213 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6214 OpInfo.ConstraintVT);
6216 unsigned NumRegs = 1;
6217 if (OpInfo.ConstraintVT != MVT::Other) {
6218 // If this is a FP input in an integer register (or visa versa) insert a bit
6219 // cast of the input value. More generally, handle any case where the input
6220 // value disagrees with the register class we plan to stick this in.
6221 if (OpInfo.Type == InlineAsm::isInput &&
6222 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6223 // Try to convert to the first EVT that the reg class contains. If the
6224 // types are identical size, use a bitcast to convert (e.g. two differing
6226 MVT RegVT = *PhysReg.second->vt_begin();
6227 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6228 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6229 RegVT, OpInfo.CallOperand);
6230 OpInfo.ConstraintVT = RegVT;
6231 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6232 // If the input is a FP value and we want it in FP registers, do a
6233 // bitcast to the corresponding integer type. This turns an f64 value
6234 // into i64, which can be passed with two i32 values on a 32-bit
6236 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6237 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6238 RegVT, OpInfo.CallOperand);
6239 OpInfo.ConstraintVT = RegVT;
6243 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6247 EVT ValueVT = OpInfo.ConstraintVT;
6249 // If this is a constraint for a specific physical register, like {r17},
6251 if (unsigned AssignedReg = PhysReg.first) {
6252 const TargetRegisterClass *RC = PhysReg.second;
6253 if (OpInfo.ConstraintVT == MVT::Other)
6254 ValueVT = *RC->vt_begin();
6256 // Get the actual register value type. This is important, because the user
6257 // may have asked for (e.g.) the AX register in i32 type. We need to
6258 // remember that AX is actually i16 to get the right extension.
6259 RegVT = *RC->vt_begin();
6261 // This is a explicit reference to a physical register.
6262 Regs.push_back(AssignedReg);
6264 // If this is an expanded reference, add the rest of the regs to Regs.
6266 TargetRegisterClass::iterator I = RC->begin();
6267 for (; *I != AssignedReg; ++I)
6268 assert(I != RC->end() && "Didn't find reg!");
6270 // Already added the first reg.
6272 for (; NumRegs; --NumRegs, ++I) {
6273 assert(I != RC->end() && "Ran out of registers to allocate!");
6278 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6282 // Otherwise, if this was a reference to an LLVM register class, create vregs
6283 // for this reference.
6284 if (const TargetRegisterClass *RC = PhysReg.second) {
6285 RegVT = *RC->vt_begin();
6286 if (OpInfo.ConstraintVT == MVT::Other)
6289 // Create the appropriate number of virtual registers.
6290 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6291 for (; NumRegs; --NumRegs)
6292 Regs.push_back(RegInfo.createVirtualRegister(RC));
6294 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6298 // Otherwise, we couldn't allocate enough registers for this.
6301 /// visitInlineAsm - Handle a call to an InlineAsm object.
6303 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6304 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6306 /// ConstraintOperands - Information about all of the constraints.
6307 SDISelAsmOperandInfoVector ConstraintOperands;
6309 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6310 TargetLowering::AsmOperandInfoVector
6311 TargetConstraints = TLI.ParseConstraints(CS);
6313 bool hasMemory = false;
6315 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6316 unsigned ResNo = 0; // ResNo - The result number of the next output.
6317 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6318 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6319 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6321 MVT OpVT = MVT::Other;
6323 // Compute the value type for each operand.
6324 switch (OpInfo.Type) {
6325 case InlineAsm::isOutput:
6326 // Indirect outputs just consume an argument.
6327 if (OpInfo.isIndirect) {
6328 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6332 // The return value of the call is this value. As such, there is no
6333 // corresponding argument.
6334 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6335 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6336 OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
6338 assert(ResNo == 0 && "Asm only has one result!");
6339 OpVT = TLI.getSimpleValueType(CS.getType());
6343 case InlineAsm::isInput:
6344 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6346 case InlineAsm::isClobber:
6351 // If this is an input or an indirect output, process the call argument.
6352 // BasicBlocks are labels, currently appearing only in asm's.
6353 if (OpInfo.CallOperandVal) {
6354 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6355 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6357 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6361 OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, DL).getSimpleVT();
6364 OpInfo.ConstraintVT = OpVT;
6366 // Indirect operand accesses access memory.
6367 if (OpInfo.isIndirect)
6370 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6371 TargetLowering::ConstraintType
6372 CType = TLI.getConstraintType(OpInfo.Codes[j]);
6373 if (CType == TargetLowering::C_Memory) {
6381 SDValue Chain, Flag;
6383 // We won't need to flush pending loads if this asm doesn't touch
6384 // memory and is nonvolatile.
6385 if (hasMemory || IA->hasSideEffects())
6388 Chain = DAG.getRoot();
6390 // Second pass over the constraints: compute which constraint option to use
6391 // and assign registers to constraints that want a specific physreg.
6392 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6393 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6395 // If this is an output operand with a matching input operand, look up the
6396 // matching input. If their types mismatch, e.g. one is an integer, the
6397 // other is floating point, or their sizes are different, flag it as an
6399 if (OpInfo.hasMatchingInput()) {
6400 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6402 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6403 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6404 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6405 OpInfo.ConstraintVT);
6406 std::pair<unsigned, const TargetRegisterClass*> InputRC =
6407 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
6408 Input.ConstraintVT);
6409 if ((OpInfo.ConstraintVT.isInteger() !=
6410 Input.ConstraintVT.isInteger()) ||
6411 (MatchRC.second != InputRC.second)) {
6412 report_fatal_error("Unsupported asm: input constraint"
6413 " with a matching output constraint of"
6414 " incompatible type!");
6416 Input.ConstraintVT = OpInfo.ConstraintVT;
6420 // Compute the constraint code and ConstraintType to use.
6421 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6423 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6424 OpInfo.Type == InlineAsm::isClobber)
6427 // If this is a memory input, and if the operand is not indirect, do what we
6428 // need to to provide an address for the memory input.
6429 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6430 !OpInfo.isIndirect) {
6431 assert((OpInfo.isMultipleAlternative ||
6432 (OpInfo.Type == InlineAsm::isInput)) &&
6433 "Can only indirectify direct input operands!");
6435 // Memory operands really want the address of the value. If we don't have
6436 // an indirect input, put it in the constpool if we can, otherwise spill
6437 // it to a stack slot.
6438 // TODO: This isn't quite right. We need to handle these according to
6439 // the addressing mode that the constraint wants. Also, this may take
6440 // an additional register for the computation and we don't want that
6443 // If the operand is a float, integer, or vector constant, spill to a
6444 // constant pool entry to get its address.
6445 const Value *OpVal = OpInfo.CallOperandVal;
6446 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6447 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6448 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6449 TLI.getPointerTy());
6451 // Otherwise, create a stack slot and emit a store to it before the
6453 Type *Ty = OpVal->getType();
6454 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
6455 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
6456 MachineFunction &MF = DAG.getMachineFunction();
6457 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6458 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
6459 Chain = DAG.getStore(Chain, getCurSDLoc(),
6460 OpInfo.CallOperand, StackSlot,
6461 MachinePointerInfo::getFixedStack(SSFI),
6463 OpInfo.CallOperand = StackSlot;
6466 // There is no longer a Value* corresponding to this operand.
6467 OpInfo.CallOperandVal = nullptr;
6469 // It is now an indirect operand.
6470 OpInfo.isIndirect = true;
6473 // If this constraint is for a specific register, allocate it before
6475 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6476 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6479 // Second pass - Loop over all of the operands, assigning virtual or physregs
6480 // to register class operands.
6481 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6482 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6484 // C_Register operands have already been allocated, Other/Memory don't need
6486 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6487 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6490 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6491 std::vector<SDValue> AsmNodeOperands;
6492 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6493 AsmNodeOperands.push_back(
6494 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6495 TLI.getPointerTy()));
6497 // If we have a !srcloc metadata node associated with it, we want to attach
6498 // this to the ultimately generated inline asm machineinstr. To do this, we
6499 // pass in the third operand as this (potentially null) inline asm MDNode.
6500 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6501 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6503 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6504 // bits as operand 3.
6505 unsigned ExtraInfo = 0;
6506 if (IA->hasSideEffects())
6507 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6508 if (IA->isAlignStack())
6509 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6510 // Set the asm dialect.
6511 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6513 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6514 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6515 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6517 // Compute the constraint code and ConstraintType to use.
6518 TLI.ComputeConstraintToUse(OpInfo, SDValue());
6520 // Ideally, we would only check against memory constraints. However, the
6521 // meaning of an other constraint can be target-specific and we can't easily
6522 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6523 // for other constriants as well.
6524 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6525 OpInfo.ConstraintType == TargetLowering::C_Other) {
6526 if (OpInfo.Type == InlineAsm::isInput)
6527 ExtraInfo |= InlineAsm::Extra_MayLoad;
6528 else if (OpInfo.Type == InlineAsm::isOutput)
6529 ExtraInfo |= InlineAsm::Extra_MayStore;
6530 else if (OpInfo.Type == InlineAsm::isClobber)
6531 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6535 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6536 TLI.getPointerTy()));
6538 // Loop over all of the inputs, copying the operand values into the
6539 // appropriate registers and processing the output regs.
6540 RegsForValue RetValRegs;
6542 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6543 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6545 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6546 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6548 switch (OpInfo.Type) {
6549 case InlineAsm::isOutput: {
6550 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6551 OpInfo.ConstraintType != TargetLowering::C_Register) {
6552 // Memory output, or 'other' output (e.g. 'X' constraint).
6553 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6555 // Add information to the INLINEASM node to know about this output.
6556 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6557 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6558 TLI.getPointerTy()));
6559 AsmNodeOperands.push_back(OpInfo.CallOperand);
6563 // Otherwise, this is a register or register class output.
6565 // Copy the output from the appropriate register. Find a register that
6567 if (OpInfo.AssignedRegs.Regs.empty()) {
6568 LLVMContext &Ctx = *DAG.getContext();
6569 Ctx.emitError(CS.getInstruction(),
6570 "couldn't allocate output register for constraint '" +
6571 Twine(OpInfo.ConstraintCode) + "'");
6575 // If this is an indirect operand, store through the pointer after the
6577 if (OpInfo.isIndirect) {
6578 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6579 OpInfo.CallOperandVal));
6581 // This is the result value of the call.
6582 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6583 // Concatenate this output onto the outputs list.
6584 RetValRegs.append(OpInfo.AssignedRegs);
6587 // Add information to the INLINEASM node to know that this register is
6590 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6591 ? InlineAsm::Kind_RegDefEarlyClobber
6592 : InlineAsm::Kind_RegDef,
6593 false, 0, DAG, AsmNodeOperands);
6596 case InlineAsm::isInput: {
6597 SDValue InOperandVal = OpInfo.CallOperand;
6599 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6600 // If this is required to match an output register we have already set,
6601 // just use its register.
6602 unsigned OperandNo = OpInfo.getMatchedOperand();
6604 // Scan until we find the definition we already emitted of this operand.
6605 // When we find it, create a RegsForValue operand.
6606 unsigned CurOp = InlineAsm::Op_FirstOperand;
6607 for (; OperandNo; --OperandNo) {
6608 // Advance to the next operand.
6610 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6611 assert((InlineAsm::isRegDefKind(OpFlag) ||
6612 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6613 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6614 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6618 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6619 if (InlineAsm::isRegDefKind(OpFlag) ||
6620 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6621 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6622 if (OpInfo.isIndirect) {
6623 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6624 LLVMContext &Ctx = *DAG.getContext();
6625 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6626 " don't know how to handle tied "
6627 "indirect register inputs");
6631 RegsForValue MatchedRegs;
6632 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6633 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6634 MatchedRegs.RegVTs.push_back(RegVT);
6635 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6636 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6638 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6639 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6641 LLVMContext &Ctx = *DAG.getContext();
6642 Ctx.emitError(CS.getInstruction(),
6643 "inline asm error: This value"
6644 " type register class is not natively supported!");
6648 // Use the produced MatchedRegs object to
6649 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6650 Chain, &Flag, CS.getInstruction());
6651 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6652 true, OpInfo.getMatchedOperand(),
6653 DAG, AsmNodeOperands);
6657 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6658 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6659 "Unexpected number of operands");
6660 // Add information to the INLINEASM node to know about this input.
6661 // See InlineAsm.h isUseOperandTiedToDef.
6662 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6663 OpInfo.getMatchedOperand());
6664 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6665 TLI.getPointerTy()));
6666 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6670 // Treat indirect 'X' constraint as memory.
6671 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6673 OpInfo.ConstraintType = TargetLowering::C_Memory;
6675 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6676 std::vector<SDValue> Ops;
6677 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6680 LLVMContext &Ctx = *DAG.getContext();
6681 Ctx.emitError(CS.getInstruction(),
6682 "invalid operand for inline asm constraint '" +
6683 Twine(OpInfo.ConstraintCode) + "'");
6687 // Add information to the INLINEASM node to know about this input.
6688 unsigned ResOpType =
6689 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6690 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6691 TLI.getPointerTy()));
6692 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6696 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6697 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6698 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6699 "Memory operands expect pointer values");
6701 // Add information to the INLINEASM node to know about this input.
6702 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6703 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6704 TLI.getPointerTy()));
6705 AsmNodeOperands.push_back(InOperandVal);
6709 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6710 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6711 "Unknown constraint type!");
6713 // TODO: Support this.
6714 if (OpInfo.isIndirect) {
6715 LLVMContext &Ctx = *DAG.getContext();
6716 Ctx.emitError(CS.getInstruction(),
6717 "Don't know how to handle indirect register inputs yet "
6718 "for constraint '" +
6719 Twine(OpInfo.ConstraintCode) + "'");
6723 // Copy the input into the appropriate registers.
6724 if (OpInfo.AssignedRegs.Regs.empty()) {
6725 LLVMContext &Ctx = *DAG.getContext();
6726 Ctx.emitError(CS.getInstruction(),
6727 "couldn't allocate input reg for constraint '" +
6728 Twine(OpInfo.ConstraintCode) + "'");
6732 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6733 Chain, &Flag, CS.getInstruction());
6735 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6736 DAG, AsmNodeOperands);
6739 case InlineAsm::isClobber: {
6740 // Add the clobbered value to the operand list, so that the register
6741 // allocator is aware that the physreg got clobbered.
6742 if (!OpInfo.AssignedRegs.Regs.empty())
6743 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6751 // Finish up input operands. Set the input chain and add the flag last.
6752 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6753 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6755 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6756 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6757 Flag = Chain.getValue(1);
6759 // If this asm returns a register value, copy the result from that register
6760 // and set it as the value of the call.
6761 if (!RetValRegs.Regs.empty()) {
6762 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6763 Chain, &Flag, CS.getInstruction());
6765 // FIXME: Why don't we do this for inline asms with MRVs?
6766 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6767 EVT ResultType = TLI.getValueType(CS.getType());
6769 // If any of the results of the inline asm is a vector, it may have the
6770 // wrong width/num elts. This can happen for register classes that can
6771 // contain multiple different value types. The preg or vreg allocated may
6772 // not have the same VT as was expected. Convert it to the right type
6773 // with bit_convert.
6774 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6775 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6778 } else if (ResultType != Val.getValueType() &&
6779 ResultType.isInteger() && Val.getValueType().isInteger()) {
6780 // If a result value was tied to an input value, the computed result may
6781 // have a wider width than the expected result. Extract the relevant
6783 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6786 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6789 setValue(CS.getInstruction(), Val);
6790 // Don't need to use this as a chain in this case.
6791 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6795 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6797 // Process indirect outputs, first output all of the flagged copies out of
6799 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6800 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6801 const Value *Ptr = IndirectStoresToEmit[i].second;
6802 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6804 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6807 // Emit the non-flagged stores from the physregs.
6808 SmallVector<SDValue, 8> OutChains;
6809 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6810 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6811 StoresToEmit[i].first,
6812 getValue(StoresToEmit[i].second),
6813 MachinePointerInfo(StoresToEmit[i].second),
6815 OutChains.push_back(Val);
6818 if (!OutChains.empty())
6819 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6824 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6825 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6826 MVT::Other, getRoot(),
6827 getValue(I.getArgOperand(0)),
6828 DAG.getSrcValue(I.getArgOperand(0))));
6831 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6832 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6833 const DataLayout &DL = *TLI.getDataLayout();
6834 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurSDLoc(),
6835 getRoot(), getValue(I.getOperand(0)),
6836 DAG.getSrcValue(I.getOperand(0)),
6837 DL.getABITypeAlignment(I.getType()));
6839 DAG.setRoot(V.getValue(1));
6842 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6843 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6844 MVT::Other, getRoot(),
6845 getValue(I.getArgOperand(0)),
6846 DAG.getSrcValue(I.getArgOperand(0))));
6849 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6850 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6851 MVT::Other, getRoot(),
6852 getValue(I.getArgOperand(0)),
6853 getValue(I.getArgOperand(1)),
6854 DAG.getSrcValue(I.getArgOperand(0)),
6855 DAG.getSrcValue(I.getArgOperand(1))));
6858 /// \brief Lower an argument list according to the target calling convention.
6860 /// \return A tuple of <return-value, token-chain>
6862 /// This is a helper for lowering intrinsics that follow a target calling
6863 /// convention or require stack pointer adjustment. Only a subset of the
6864 /// intrinsic's operands need to participate in the calling convention.
6865 std::pair<SDValue, SDValue>
6866 SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
6867 unsigned NumArgs, SDValue Callee,
6869 MachineBasicBlock *LandingPad) {
6870 TargetLowering::ArgListTy Args;
6871 Args.reserve(NumArgs);
6873 // Populate the argument list.
6874 // Attributes for args start at offset 1, after the return attribute.
6875 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6876 ArgI != ArgE; ++ArgI) {
6877 const Value *V = CS->getOperand(ArgI);
6879 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6881 TargetLowering::ArgListEntry Entry;
6882 Entry.Node = getValue(V);
6883 Entry.Ty = V->getType();
6884 Entry.setAttributes(&CS, AttrI);
6885 Args.push_back(Entry);
6888 Type *retTy = UseVoidTy ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
6889 TargetLowering::CallLoweringInfo CLI(DAG);
6890 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
6891 .setCallee(CS.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
6892 .setDiscardResult(CS->use_empty());
6894 return lowerInvokable(CLI, LandingPad);
6897 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6898 /// or patchpoint target node's operand list.
6900 /// Constants are converted to TargetConstants purely as an optimization to
6901 /// avoid constant materialization and register allocation.
6903 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6904 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6905 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6906 /// address materialization and register allocation, but may also be required
6907 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6908 /// alloca in the entry block, then the runtime may assume that the alloca's
6909 /// StackMap location can be read immediately after compilation and that the
6910 /// location is valid at any point during execution (this is similar to the
6911 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6912 /// only available in a register, then the runtime would need to trap when
6913 /// execution reaches the StackMap in order to read the alloca's location.
6914 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
6915 SmallVectorImpl<SDValue> &Ops,
6916 SelectionDAGBuilder &Builder) {
6917 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6918 SDValue OpVal = Builder.getValue(CS.getArgument(i));
6919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6921 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6923 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
6924 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6925 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6927 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
6929 Ops.push_back(OpVal);
6933 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6934 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6935 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6936 // [live variables...])
6938 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6940 SDValue Chain, InFlag, Callee, NullPtr;
6941 SmallVector<SDValue, 32> Ops;
6943 SDLoc DL = getCurSDLoc();
6944 Callee = getValue(CI.getCalledValue());
6945 NullPtr = DAG.getIntPtrConstant(0, true);
6947 // The stackmap intrinsic only records the live variables (the arguemnts
6948 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6949 // intrinsic, this won't be lowered to a function call. This means we don't
6950 // have to worry about calling conventions and target specific lowering code.
6951 // Instead we perform the call lowering right here.
6953 // chain, flag = CALLSEQ_START(chain, 0)
6954 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6955 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6957 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
6958 InFlag = Chain.getValue(1);
6960 // Add the <id> and <numBytes> constants.
6961 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6962 Ops.push_back(DAG.getTargetConstant(
6963 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
6964 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6965 Ops.push_back(DAG.getTargetConstant(
6966 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
6968 // Push live variables for the stack map.
6969 addStackMapLiveVars(&CI, 2, Ops, *this);
6971 // We are not pushing any register mask info here on the operands list,
6972 // because the stackmap doesn't clobber anything.
6974 // Push the chain and the glue flag.
6975 Ops.push_back(Chain);
6976 Ops.push_back(InFlag);
6978 // Create the STACKMAP node.
6979 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6980 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
6981 Chain = SDValue(SM, 0);
6982 InFlag = Chain.getValue(1);
6984 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
6986 // Stackmaps don't generate values, so nothing goes into the NodeMap.
6988 // Set the root to the target-lowered call chain.
6991 // Inform the Frame Information that we have a stackmap in this function.
6992 FuncInfo.MF->getFrameInfo()->setHasStackMap();
6995 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6996 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
6997 MachineBasicBlock *LandingPad) {
6998 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7003 // [live variables...])
7005 CallingConv::ID CC = CS.getCallingConv();
7006 bool IsAnyRegCC = CC == CallingConv::AnyReg;
7007 bool HasDef = !CS->getType()->isVoidTy();
7008 SDValue Callee = getValue(CS->getOperand(2)); // <target>
7010 // Get the real number of arguments participating in the call <numArgs>
7011 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7012 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7014 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7015 // Intrinsics include all meta-operands up to but not including CC.
7016 unsigned NumMetaOpers = PatchPointOpers::CCPos;
7017 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7018 "Not enough arguments provided to the patchpoint intrinsic");
7020 // For AnyRegCC the arguments are lowered later on manually.
7021 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7022 std::pair<SDValue, SDValue> Result =
7023 lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC,
7026 SDNode *CallEnd = Result.second.getNode();
7027 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7028 CallEnd = CallEnd->getOperand(0).getNode();
7030 /// Get a call instruction from the call sequence chain.
7031 /// Tail calls are not allowed.
7032 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7033 "Expected a callseq node.");
7034 SDNode *Call = CallEnd->getOperand(0).getNode();
7035 bool HasGlue = Call->getGluedNode();
7037 // Replace the target specific call node with the patchable intrinsic.
7038 SmallVector<SDValue, 8> Ops;
7040 // Add the <id> and <numBytes> constants.
7041 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7042 Ops.push_back(DAG.getTargetConstant(
7043 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
7044 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7045 Ops.push_back(DAG.getTargetConstant(
7046 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7048 // Assume that the Callee is a constant address.
7049 // FIXME: handle function symbols in the future.
7051 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
7052 /*isTarget=*/true));
7054 // Adjust <numArgs> to account for any arguments that have been passed on the
7056 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7057 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7058 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7059 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
7061 // Add the calling convention
7062 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
7064 // Add the arguments we omitted previously. The register allocator should
7065 // place these in any free register.
7067 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7068 Ops.push_back(getValue(CS.getArgument(i)));
7070 // Push the arguments from the call instruction up to the register mask.
7071 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7072 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
7075 // Push live variables for the stack map.
7076 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, Ops, *this);
7078 // Push the register mask info.
7080 Ops.push_back(*(Call->op_end()-2));
7082 Ops.push_back(*(Call->op_end()-1));
7084 // Push the chain (this is originally the first operand of the call, but
7085 // becomes now the last or second to last operand).
7086 Ops.push_back(*(Call->op_begin()));
7088 // Push the glue flag (last operand).
7090 Ops.push_back(*(Call->op_end()-1));
7093 if (IsAnyRegCC && HasDef) {
7094 // Create the return types based on the intrinsic definition
7095 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7096 SmallVector<EVT, 3> ValueVTs;
7097 ComputeValueVTs(TLI, CS->getType(), ValueVTs);
7098 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7100 // There is always a chain and a glue type at the end
7101 ValueVTs.push_back(MVT::Other);
7102 ValueVTs.push_back(MVT::Glue);
7103 NodeTys = DAG.getVTList(ValueVTs);
7105 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7107 // Replace the target specific call node with a PATCHPOINT node.
7108 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7109 getCurSDLoc(), NodeTys, Ops);
7111 // Update the NodeMap.
7114 setValue(CS.getInstruction(), SDValue(MN, 0));
7116 setValue(CS.getInstruction(), Result.first);
7119 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7120 // call sequence. Furthermore the location of the chain and glue can change
7121 // when the AnyReg calling convention is used and the intrinsic returns a
7123 if (IsAnyRegCC && HasDef) {
7124 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7125 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7126 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7128 DAG.ReplaceAllUsesWith(Call, MN);
7129 DAG.DeleteNode(Call);
7131 // Inform the Frame Information that we have a patchpoint in this function.
7132 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
7135 /// Returns an AttributeSet representing the attributes applied to the return
7136 /// value of the given call.
7137 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7138 SmallVector<Attribute::AttrKind, 2> Attrs;
7140 Attrs.push_back(Attribute::SExt);
7142 Attrs.push_back(Attribute::ZExt);
7144 Attrs.push_back(Attribute::InReg);
7146 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7150 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7151 /// implementation, which just calls LowerCall.
7152 /// FIXME: When all targets are
7153 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7154 std::pair<SDValue, SDValue>
7155 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7156 // Handle the incoming return values from the call.
7158 Type *OrigRetTy = CLI.RetTy;
7159 SmallVector<EVT, 4> RetTys;
7160 SmallVector<uint64_t, 4> Offsets;
7161 ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
7163 SmallVector<ISD::OutputArg, 4> Outs;
7164 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
7166 bool CanLowerReturn =
7167 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7168 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7170 SDValue DemoteStackSlot;
7171 int DemoteStackIdx = -100;
7172 if (!CanLowerReturn) {
7173 // FIXME: equivalent assert?
7174 // assert(!CS.hasInAllocaArgument() &&
7175 // "sret demotion is incompatible with inalloca");
7176 uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
7177 unsigned Align = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
7178 MachineFunction &MF = CLI.DAG.getMachineFunction();
7179 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7180 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7182 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
7184 Entry.Node = DemoteStackSlot;
7185 Entry.Ty = StackSlotPtrType;
7186 Entry.isSExt = false;
7187 Entry.isZExt = false;
7188 Entry.isInReg = false;
7189 Entry.isSRet = true;
7190 Entry.isNest = false;
7191 Entry.isByVal = false;
7192 Entry.isReturned = false;
7193 Entry.Alignment = Align;
7194 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7195 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7197 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7199 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7200 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7201 for (unsigned i = 0; i != NumRegs; ++i) {
7202 ISD::InputArg MyFlags;
7203 MyFlags.VT = RegisterVT;
7205 MyFlags.Used = CLI.IsReturnValueUsed;
7207 MyFlags.Flags.setSExt();
7209 MyFlags.Flags.setZExt();
7211 MyFlags.Flags.setInReg();
7212 CLI.Ins.push_back(MyFlags);
7217 // Handle all of the outgoing arguments.
7219 CLI.OutVals.clear();
7220 ArgListTy &Args = CLI.getArgs();
7221 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7222 SmallVector<EVT, 4> ValueVTs;
7223 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7224 Type *FinalType = Args[i].Ty;
7225 if (Args[i].isByVal)
7226 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7227 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7228 FinalType, CLI.CallConv, CLI.IsVarArg);
7229 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7231 EVT VT = ValueVTs[Value];
7232 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7233 SDValue Op = SDValue(Args[i].Node.getNode(),
7234 Args[i].Node.getResNo() + Value);
7235 ISD::ArgFlagsTy Flags;
7236 unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
7242 if (Args[i].isInReg)
7246 if (Args[i].isByVal)
7248 if (Args[i].isInAlloca) {
7249 Flags.setInAlloca();
7250 // Set the byval flag for CCAssignFn callbacks that don't know about
7251 // inalloca. This way we can know how many bytes we should've allocated
7252 // and how many bytes a callee cleanup function will pop. If we port
7253 // inalloca to more targets, we'll have to add custom inalloca handling
7254 // in the various CC lowering callbacks.
7257 if (Args[i].isByVal || Args[i].isInAlloca) {
7258 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7259 Type *ElementTy = Ty->getElementType();
7260 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
7261 // For ByVal, alignment should come from FE. BE will guess if this
7262 // info is not there but there are cases it cannot get right.
7263 unsigned FrameAlign;
7264 if (Args[i].Alignment)
7265 FrameAlign = Args[i].Alignment;
7267 FrameAlign = getByValTypeAlignment(ElementTy);
7268 Flags.setByValAlign(FrameAlign);
7272 if (NeedsRegBlock) {
7273 Flags.setInConsecutiveRegs();
7274 if (Value == NumValues - 1)
7275 Flags.setInConsecutiveRegsLast();
7277 Flags.setOrigAlign(OriginalAlignment);
7279 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7280 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7281 SmallVector<SDValue, 4> Parts(NumParts);
7282 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7285 ExtendKind = ISD::SIGN_EXTEND;
7286 else if (Args[i].isZExt)
7287 ExtendKind = ISD::ZERO_EXTEND;
7289 // Conservatively only handle 'returned' on non-vectors for now
7290 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7291 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7292 "unexpected use of 'returned'");
7293 // Before passing 'returned' to the target lowering code, ensure that
7294 // either the register MVT and the actual EVT are the same size or that
7295 // the return value and argument are extended in the same way; in these
7296 // cases it's safe to pass the argument register value unchanged as the
7297 // return register value (although it's at the target's option whether
7299 // TODO: allow code generation to take advantage of partially preserved
7300 // registers rather than clobbering the entire register when the
7301 // parameter extension method is not compatible with the return
7303 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7304 (ExtendKind != ISD::ANY_EXTEND &&
7305 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7306 Flags.setReturned();
7309 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7310 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
7312 for (unsigned j = 0; j != NumParts; ++j) {
7313 // if it isn't first piece, alignment must be 1
7314 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7315 i < CLI.NumFixedArgs,
7316 i, j*Parts[j].getValueType().getStoreSize());
7317 if (NumParts > 1 && j == 0)
7318 MyFlags.Flags.setSplit();
7320 MyFlags.Flags.setOrigAlign(1);
7322 CLI.Outs.push_back(MyFlags);
7323 CLI.OutVals.push_back(Parts[j]);
7328 SmallVector<SDValue, 4> InVals;
7329 CLI.Chain = LowerCall(CLI, InVals);
7331 // Verify that the target's LowerCall behaved as expected.
7332 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7333 "LowerCall didn't return a valid chain!");
7334 assert((!CLI.IsTailCall || InVals.empty()) &&
7335 "LowerCall emitted a return value for a tail call!");
7336 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7337 "LowerCall didn't emit the correct number of values!");
7339 // For a tail call, the return value is merely live-out and there aren't
7340 // any nodes in the DAG representing it. Return a special value to
7341 // indicate that a tail call has been emitted and no more Instructions
7342 // should be processed in the current block.
7343 if (CLI.IsTailCall) {
7344 CLI.DAG.setRoot(CLI.Chain);
7345 return std::make_pair(SDValue(), SDValue());
7348 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7349 assert(InVals[i].getNode() &&
7350 "LowerCall emitted a null value!");
7351 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7352 "LowerCall emitted a value with the wrong type!");
7355 SmallVector<SDValue, 4> ReturnValues;
7356 if (!CanLowerReturn) {
7357 // The instruction result is the result of loading from the
7358 // hidden sret parameter.
7359 SmallVector<EVT, 1> PVTs;
7360 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
7362 ComputeValueVTs(*this, PtrRetTy, PVTs);
7363 assert(PVTs.size() == 1 && "Pointers should fit in one register");
7364 EVT PtrVT = PVTs[0];
7366 unsigned NumValues = RetTys.size();
7367 ReturnValues.resize(NumValues);
7368 SmallVector<SDValue, 4> Chains(NumValues);
7370 for (unsigned i = 0; i < NumValues; ++i) {
7371 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7372 CLI.DAG.getConstant(Offsets[i], PtrVT));
7373 SDValue L = CLI.DAG.getLoad(
7374 RetTys[i], CLI.DL, CLI.Chain, Add,
7375 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
7377 ReturnValues[i] = L;
7378 Chains[i] = L.getValue(1);
7381 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7383 // Collect the legal value parts into potentially illegal values
7384 // that correspond to the original function's return values.
7385 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7387 AssertOp = ISD::AssertSext;
7388 else if (CLI.RetZExt)
7389 AssertOp = ISD::AssertZext;
7390 unsigned CurReg = 0;
7391 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7393 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7394 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7396 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7397 NumRegs, RegisterVT, VT, nullptr,
7402 // For a function returning void, there is no return value. We can't create
7403 // such a node, so we just return a null return value in that case. In
7404 // that case, nothing will actually look at the value.
7405 if (ReturnValues.empty())
7406 return std::make_pair(SDValue(), CLI.Chain);
7409 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7410 CLI.DAG.getVTList(RetTys), ReturnValues);
7411 return std::make_pair(Res, CLI.Chain);
7414 void TargetLowering::LowerOperationWrapper(SDNode *N,
7415 SmallVectorImpl<SDValue> &Results,
7416 SelectionDAG &DAG) const {
7417 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
7419 Results.push_back(Res);
7422 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7423 llvm_unreachable("LowerOperation not implemented for this target!");
7427 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7428 SDValue Op = getNonRegisterValue(V);
7429 assert((Op.getOpcode() != ISD::CopyFromReg ||
7430 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7431 "Copy from a reg to the same reg!");
7432 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7435 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
7436 SDValue Chain = DAG.getEntryNode();
7438 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7439 FuncInfo.PreferredExtendType.end())
7441 : FuncInfo.PreferredExtendType[V];
7442 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7443 PendingExports.push_back(Chain);
7446 #include "llvm/CodeGen/SelectionDAGISel.h"
7448 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7449 /// entry block, return true. This includes arguments used by switches, since
7450 /// the switch may expand into multiple basic blocks.
7451 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7452 // With FastISel active, we may be splitting blocks, so force creation
7453 // of virtual registers for all non-dead arguments.
7455 return A->use_empty();
7457 const BasicBlock *Entry = A->getParent()->begin();
7458 for (const User *U : A->users())
7459 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7460 return false; // Use not in entry block.
7465 void SelectionDAGISel::LowerArguments(const Function &F) {
7466 SelectionDAG &DAG = SDB->DAG;
7467 SDLoc dl = SDB->getCurSDLoc();
7468 const DataLayout *DL = TLI->getDataLayout();
7469 SmallVector<ISD::InputArg, 16> Ins;
7471 if (!FuncInfo->CanLowerReturn) {
7472 // Put in an sret pointer parameter before all the other parameters.
7473 SmallVector<EVT, 1> ValueVTs;
7474 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7476 // NOTE: Assuming that a pointer will never break down to more than one VT
7478 ISD::ArgFlagsTy Flags;
7480 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7481 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
7482 Ins.push_back(RetArg);
7485 // Set up the incoming argument description vector.
7487 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7488 I != E; ++I, ++Idx) {
7489 SmallVector<EVT, 4> ValueVTs;
7490 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7491 bool isArgValueUsed = !I->use_empty();
7492 unsigned PartBase = 0;
7493 Type *FinalType = I->getType();
7494 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7495 FinalType = cast<PointerType>(FinalType)->getElementType();
7496 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7497 FinalType, F.getCallingConv(), F.isVarArg());
7498 for (unsigned Value = 0, NumValues = ValueVTs.size();
7499 Value != NumValues; ++Value) {
7500 EVT VT = ValueVTs[Value];
7501 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7502 ISD::ArgFlagsTy Flags;
7503 unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
7505 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7507 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7509 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7511 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7513 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7515 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7516 Flags.setInAlloca();
7517 // Set the byval flag for CCAssignFn callbacks that don't know about
7518 // inalloca. This way we can know how many bytes we should've allocated
7519 // and how many bytes a callee cleanup function will pop. If we port
7520 // inalloca to more targets, we'll have to add custom inalloca handling
7521 // in the various CC lowering callbacks.
7524 if (Flags.isByVal() || Flags.isInAlloca()) {
7525 PointerType *Ty = cast<PointerType>(I->getType());
7526 Type *ElementTy = Ty->getElementType();
7527 Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
7528 // For ByVal, alignment should be passed from FE. BE will guess if
7529 // this info is not there but there are cases it cannot get right.
7530 unsigned FrameAlign;
7531 if (F.getParamAlignment(Idx))
7532 FrameAlign = F.getParamAlignment(Idx);
7534 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7535 Flags.setByValAlign(FrameAlign);
7537 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7539 if (NeedsRegBlock) {
7540 Flags.setInConsecutiveRegs();
7541 if (Value == NumValues - 1)
7542 Flags.setInConsecutiveRegsLast();
7544 Flags.setOrigAlign(OriginalAlignment);
7546 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7547 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7548 for (unsigned i = 0; i != NumRegs; ++i) {
7549 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7550 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7551 if (NumRegs > 1 && i == 0)
7552 MyFlags.Flags.setSplit();
7553 // if it isn't first piece, alignment must be 1
7555 MyFlags.Flags.setOrigAlign(1);
7556 Ins.push_back(MyFlags);
7558 PartBase += VT.getStoreSize();
7562 // Call the target to set up the argument values.
7563 SmallVector<SDValue, 8> InVals;
7564 SDValue NewRoot = TLI->LowerFormalArguments(
7565 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7567 // Verify that the target's LowerFormalArguments behaved as expected.
7568 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7569 "LowerFormalArguments didn't return a valid chain!");
7570 assert(InVals.size() == Ins.size() &&
7571 "LowerFormalArguments didn't emit the correct number of values!");
7573 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7574 assert(InVals[i].getNode() &&
7575 "LowerFormalArguments emitted a null value!");
7576 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7577 "LowerFormalArguments emitted a value with the wrong type!");
7581 // Update the DAG with the new chain value resulting from argument lowering.
7582 DAG.setRoot(NewRoot);
7584 // Set up the argument values.
7587 if (!FuncInfo->CanLowerReturn) {
7588 // Create a virtual register for the sret pointer, and put in a copy
7589 // from the sret argument into it.
7590 SmallVector<EVT, 1> ValueVTs;
7591 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7592 MVT VT = ValueVTs[0].getSimpleVT();
7593 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7594 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7595 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7596 RegVT, VT, nullptr, AssertOp);
7598 MachineFunction& MF = SDB->DAG.getMachineFunction();
7599 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7600 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7601 FuncInfo->DemoteRegister = SRetReg;
7603 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7604 DAG.setRoot(NewRoot);
7606 // i indexes lowered arguments. Bump it past the hidden sret argument.
7607 // Idx indexes LLVM arguments. Don't touch it.
7611 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7613 SmallVector<SDValue, 4> ArgValues;
7614 SmallVector<EVT, 4> ValueVTs;
7615 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7616 unsigned NumValues = ValueVTs.size();
7618 // If this argument is unused then remember its value. It is used to generate
7619 // debugging information.
7620 if (I->use_empty() && NumValues) {
7621 SDB->setUnusedArgValue(I, InVals[i]);
7623 // Also remember any frame index for use in FastISel.
7624 if (FrameIndexSDNode *FI =
7625 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7626 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7629 for (unsigned Val = 0; Val != NumValues; ++Val) {
7630 EVT VT = ValueVTs[Val];
7631 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7632 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7634 if (!I->use_empty()) {
7635 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7636 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7637 AssertOp = ISD::AssertSext;
7638 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7639 AssertOp = ISD::AssertZext;
7641 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7642 NumParts, PartVT, VT,
7643 nullptr, AssertOp));
7649 // We don't need to do anything else for unused arguments.
7650 if (ArgValues.empty())
7653 // Note down frame index.
7654 if (FrameIndexSDNode *FI =
7655 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7656 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7658 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7659 SDB->getCurSDLoc());
7661 SDB->setValue(I, Res);
7662 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7663 if (LoadSDNode *LNode =
7664 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7665 if (FrameIndexSDNode *FI =
7666 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7667 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7670 // If this argument is live outside of the entry block, insert a copy from
7671 // wherever we got it to the vreg that other BB's will reference it as.
7672 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7673 // If we can, though, try to skip creating an unnecessary vreg.
7674 // FIXME: This isn't very clean... it would be nice to make this more
7675 // general. It's also subtly incompatible with the hacks FastISel
7677 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7678 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7679 FuncInfo->ValueMap[I] = Reg;
7683 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7684 FuncInfo->InitializeRegForValue(I);
7685 SDB->CopyToExportRegsIfNeeded(I);
7689 assert(i == InVals.size() && "Argument register count mismatch!");
7691 // Finally, if the target has anything special to do, allow it to do so.
7692 // FIXME: this should insert code into the DAG!
7693 EmitFunctionEntryCode();
7696 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7697 /// ensure constants are generated when needed. Remember the virtual registers
7698 /// that need to be added to the Machine PHI nodes as input. We cannot just
7699 /// directly add them, because expansion might result in multiple MBB's for one
7700 /// BB. As such, the start of the BB might correspond to a different MBB than
7704 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7705 const TerminatorInst *TI = LLVMBB->getTerminator();
7707 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7709 // Check successor nodes' PHI nodes that expect a constant to be available
7711 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7712 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7713 if (!isa<PHINode>(SuccBB->begin())) continue;
7714 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7716 // If this terminator has multiple identical successors (common for
7717 // switches), only handle each succ once.
7718 if (!SuccsHandled.insert(SuccMBB).second)
7721 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7723 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7724 // nodes and Machine PHI nodes, but the incoming operands have not been
7726 for (BasicBlock::const_iterator I = SuccBB->begin();
7727 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7728 // Ignore dead phi's.
7729 if (PN->use_empty()) continue;
7732 if (PN->getType()->isEmptyTy())
7736 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7738 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7739 unsigned &RegOut = ConstantsOut[C];
7741 RegOut = FuncInfo.CreateRegs(C->getType());
7742 CopyValueToVirtualRegister(C, RegOut);
7746 DenseMap<const Value *, unsigned>::iterator I =
7747 FuncInfo.ValueMap.find(PHIOp);
7748 if (I != FuncInfo.ValueMap.end())
7751 assert(isa<AllocaInst>(PHIOp) &&
7752 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7753 "Didn't codegen value into a register!??");
7754 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7755 CopyValueToVirtualRegister(PHIOp, Reg);
7759 // Remember that this register needs to added to the machine PHI node as
7760 // the input for this MBB.
7761 SmallVector<EVT, 4> ValueVTs;
7762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7763 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
7764 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7765 EVT VT = ValueVTs[vti];
7766 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7767 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7768 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7769 Reg += NumRegisters;
7774 ConstantsOut.clear();
7777 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7780 SelectionDAGBuilder::StackProtectorDescriptor::
7781 AddSuccessorMBB(const BasicBlock *BB,
7782 MachineBasicBlock *ParentMBB,
7784 MachineBasicBlock *SuccMBB) {
7785 // If SuccBB has not been created yet, create it.
7787 MachineFunction *MF = ParentMBB->getParent();
7788 MachineFunction::iterator BBI = ParentMBB;
7789 SuccMBB = MF->CreateMachineBasicBlock(BB);
7790 MF->insert(++BBI, SuccMBB);
7792 // Add it as a successor of ParentMBB.
7793 ParentMBB->addSuccessor(
7794 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));