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 #define DEBUG_TYPE "isel"
15 #include "SDNodeDbgValue.h"
16 #include "SelectionDAGBuilder.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/IntrinsicInst.h"
31 #include "llvm/LLVMContext.h"
32 #include "llvm/Module.h"
33 #include "llvm/CodeGen/Analysis.h"
34 #include "llvm/CodeGen/FastISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCStrategy.h"
37 #include "llvm/CodeGen/GCMetadata.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineJumpTableInfo.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/PseudoSourceValue.h"
45 #include "llvm/CodeGen/SelectionDAG.h"
46 #include "llvm/Analysis/DebugInfo.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetIntrinsicInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/raw_ostream.h"
61 /// LimitFloatPrecision - Generate low-precision inline sequences for
62 /// some float libcalls (6, 8 or 12 bits).
63 static unsigned LimitFloatPrecision;
65 static cl::opt<unsigned, true>
66 LimitFPPrecision("limit-float-precision",
67 cl::desc("Generate low-precision inline sequences "
68 "for some float libcalls"),
69 cl::location(LimitFloatPrecision),
72 // Limit the width of DAG chains. This is important in general to prevent
73 // prevent DAG-based analysis from blowing up. For example, alias analysis and
74 // load clustering may not complete in reasonable time. It is difficult to
75 // recognize and avoid this situation within each individual analysis, and
76 // future analyses are likely to have the same behavior. Limiting DAG width is
77 // the safe approach, and will be especially important with global DAGs.
79 // MaxParallelChains default is arbitrarily high to avoid affecting
80 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
81 // sequence over this should have been converted to llvm.memcpy by the
82 // frontend. It easy to induce this behavior with .ll code such as:
83 // %buffer = alloca [4096 x i8]
84 // %data = load [4096 x i8]* %argPtr
85 // store [4096 x i8] %data, [4096 x i8]* %buffer
86 static const unsigned MaxParallelChains = 64;
88 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
89 const SDValue *Parts, unsigned NumParts,
90 EVT PartVT, EVT ValueVT);
92 /// getCopyFromParts - Create a value that contains the specified legal parts
93 /// combined into the value they represent. If the parts combine to a type
94 /// larger then ValueVT then AssertOp can be used to specify whether the extra
95 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
96 /// (ISD::AssertSext).
97 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL,
99 unsigned NumParts, EVT PartVT, EVT ValueVT,
100 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
101 if (ValueVT.isVector())
102 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT);
104 assert(NumParts > 0 && "No parts to assemble!");
105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
106 SDValue Val = Parts[0];
109 // Assemble the value from multiple parts.
110 if (ValueVT.isInteger()) {
111 unsigned PartBits = PartVT.getSizeInBits();
112 unsigned ValueBits = ValueVT.getSizeInBits();
114 // Assemble the power of 2 part.
115 unsigned RoundParts = NumParts & (NumParts - 1) ?
116 1 << Log2_32(NumParts) : NumParts;
117 unsigned RoundBits = PartBits * RoundParts;
118 EVT RoundVT = RoundBits == ValueBits ?
119 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
122 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
124 if (RoundParts > 2) {
125 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
127 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
128 RoundParts / 2, PartVT, HalfVT);
130 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
131 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
134 if (TLI.isBigEndian())
137 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
139 if (RoundParts < NumParts) {
140 // Assemble the trailing non-power-of-2 part.
141 unsigned OddParts = NumParts - RoundParts;
142 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
143 Hi = getCopyFromParts(DAG, DL,
144 Parts + RoundParts, OddParts, PartVT, OddVT);
146 // Combine the round and odd parts.
148 if (TLI.isBigEndian())
150 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
151 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
152 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
153 DAG.getConstant(Lo.getValueType().getSizeInBits(),
154 TLI.getPointerTy()));
155 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
156 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
158 } else if (PartVT.isFloatingPoint()) {
159 // FP split into multiple FP parts (for ppcf128)
160 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
163 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
164 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
165 if (TLI.isBigEndian())
167 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
169 // FP split into integer parts (soft fp)
170 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
171 !PartVT.isVector() && "Unexpected split");
172 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
173 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT);
177 // There is now one part, held in Val. Correct it to match ValueVT.
178 PartVT = Val.getValueType();
180 if (PartVT == ValueVT)
183 if (PartVT.isInteger() && ValueVT.isInteger()) {
184 if (ValueVT.bitsLT(PartVT)) {
185 // For a truncate, see if we have any information to
186 // indicate whether the truncated bits will always be
187 // zero or sign-extension.
188 if (AssertOp != ISD::DELETED_NODE)
189 Val = DAG.getNode(AssertOp, DL, PartVT, Val,
190 DAG.getValueType(ValueVT));
191 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
193 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
196 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
197 // FP_ROUND's are always exact here.
198 if (ValueVT.bitsLT(Val.getValueType()))
199 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
200 DAG.getIntPtrConstant(1));
202 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
205 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
206 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
208 llvm_unreachable("Unknown mismatch!");
212 /// getCopyFromParts - Create a value that contains the specified legal parts
213 /// combined into the value they represent. If the parts combine to a type
214 /// larger then ValueVT then AssertOp can be used to specify whether the extra
215 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
216 /// (ISD::AssertSext).
217 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
218 const SDValue *Parts, unsigned NumParts,
219 EVT PartVT, EVT ValueVT) {
220 assert(ValueVT.isVector() && "Not a vector value");
221 assert(NumParts > 0 && "No parts to assemble!");
222 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
223 SDValue Val = Parts[0];
225 // Handle a multi-element vector.
227 EVT IntermediateVT, RegisterVT;
228 unsigned NumIntermediates;
230 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
231 NumIntermediates, RegisterVT);
232 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
233 NumParts = NumRegs; // Silence a compiler warning.
234 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
235 assert(RegisterVT == Parts[0].getValueType() &&
236 "Part type doesn't match part!");
238 // Assemble the parts into intermediate operands.
239 SmallVector<SDValue, 8> Ops(NumIntermediates);
240 if (NumIntermediates == NumParts) {
241 // If the register was not expanded, truncate or copy the value,
243 for (unsigned i = 0; i != NumParts; ++i)
244 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
245 PartVT, IntermediateVT);
246 } else if (NumParts > 0) {
247 // If the intermediate type was expanded, build the intermediate
248 // operands from the parts.
249 assert(NumParts % NumIntermediates == 0 &&
250 "Must expand into a divisible number of parts!");
251 unsigned Factor = NumParts / NumIntermediates;
252 for (unsigned i = 0; i != NumIntermediates; ++i)
253 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
254 PartVT, IntermediateVT);
257 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
258 // intermediate operands.
259 Val = DAG.getNode(IntermediateVT.isVector() ?
260 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
261 ValueVT, &Ops[0], NumIntermediates);
264 // There is now one part, held in Val. Correct it to match ValueVT.
265 PartVT = Val.getValueType();
267 if (PartVT == ValueVT)
270 if (PartVT.isVector()) {
271 // If the element type of the source/dest vectors are the same, but the
272 // parts vector has more elements than the value vector, then we have a
273 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
275 if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
276 assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
277 "Cannot narrow, it would be a lossy transformation");
278 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
279 DAG.getIntPtrConstant(0));
282 // Vector/Vector bitcast.
283 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
286 assert(ValueVT.getVectorElementType() == PartVT &&
287 ValueVT.getVectorNumElements() == 1 &&
288 "Only trivial scalar-to-vector conversions should get here!");
289 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
295 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl,
296 SDValue Val, SDValue *Parts, unsigned NumParts,
299 /// getCopyToParts - Create a series of nodes that contain the specified value
300 /// split into legal parts. If the parts contain more bits than Val, then, for
301 /// integers, ExtendKind can be used to specify how to generate the extra bits.
302 static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL,
303 SDValue Val, SDValue *Parts, unsigned NumParts,
305 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
306 EVT ValueVT = Val.getValueType();
308 // Handle the vector case separately.
309 if (ValueVT.isVector())
310 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT);
312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
313 unsigned PartBits = PartVT.getSizeInBits();
314 unsigned OrigNumParts = NumParts;
315 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
320 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
321 if (PartVT == ValueVT) {
322 assert(NumParts == 1 && "No-op copy with multiple parts!");
327 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
328 // If the parts cover more bits than the value has, promote the value.
329 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
330 assert(NumParts == 1 && "Do not know what to promote to!");
331 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
333 assert(PartVT.isInteger() && ValueVT.isInteger() &&
334 "Unknown mismatch!");
335 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
336 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
338 } else if (PartBits == ValueVT.getSizeInBits()) {
339 // Different types of the same size.
340 assert(NumParts == 1 && PartVT != ValueVT);
341 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
342 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
343 // If the parts cover less bits than value has, truncate the value.
344 assert(PartVT.isInteger() && ValueVT.isInteger() &&
345 "Unknown mismatch!");
346 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
347 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
350 // The value may have changed - recompute ValueVT.
351 ValueVT = Val.getValueType();
352 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
353 "Failed to tile the value with PartVT!");
356 assert(PartVT == ValueVT && "Type conversion failed!");
361 // Expand the value into multiple parts.
362 if (NumParts & (NumParts - 1)) {
363 // The number of parts is not a power of 2. Split off and copy the tail.
364 assert(PartVT.isInteger() && ValueVT.isInteger() &&
365 "Do not know what to expand to!");
366 unsigned RoundParts = 1 << Log2_32(NumParts);
367 unsigned RoundBits = RoundParts * PartBits;
368 unsigned OddParts = NumParts - RoundParts;
369 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
370 DAG.getIntPtrConstant(RoundBits));
371 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT);
373 if (TLI.isBigEndian())
374 // The odd parts were reversed by getCopyToParts - unreverse them.
375 std::reverse(Parts + RoundParts, Parts + NumParts);
377 NumParts = RoundParts;
378 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
379 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
382 // The number of parts is a power of 2. Repeatedly bisect the value using
384 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
385 EVT::getIntegerVT(*DAG.getContext(),
386 ValueVT.getSizeInBits()),
389 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
390 for (unsigned i = 0; i < NumParts; i += StepSize) {
391 unsigned ThisBits = StepSize * PartBits / 2;
392 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
393 SDValue &Part0 = Parts[i];
394 SDValue &Part1 = Parts[i+StepSize/2];
396 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
397 ThisVT, Part0, DAG.getIntPtrConstant(1));
398 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
399 ThisVT, Part0, DAG.getIntPtrConstant(0));
401 if (ThisBits == PartBits && ThisVT != PartVT) {
402 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
403 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
408 if (TLI.isBigEndian())
409 std::reverse(Parts, Parts + OrigNumParts);
413 /// getCopyToPartsVector - Create a series of nodes that contain the specified
414 /// value split into legal parts.
415 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL,
416 SDValue Val, SDValue *Parts, unsigned NumParts,
418 EVT ValueVT = Val.getValueType();
419 assert(ValueVT.isVector() && "Not a vector");
420 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
423 if (PartVT == ValueVT) {
425 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
426 // Bitconvert vector->vector case.
427 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
428 } else if (PartVT.isVector() &&
429 PartVT.getVectorElementType() == ValueVT.getVectorElementType()&&
430 PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
431 EVT ElementVT = PartVT.getVectorElementType();
432 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
434 SmallVector<SDValue, 16> Ops;
435 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
436 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
437 ElementVT, Val, DAG.getIntPtrConstant(i)));
439 for (unsigned i = ValueVT.getVectorNumElements(),
440 e = PartVT.getVectorNumElements(); i != e; ++i)
441 Ops.push_back(DAG.getUNDEF(ElementVT));
443 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
445 // FIXME: Use CONCAT for 2x -> 4x.
447 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
448 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
450 // Vector -> scalar conversion.
451 assert(ValueVT.getVectorElementType() == PartVT &&
452 ValueVT.getVectorNumElements() == 1 &&
453 "Only trivial vector-to-scalar conversions should get here!");
454 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
455 PartVT, Val, DAG.getIntPtrConstant(0));
462 // Handle a multi-element vector.
463 EVT IntermediateVT, RegisterVT;
464 unsigned NumIntermediates;
465 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
467 NumIntermediates, RegisterVT);
468 unsigned NumElements = ValueVT.getVectorNumElements();
470 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
471 NumParts = NumRegs; // Silence a compiler warning.
472 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
474 // Split the vector into intermediate operands.
475 SmallVector<SDValue, 8> Ops(NumIntermediates);
476 for (unsigned i = 0; i != NumIntermediates; ++i) {
477 if (IntermediateVT.isVector())
478 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
480 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates)));
482 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
483 IntermediateVT, Val, DAG.getIntPtrConstant(i));
486 // Split the intermediate operands into legal parts.
487 if (NumParts == NumIntermediates) {
488 // If the register was not expanded, promote or copy the value,
490 for (unsigned i = 0; i != NumParts; ++i)
491 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT);
492 } else if (NumParts > 0) {
493 // If the intermediate type was expanded, split each the value into
495 assert(NumParts % NumIntermediates == 0 &&
496 "Must expand into a divisible number of parts!");
497 unsigned Factor = NumParts / NumIntermediates;
498 for (unsigned i = 0; i != NumIntermediates; ++i)
499 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT);
507 /// RegsForValue - This struct represents the registers (physical or virtual)
508 /// that a particular set of values is assigned, and the type information
509 /// about the value. The most common situation is to represent one value at a
510 /// time, but struct or array values are handled element-wise as multiple
511 /// values. The splitting of aggregates is performed recursively, so that we
512 /// never have aggregate-typed registers. The values at this point do not
513 /// necessarily have legal types, so each value may require one or more
514 /// registers of some legal type.
516 struct RegsForValue {
517 /// ValueVTs - The value types of the values, which may not be legal, and
518 /// may need be promoted or synthesized from one or more registers.
520 SmallVector<EVT, 4> ValueVTs;
522 /// RegVTs - The value types of the registers. This is the same size as
523 /// ValueVTs and it records, for each value, what the type of the assigned
524 /// register or registers are. (Individual values are never synthesized
525 /// from more than one type of register.)
527 /// With virtual registers, the contents of RegVTs is redundant with TLI's
528 /// getRegisterType member function, however when with physical registers
529 /// it is necessary to have a separate record of the types.
531 SmallVector<EVT, 4> RegVTs;
533 /// Regs - This list holds the registers assigned to the values.
534 /// Each legal or promoted value requires one register, and each
535 /// expanded value requires multiple registers.
537 SmallVector<unsigned, 4> Regs;
541 RegsForValue(const SmallVector<unsigned, 4> ®s,
542 EVT regvt, EVT valuevt)
543 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
545 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
546 unsigned Reg, const Type *Ty) {
547 ComputeValueVTs(tli, Ty, ValueVTs);
549 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
550 EVT ValueVT = ValueVTs[Value];
551 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
552 EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
553 for (unsigned i = 0; i != NumRegs; ++i)
554 Regs.push_back(Reg + i);
555 RegVTs.push_back(RegisterVT);
560 /// areValueTypesLegal - Return true if types of all the values are legal.
561 bool areValueTypesLegal(const TargetLowering &TLI) {
562 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
563 EVT RegisterVT = RegVTs[Value];
564 if (!TLI.isTypeLegal(RegisterVT))
570 /// append - Add the specified values to this one.
571 void append(const RegsForValue &RHS) {
572 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
573 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
574 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
577 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
578 /// this value and returns the result as a ValueVTs value. This uses
579 /// Chain/Flag as the input and updates them for the output Chain/Flag.
580 /// If the Flag pointer is NULL, no flag is used.
581 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
583 SDValue &Chain, SDValue *Flag) const;
585 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
586 /// specified value into the registers specified by this object. This uses
587 /// Chain/Flag as the input and updates them for the output Chain/Flag.
588 /// If the Flag pointer is NULL, no flag is used.
589 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
590 SDValue &Chain, SDValue *Flag) const;
592 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
593 /// operand list. This adds the code marker, matching input operand index
594 /// (if applicable), and includes the number of values added into it.
595 void AddInlineAsmOperands(unsigned Kind,
596 bool HasMatching, unsigned MatchingIdx,
598 std::vector<SDValue> &Ops) const;
602 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
603 /// this value and returns the result as a ValueVT value. This uses
604 /// Chain/Flag as the input and updates them for the output Chain/Flag.
605 /// If the Flag pointer is NULL, no flag is used.
606 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
607 FunctionLoweringInfo &FuncInfo,
609 SDValue &Chain, SDValue *Flag) const {
610 // A Value with type {} or [0 x %t] needs no registers.
611 if (ValueVTs.empty())
614 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
616 // Assemble the legal parts into the final values.
617 SmallVector<SDValue, 4> Values(ValueVTs.size());
618 SmallVector<SDValue, 8> Parts;
619 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
620 // Copy the legal parts from the registers.
621 EVT ValueVT = ValueVTs[Value];
622 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
623 EVT RegisterVT = RegVTs[Value];
625 Parts.resize(NumRegs);
626 for (unsigned i = 0; i != NumRegs; ++i) {
629 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
631 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
632 *Flag = P.getValue(2);
635 Chain = P.getValue(1);
638 // If the source register was virtual and if we know something about it,
639 // add an assert node.
640 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
641 !RegisterVT.isInteger() || RegisterVT.isVector())
644 const FunctionLoweringInfo::LiveOutInfo *LOI =
645 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
649 unsigned RegSize = RegisterVT.getSizeInBits();
650 unsigned NumSignBits = LOI->NumSignBits;
651 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
653 // FIXME: We capture more information than the dag can represent. For
654 // now, just use the tightest assertzext/assertsext possible.
656 EVT FromVT(MVT::Other);
657 if (NumSignBits == RegSize)
658 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
659 else if (NumZeroBits >= RegSize-1)
660 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
661 else if (NumSignBits > RegSize-8)
662 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
663 else if (NumZeroBits >= RegSize-8)
664 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
665 else if (NumSignBits > RegSize-16)
666 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
667 else if (NumZeroBits >= RegSize-16)
668 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
669 else if (NumSignBits > RegSize-32)
670 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
671 else if (NumZeroBits >= RegSize-32)
672 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
676 // Add an assertion node.
677 assert(FromVT != MVT::Other);
678 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
679 RegisterVT, P, DAG.getValueType(FromVT));
682 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
683 NumRegs, RegisterVT, ValueVT);
688 return DAG.getNode(ISD::MERGE_VALUES, dl,
689 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
690 &Values[0], ValueVTs.size());
693 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
694 /// specified value into the registers specified by this object. This uses
695 /// Chain/Flag as the input and updates them for the output Chain/Flag.
696 /// If the Flag pointer is NULL, no flag is used.
697 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
698 SDValue &Chain, SDValue *Flag) const {
699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
701 // Get the list of the values's legal parts.
702 unsigned NumRegs = Regs.size();
703 SmallVector<SDValue, 8> Parts(NumRegs);
704 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
705 EVT ValueVT = ValueVTs[Value];
706 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
707 EVT RegisterVT = RegVTs[Value];
709 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
710 &Parts[Part], NumParts, RegisterVT);
714 // Copy the parts into the registers.
715 SmallVector<SDValue, 8> Chains(NumRegs);
716 for (unsigned i = 0; i != NumRegs; ++i) {
719 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
721 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
722 *Flag = Part.getValue(1);
725 Chains[i] = Part.getValue(0);
728 if (NumRegs == 1 || Flag)
729 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
730 // flagged to it. That is the CopyToReg nodes and the user are considered
731 // a single scheduling unit. If we create a TokenFactor and return it as
732 // chain, then the TokenFactor is both a predecessor (operand) of the
733 // user as well as a successor (the TF operands are flagged to the user).
734 // c1, f1 = CopyToReg
735 // c2, f2 = CopyToReg
736 // c3 = TokenFactor c1, c2
739 Chain = Chains[NumRegs-1];
741 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
744 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
745 /// operand list. This adds the code marker and includes the number of
746 /// values added into it.
747 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
748 unsigned MatchingIdx,
750 std::vector<SDValue> &Ops) const {
751 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
753 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
755 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
756 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
759 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
760 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
761 EVT RegisterVT = RegVTs[Value];
762 for (unsigned i = 0; i != NumRegs; ++i) {
763 assert(Reg < Regs.size() && "Mismatch in # registers expected");
764 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
769 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
772 TD = DAG.getTarget().getTargetData();
775 /// clear - Clear out the current SelectionDAG and the associated
776 /// state and prepare this SelectionDAGBuilder object to be used
777 /// for a new block. This doesn't clear out information about
778 /// additional blocks that are needed to complete switch lowering
779 /// or PHI node updating; that information is cleared out as it is
781 void SelectionDAGBuilder::clear() {
783 UnusedArgNodeMap.clear();
784 PendingLoads.clear();
785 PendingExports.clear();
786 CurDebugLoc = DebugLoc();
790 /// clearDanglingDebugInfo - Clear the dangling debug information
791 /// map. This function is seperated from the clear so that debug
792 /// information that is dangling in a basic block can be properly
793 /// resolved in a different basic block. This allows the
794 /// SelectionDAG to resolve dangling debug information attached
796 void SelectionDAGBuilder::clearDanglingDebugInfo() {
797 DanglingDebugInfoMap.clear();
800 /// getRoot - Return the current virtual root of the Selection DAG,
801 /// flushing any PendingLoad items. This must be done before emitting
802 /// a store or any other node that may need to be ordered after any
803 /// prior load instructions.
805 SDValue SelectionDAGBuilder::getRoot() {
806 if (PendingLoads.empty())
807 return DAG.getRoot();
809 if (PendingLoads.size() == 1) {
810 SDValue Root = PendingLoads[0];
812 PendingLoads.clear();
816 // Otherwise, we have to make a token factor node.
817 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
818 &PendingLoads[0], PendingLoads.size());
819 PendingLoads.clear();
824 /// getControlRoot - Similar to getRoot, but instead of flushing all the
825 /// PendingLoad items, flush all the PendingExports items. It is necessary
826 /// to do this before emitting a terminator instruction.
828 SDValue SelectionDAGBuilder::getControlRoot() {
829 SDValue Root = DAG.getRoot();
831 if (PendingExports.empty())
834 // Turn all of the CopyToReg chains into one factored node.
835 if (Root.getOpcode() != ISD::EntryToken) {
836 unsigned i = 0, e = PendingExports.size();
837 for (; i != e; ++i) {
838 assert(PendingExports[i].getNode()->getNumOperands() > 1);
839 if (PendingExports[i].getNode()->getOperand(0) == Root)
840 break; // Don't add the root if we already indirectly depend on it.
844 PendingExports.push_back(Root);
847 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
849 PendingExports.size());
850 PendingExports.clear();
855 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
856 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
857 DAG.AssignOrdering(Node, SDNodeOrder);
859 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
860 AssignOrderingToNode(Node->getOperand(I).getNode());
863 void SelectionDAGBuilder::visit(const Instruction &I) {
864 // Set up outgoing PHI node register values before emitting the terminator.
865 if (isa<TerminatorInst>(&I))
866 HandlePHINodesInSuccessorBlocks(I.getParent());
868 CurDebugLoc = I.getDebugLoc();
870 visit(I.getOpcode(), I);
872 if (!isa<TerminatorInst>(&I) && !HasTailCall)
873 CopyToExportRegsIfNeeded(&I);
875 CurDebugLoc = DebugLoc();
878 void SelectionDAGBuilder::visitPHI(const PHINode &) {
879 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
882 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
883 // Note: this doesn't use InstVisitor, because it has to work with
884 // ConstantExpr's in addition to instructions.
886 default: llvm_unreachable("Unknown instruction type encountered!");
887 // Build the switch statement using the Instruction.def file.
888 #define HANDLE_INST(NUM, OPCODE, CLASS) \
889 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
890 #include "llvm/Instruction.def"
893 // Assign the ordering to the freshly created DAG nodes.
894 if (NodeMap.count(&I)) {
896 AssignOrderingToNode(getValue(&I).getNode());
900 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
901 // generate the debug data structures now that we've seen its definition.
902 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
904 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
906 const DbgValueInst *DI = DDI.getDI();
907 DebugLoc dl = DDI.getdl();
908 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
909 MDNode *Variable = DI->getVariable();
910 uint64_t Offset = DI->getOffset();
913 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
914 SDV = DAG.getDbgValue(Variable, Val.getNode(),
915 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
916 DAG.AddDbgValue(SDV, Val.getNode(), false);
919 DEBUG(dbgs() << "Dropping debug info for " << DI);
920 DanglingDebugInfoMap[V] = DanglingDebugInfo();
924 // getValue - Return an SDValue for the given Value.
925 SDValue SelectionDAGBuilder::getValue(const Value *V) {
926 // If we already have an SDValue for this value, use it. It's important
927 // to do this first, so that we don't create a CopyFromReg if we already
928 // have a regular SDValue.
929 SDValue &N = NodeMap[V];
930 if (N.getNode()) return N;
932 // If there's a virtual register allocated and initialized for this
934 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
935 if (It != FuncInfo.ValueMap.end()) {
936 unsigned InReg = It->second;
937 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
938 SDValue Chain = DAG.getEntryNode();
939 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain,NULL);
940 resolveDanglingDebugInfo(V, N);
944 // Otherwise create a new SDValue and remember it.
945 SDValue Val = getValueImpl(V);
947 resolveDanglingDebugInfo(V, Val);
951 /// getNonRegisterValue - Return an SDValue for the given Value, but
952 /// don't look in FuncInfo.ValueMap for a virtual register.
953 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
954 // If we already have an SDValue for this value, use it.
955 SDValue &N = NodeMap[V];
956 if (N.getNode()) return N;
958 // Otherwise create a new SDValue and remember it.
959 SDValue Val = getValueImpl(V);
961 resolveDanglingDebugInfo(V, Val);
965 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
966 /// Create an SDValue for the given value.
967 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
968 if (const Constant *C = dyn_cast<Constant>(V)) {
969 EVT VT = TLI.getValueType(V->getType(), true);
971 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
972 return DAG.getConstant(*CI, VT);
974 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
975 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT);
977 if (isa<ConstantPointerNull>(C))
978 return DAG.getConstant(0, TLI.getPointerTy());
980 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
981 return DAG.getConstantFP(*CFP, VT);
983 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
984 return DAG.getUNDEF(VT);
986 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
987 visit(CE->getOpcode(), *CE);
988 SDValue N1 = NodeMap[V];
989 assert(N1.getNode() && "visit didn't populate the NodeMap!");
993 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
994 SmallVector<SDValue, 4> Constants;
995 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
997 SDNode *Val = getValue(*OI).getNode();
998 // If the operand is an empty aggregate, there are no values.
1000 // Add each leaf value from the operand to the Constants list
1001 // to form a flattened list of all the values.
1002 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1003 Constants.push_back(SDValue(Val, i));
1006 return DAG.getMergeValues(&Constants[0], Constants.size(),
1010 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1011 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1012 "Unknown struct or array constant!");
1014 SmallVector<EVT, 4> ValueVTs;
1015 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1016 unsigned NumElts = ValueVTs.size();
1018 return SDValue(); // empty struct
1019 SmallVector<SDValue, 4> Constants(NumElts);
1020 for (unsigned i = 0; i != NumElts; ++i) {
1021 EVT EltVT = ValueVTs[i];
1022 if (isa<UndefValue>(C))
1023 Constants[i] = DAG.getUNDEF(EltVT);
1024 else if (EltVT.isFloatingPoint())
1025 Constants[i] = DAG.getConstantFP(0, EltVT);
1027 Constants[i] = DAG.getConstant(0, EltVT);
1030 return DAG.getMergeValues(&Constants[0], NumElts,
1034 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1035 return DAG.getBlockAddress(BA, VT);
1037 const VectorType *VecTy = cast<VectorType>(V->getType());
1038 unsigned NumElements = VecTy->getNumElements();
1040 // Now that we know the number and type of the elements, get that number of
1041 // elements into the Ops array based on what kind of constant it is.
1042 SmallVector<SDValue, 16> Ops;
1043 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1044 for (unsigned i = 0; i != NumElements; ++i)
1045 Ops.push_back(getValue(CP->getOperand(i)));
1047 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1048 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1051 if (EltVT.isFloatingPoint())
1052 Op = DAG.getConstantFP(0, EltVT);
1054 Op = DAG.getConstant(0, EltVT);
1055 Ops.assign(NumElements, Op);
1058 // Create a BUILD_VECTOR node.
1059 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1060 VT, &Ops[0], Ops.size());
1063 // If this is a static alloca, generate it as the frameindex instead of
1065 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1066 DenseMap<const AllocaInst*, int>::iterator SI =
1067 FuncInfo.StaticAllocaMap.find(AI);
1068 if (SI != FuncInfo.StaticAllocaMap.end())
1069 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1072 // If this is an instruction which fast-isel has deferred, select it now.
1073 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1074 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1075 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1076 SDValue Chain = DAG.getEntryNode();
1077 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
1080 llvm_unreachable("Can't get register for value!");
1084 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1085 SDValue Chain = getControlRoot();
1086 SmallVector<ISD::OutputArg, 8> Outs;
1087 SmallVector<SDValue, 8> OutVals;
1089 if (!FuncInfo.CanLowerReturn) {
1090 unsigned DemoteReg = FuncInfo.DemoteRegister;
1091 const Function *F = I.getParent()->getParent();
1093 // Emit a store of the return value through the virtual register.
1094 // Leave Outs empty so that LowerReturn won't try to load return
1095 // registers the usual way.
1096 SmallVector<EVT, 1> PtrValueVTs;
1097 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1100 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1101 SDValue RetOp = getValue(I.getOperand(0));
1103 SmallVector<EVT, 4> ValueVTs;
1104 SmallVector<uint64_t, 4> Offsets;
1105 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1106 unsigned NumValues = ValueVTs.size();
1108 SmallVector<SDValue, 4> Chains(NumValues);
1109 for (unsigned i = 0; i != NumValues; ++i) {
1110 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(),
1111 RetPtr.getValueType(), RetPtr,
1112 DAG.getIntPtrConstant(Offsets[i]));
1114 DAG.getStore(Chain, getCurDebugLoc(),
1115 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1116 // FIXME: better loc info would be nice.
1117 Add, MachinePointerInfo(), false, false, 0);
1120 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1121 MVT::Other, &Chains[0], NumValues);
1122 } else if (I.getNumOperands() != 0) {
1123 SmallVector<EVT, 4> ValueVTs;
1124 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1125 unsigned NumValues = ValueVTs.size();
1127 SDValue RetOp = getValue(I.getOperand(0));
1128 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1129 EVT VT = ValueVTs[j];
1131 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1133 const Function *F = I.getParent()->getParent();
1134 if (F->paramHasAttr(0, Attribute::SExt))
1135 ExtendKind = ISD::SIGN_EXTEND;
1136 else if (F->paramHasAttr(0, Attribute::ZExt))
1137 ExtendKind = ISD::ZERO_EXTEND;
1139 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1140 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1142 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1143 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1144 SmallVector<SDValue, 4> Parts(NumParts);
1145 getCopyToParts(DAG, getCurDebugLoc(),
1146 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1147 &Parts[0], NumParts, PartVT, ExtendKind);
1149 // 'inreg' on function refers to return value
1150 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1151 if (F->paramHasAttr(0, Attribute::InReg))
1154 // Propagate extension type if any
1155 if (ExtendKind == ISD::SIGN_EXTEND)
1157 else if (ExtendKind == ISD::ZERO_EXTEND)
1160 for (unsigned i = 0; i < NumParts; ++i) {
1161 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1163 OutVals.push_back(Parts[i]);
1169 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1170 CallingConv::ID CallConv =
1171 DAG.getMachineFunction().getFunction()->getCallingConv();
1172 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1173 Outs, OutVals, getCurDebugLoc(), DAG);
1175 // Verify that the target's LowerReturn behaved as expected.
1176 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1177 "LowerReturn didn't return a valid chain!");
1179 // Update the DAG with the new chain value resulting from return lowering.
1183 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1184 /// created for it, emit nodes to copy the value into the virtual
1186 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1188 if (V->getType()->isEmptyTy())
1191 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1192 if (VMI != FuncInfo.ValueMap.end()) {
1193 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1194 CopyValueToVirtualRegister(V, VMI->second);
1198 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1199 /// the current basic block, add it to ValueMap now so that we'll get a
1201 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1202 // No need to export constants.
1203 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1205 // Already exported?
1206 if (FuncInfo.isExportedInst(V)) return;
1208 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1209 CopyValueToVirtualRegister(V, Reg);
1212 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1213 const BasicBlock *FromBB) {
1214 // The operands of the setcc have to be in this block. We don't know
1215 // how to export them from some other block.
1216 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1217 // Can export from current BB.
1218 if (VI->getParent() == FromBB)
1221 // Is already exported, noop.
1222 return FuncInfo.isExportedInst(V);
1225 // If this is an argument, we can export it if the BB is the entry block or
1226 // if it is already exported.
1227 if (isa<Argument>(V)) {
1228 if (FromBB == &FromBB->getParent()->getEntryBlock())
1231 // Otherwise, can only export this if it is already exported.
1232 return FuncInfo.isExportedInst(V);
1235 // Otherwise, constants can always be exported.
1239 static bool InBlock(const Value *V, const BasicBlock *BB) {
1240 if (const Instruction *I = dyn_cast<Instruction>(V))
1241 return I->getParent() == BB;
1245 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1246 /// This function emits a branch and is used at the leaves of an OR or an
1247 /// AND operator tree.
1250 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1251 MachineBasicBlock *TBB,
1252 MachineBasicBlock *FBB,
1253 MachineBasicBlock *CurBB,
1254 MachineBasicBlock *SwitchBB) {
1255 const BasicBlock *BB = CurBB->getBasicBlock();
1257 // If the leaf of the tree is a comparison, merge the condition into
1259 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1260 // The operands of the cmp have to be in this block. We don't know
1261 // how to export them from some other block. If this is the first block
1262 // of the sequence, no exporting is needed.
1263 if (CurBB == SwitchBB ||
1264 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1265 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1266 ISD::CondCode Condition;
1267 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1268 Condition = getICmpCondCode(IC->getPredicate());
1269 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1270 Condition = getFCmpCondCode(FC->getPredicate());
1272 Condition = ISD::SETEQ; // silence warning.
1273 llvm_unreachable("Unknown compare instruction");
1276 CaseBlock CB(Condition, BOp->getOperand(0),
1277 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1278 SwitchCases.push_back(CB);
1283 // Create a CaseBlock record representing this branch.
1284 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1285 NULL, TBB, FBB, CurBB);
1286 SwitchCases.push_back(CB);
1289 /// FindMergedConditions - If Cond is an expression like
1290 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1291 MachineBasicBlock *TBB,
1292 MachineBasicBlock *FBB,
1293 MachineBasicBlock *CurBB,
1294 MachineBasicBlock *SwitchBB,
1296 // If this node is not part of the or/and tree, emit it as a branch.
1297 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1298 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1299 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1300 BOp->getParent() != CurBB->getBasicBlock() ||
1301 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1302 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1303 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1307 // Create TmpBB after CurBB.
1308 MachineFunction::iterator BBI = CurBB;
1309 MachineFunction &MF = DAG.getMachineFunction();
1310 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1311 CurBB->getParent()->insert(++BBI, TmpBB);
1313 if (Opc == Instruction::Or) {
1314 // Codegen X | Y as:
1322 // Emit the LHS condition.
1323 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1325 // Emit the RHS condition into TmpBB.
1326 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1328 assert(Opc == Instruction::And && "Unknown merge op!");
1329 // Codegen X & Y as:
1336 // This requires creation of TmpBB after CurBB.
1338 // Emit the LHS condition.
1339 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1341 // Emit the RHS condition into TmpBB.
1342 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1346 /// If the set of cases should be emitted as a series of branches, return true.
1347 /// If we should emit this as a bunch of and/or'd together conditions, return
1350 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1351 if (Cases.size() != 2) return true;
1353 // If this is two comparisons of the same values or'd or and'd together, they
1354 // will get folded into a single comparison, so don't emit two blocks.
1355 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1356 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1357 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1358 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1362 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1363 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1364 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1365 Cases[0].CC == Cases[1].CC &&
1366 isa<Constant>(Cases[0].CmpRHS) &&
1367 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1368 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1370 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1377 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1378 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1380 // Update machine-CFG edges.
1381 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1383 // Figure out which block is immediately after the current one.
1384 MachineBasicBlock *NextBlock = 0;
1385 MachineFunction::iterator BBI = BrMBB;
1386 if (++BBI != FuncInfo.MF->end())
1389 if (I.isUnconditional()) {
1390 // Update machine-CFG edges.
1391 BrMBB->addSuccessor(Succ0MBB);
1393 // If this is not a fall-through branch, emit the branch.
1394 if (Succ0MBB != NextBlock)
1395 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1396 MVT::Other, getControlRoot(),
1397 DAG.getBasicBlock(Succ0MBB)));
1402 // If this condition is one of the special cases we handle, do special stuff
1404 const Value *CondVal = I.getCondition();
1405 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1407 // If this is a series of conditions that are or'd or and'd together, emit
1408 // this as a sequence of branches instead of setcc's with and/or operations.
1409 // As long as jumps are not expensive, this should improve performance.
1410 // For example, instead of something like:
1423 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1424 if (!TLI.isJumpExpensive() &&
1426 (BOp->getOpcode() == Instruction::And ||
1427 BOp->getOpcode() == Instruction::Or)) {
1428 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1430 // If the compares in later blocks need to use values not currently
1431 // exported from this block, export them now. This block should always
1432 // be the first entry.
1433 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1435 // Allow some cases to be rejected.
1436 if (ShouldEmitAsBranches(SwitchCases)) {
1437 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1438 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1439 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1442 // Emit the branch for this block.
1443 visitSwitchCase(SwitchCases[0], BrMBB);
1444 SwitchCases.erase(SwitchCases.begin());
1448 // Okay, we decided not to do this, remove any inserted MBB's and clear
1450 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1451 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1453 SwitchCases.clear();
1457 // Create a CaseBlock record representing this branch.
1458 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1459 NULL, Succ0MBB, Succ1MBB, BrMBB);
1461 // Use visitSwitchCase to actually insert the fast branch sequence for this
1463 visitSwitchCase(CB, BrMBB);
1466 /// visitSwitchCase - Emits the necessary code to represent a single node in
1467 /// the binary search tree resulting from lowering a switch instruction.
1468 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1469 MachineBasicBlock *SwitchBB) {
1471 SDValue CondLHS = getValue(CB.CmpLHS);
1472 DebugLoc dl = getCurDebugLoc();
1474 // Build the setcc now.
1475 if (CB.CmpMHS == NULL) {
1476 // Fold "(X == true)" to X and "(X == false)" to !X to
1477 // handle common cases produced by branch lowering.
1478 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1479 CB.CC == ISD::SETEQ)
1481 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1482 CB.CC == ISD::SETEQ) {
1483 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1484 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1486 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1488 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1490 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1491 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1493 SDValue CmpOp = getValue(CB.CmpMHS);
1494 EVT VT = CmpOp.getValueType();
1496 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1497 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1500 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1501 VT, CmpOp, DAG.getConstant(Low, VT));
1502 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1503 DAG.getConstant(High-Low, VT), ISD::SETULE);
1507 // Update successor info
1508 SwitchBB->addSuccessor(CB.TrueBB);
1509 SwitchBB->addSuccessor(CB.FalseBB);
1511 // Set NextBlock to be the MBB immediately after the current one, if any.
1512 // This is used to avoid emitting unnecessary branches to the next block.
1513 MachineBasicBlock *NextBlock = 0;
1514 MachineFunction::iterator BBI = SwitchBB;
1515 if (++BBI != FuncInfo.MF->end())
1518 // If the lhs block is the next block, invert the condition so that we can
1519 // fall through to the lhs instead of the rhs block.
1520 if (CB.TrueBB == NextBlock) {
1521 std::swap(CB.TrueBB, CB.FalseBB);
1522 SDValue True = DAG.getConstant(1, Cond.getValueType());
1523 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1526 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1527 MVT::Other, getControlRoot(), Cond,
1528 DAG.getBasicBlock(CB.TrueBB));
1530 // Insert the false branch. Do this even if it's a fall through branch,
1531 // this makes it easier to do DAG optimizations which require inverting
1532 // the branch condition.
1533 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1534 DAG.getBasicBlock(CB.FalseBB));
1536 DAG.setRoot(BrCond);
1539 /// visitJumpTable - Emit JumpTable node in the current MBB
1540 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1541 // Emit the code for the jump table
1542 assert(JT.Reg != -1U && "Should lower JT Header first!");
1543 EVT PTy = TLI.getPointerTy();
1544 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1546 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1547 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1548 MVT::Other, Index.getValue(1),
1550 DAG.setRoot(BrJumpTable);
1553 /// visitJumpTableHeader - This function emits necessary code to produce index
1554 /// in the JumpTable from switch case.
1555 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1556 JumpTableHeader &JTH,
1557 MachineBasicBlock *SwitchBB) {
1558 // Subtract the lowest switch case value from the value being switched on and
1559 // conditional branch to default mbb if the result is greater than the
1560 // difference between smallest and largest cases.
1561 SDValue SwitchOp = getValue(JTH.SValue);
1562 EVT VT = SwitchOp.getValueType();
1563 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1564 DAG.getConstant(JTH.First, VT));
1566 // The SDNode we just created, which holds the value being switched on minus
1567 // the smallest case value, needs to be copied to a virtual register so it
1568 // can be used as an index into the jump table in a subsequent basic block.
1569 // This value may be smaller or larger than the target's pointer type, and
1570 // therefore require extension or truncating.
1571 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1573 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1574 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1575 JumpTableReg, SwitchOp);
1576 JT.Reg = JumpTableReg;
1578 // Emit the range check for the jump table, and branch to the default block
1579 // for the switch statement if the value being switched on exceeds the largest
1580 // case in the switch.
1581 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1582 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1583 DAG.getConstant(JTH.Last-JTH.First,VT),
1586 // Set NextBlock to be the MBB immediately after the current one, if any.
1587 // This is used to avoid emitting unnecessary branches to the next block.
1588 MachineBasicBlock *NextBlock = 0;
1589 MachineFunction::iterator BBI = SwitchBB;
1591 if (++BBI != FuncInfo.MF->end())
1594 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1595 MVT::Other, CopyTo, CMP,
1596 DAG.getBasicBlock(JT.Default));
1598 if (JT.MBB != NextBlock)
1599 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1600 DAG.getBasicBlock(JT.MBB));
1602 DAG.setRoot(BrCond);
1605 /// visitBitTestHeader - This function emits necessary code to produce value
1606 /// suitable for "bit tests"
1607 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1608 MachineBasicBlock *SwitchBB) {
1609 // Subtract the minimum value
1610 SDValue SwitchOp = getValue(B.SValue);
1611 EVT VT = SwitchOp.getValueType();
1612 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1613 DAG.getConstant(B.First, VT));
1616 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1617 TLI.getSetCCResultType(Sub.getValueType()),
1618 Sub, DAG.getConstant(B.Range, VT),
1621 // Determine the type of the test operands.
1622 bool UsePtrType = false;
1623 if (!TLI.isTypeLegal(VT))
1626 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1627 if ((uint64_t)((int64_t)B.Cases[i].Mask >> VT.getSizeInBits()) + 1 >= 2) {
1628 // Switch table case range are encoded into series of masks.
1629 // Just use pointer type, it's guaranteed to fit.
1635 VT = TLI.getPointerTy();
1636 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
1640 B.Reg = FuncInfo.CreateReg(VT);
1641 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1644 // Set NextBlock to be the MBB immediately after the current one, if any.
1645 // This is used to avoid emitting unnecessary branches to the next block.
1646 MachineBasicBlock *NextBlock = 0;
1647 MachineFunction::iterator BBI = SwitchBB;
1648 if (++BBI != FuncInfo.MF->end())
1651 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1653 SwitchBB->addSuccessor(B.Default);
1654 SwitchBB->addSuccessor(MBB);
1656 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1657 MVT::Other, CopyTo, RangeCmp,
1658 DAG.getBasicBlock(B.Default));
1660 if (MBB != NextBlock)
1661 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1662 DAG.getBasicBlock(MBB));
1664 DAG.setRoot(BrRange);
1667 /// visitBitTestCase - this function produces one "bit test"
1668 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1669 MachineBasicBlock* NextMBB,
1672 MachineBasicBlock *SwitchBB) {
1674 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1677 if (CountPopulation_64(B.Mask) == 1) {
1678 // Testing for a single bit; just compare the shift count with what it
1679 // would need to be to shift a 1 bit in that position.
1680 Cmp = DAG.getSetCC(getCurDebugLoc(),
1681 TLI.getSetCCResultType(VT),
1683 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
1686 // Make desired shift
1687 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
1688 DAG.getConstant(1, VT), ShiftOp);
1690 // Emit bit tests and jumps
1691 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1692 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1693 Cmp = DAG.getSetCC(getCurDebugLoc(),
1694 TLI.getSetCCResultType(VT),
1695 AndOp, DAG.getConstant(0, VT),
1699 SwitchBB->addSuccessor(B.TargetBB);
1700 SwitchBB->addSuccessor(NextMBB);
1702 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1703 MVT::Other, getControlRoot(),
1704 Cmp, DAG.getBasicBlock(B.TargetBB));
1706 // Set NextBlock to be the MBB immediately after the current one, if any.
1707 // This is used to avoid emitting unnecessary branches to the next block.
1708 MachineBasicBlock *NextBlock = 0;
1709 MachineFunction::iterator BBI = SwitchBB;
1710 if (++BBI != FuncInfo.MF->end())
1713 if (NextMBB != NextBlock)
1714 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1715 DAG.getBasicBlock(NextMBB));
1720 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1721 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1723 // Retrieve successors.
1724 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1725 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1727 const Value *Callee(I.getCalledValue());
1728 if (isa<InlineAsm>(Callee))
1731 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1733 // If the value of the invoke is used outside of its defining block, make it
1734 // available as a virtual register.
1735 CopyToExportRegsIfNeeded(&I);
1737 // Update successor info
1738 InvokeMBB->addSuccessor(Return);
1739 InvokeMBB->addSuccessor(LandingPad);
1741 // Drop into normal successor.
1742 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1743 MVT::Other, getControlRoot(),
1744 DAG.getBasicBlock(Return)));
1747 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1750 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1751 /// small case ranges).
1752 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1753 CaseRecVector& WorkList,
1755 MachineBasicBlock *Default,
1756 MachineBasicBlock *SwitchBB) {
1757 Case& BackCase = *(CR.Range.second-1);
1759 // Size is the number of Cases represented by this range.
1760 size_t Size = CR.Range.second - CR.Range.first;
1764 // Get the MachineFunction which holds the current MBB. This is used when
1765 // inserting any additional MBBs necessary to represent the switch.
1766 MachineFunction *CurMF = FuncInfo.MF;
1768 // Figure out which block is immediately after the current one.
1769 MachineBasicBlock *NextBlock = 0;
1770 MachineFunction::iterator BBI = CR.CaseBB;
1772 if (++BBI != FuncInfo.MF->end())
1775 // If any two of the cases has the same destination, and if one value
1776 // is the same as the other, but has one bit unset that the other has set,
1777 // use bit manipulation to do two compares at once. For example:
1778 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1779 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
1780 // TODO: Handle cases where CR.CaseBB != SwitchBB.
1781 if (Size == 2 && CR.CaseBB == SwitchBB) {
1782 Case &Small = *CR.Range.first;
1783 Case &Big = *(CR.Range.second-1);
1785 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
1786 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
1787 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
1789 // Check that there is only one bit different.
1790 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
1791 (SmallValue | BigValue) == BigValue) {
1792 // Isolate the common bit.
1793 APInt CommonBit = BigValue & ~SmallValue;
1794 assert((SmallValue | CommonBit) == BigValue &&
1795 CommonBit.countPopulation() == 1 && "Not a common bit?");
1797 SDValue CondLHS = getValue(SV);
1798 EVT VT = CondLHS.getValueType();
1799 DebugLoc DL = getCurDebugLoc();
1801 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
1802 DAG.getConstant(CommonBit, VT));
1803 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
1804 Or, DAG.getConstant(BigValue, VT),
1807 // Update successor info.
1808 SwitchBB->addSuccessor(Small.BB);
1809 SwitchBB->addSuccessor(Default);
1811 // Insert the true branch.
1812 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
1813 getControlRoot(), Cond,
1814 DAG.getBasicBlock(Small.BB));
1816 // Insert the false branch.
1817 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
1818 DAG.getBasicBlock(Default));
1820 DAG.setRoot(BrCond);
1826 // Rearrange the case blocks so that the last one falls through if possible.
1827 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1828 // The last case block won't fall through into 'NextBlock' if we emit the
1829 // branches in this order. See if rearranging a case value would help.
1830 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1831 if (I->BB == NextBlock) {
1832 std::swap(*I, BackCase);
1838 // Create a CaseBlock record representing a conditional branch to
1839 // the Case's target mbb if the value being switched on SV is equal
1841 MachineBasicBlock *CurBlock = CR.CaseBB;
1842 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1843 MachineBasicBlock *FallThrough;
1845 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1846 CurMF->insert(BBI, FallThrough);
1848 // Put SV in a virtual register to make it available from the new blocks.
1849 ExportFromCurrentBlock(SV);
1851 // If the last case doesn't match, go to the default block.
1852 FallThrough = Default;
1855 const Value *RHS, *LHS, *MHS;
1857 if (I->High == I->Low) {
1858 // This is just small small case range :) containing exactly 1 case
1860 LHS = SV; RHS = I->High; MHS = NULL;
1863 LHS = I->Low; MHS = SV; RHS = I->High;
1865 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1867 // If emitting the first comparison, just call visitSwitchCase to emit the
1868 // code into the current block. Otherwise, push the CaseBlock onto the
1869 // vector to be later processed by SDISel, and insert the node's MBB
1870 // before the next MBB.
1871 if (CurBlock == SwitchBB)
1872 visitSwitchCase(CB, SwitchBB);
1874 SwitchCases.push_back(CB);
1876 CurBlock = FallThrough;
1882 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1883 return !DisableJumpTables &&
1884 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1885 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1888 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1889 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1890 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
1891 return (LastExt - FirstExt + 1ULL);
1894 /// handleJTSwitchCase - Emit jumptable for current switch case range
1895 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1896 CaseRecVector& WorkList,
1898 MachineBasicBlock* Default,
1899 MachineBasicBlock *SwitchBB) {
1900 Case& FrontCase = *CR.Range.first;
1901 Case& BackCase = *(CR.Range.second-1);
1903 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1904 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1906 APInt TSize(First.getBitWidth(), 0);
1907 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1911 if (!areJTsAllowed(TLI) || TSize.ult(4))
1914 APInt Range = ComputeRange(First, Last);
1915 double Density = TSize.roundToDouble() / Range.roundToDouble();
1919 DEBUG(dbgs() << "Lowering jump table\n"
1920 << "First entry: " << First << ". Last entry: " << Last << '\n'
1921 << "Range: " << Range
1922 << ". Size: " << TSize << ". Density: " << Density << "\n\n");
1924 // Get the MachineFunction which holds the current MBB. This is used when
1925 // inserting any additional MBBs necessary to represent the switch.
1926 MachineFunction *CurMF = FuncInfo.MF;
1928 // Figure out which block is immediately after the current one.
1929 MachineFunction::iterator BBI = CR.CaseBB;
1932 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1934 // Create a new basic block to hold the code for loading the address
1935 // of the jump table, and jumping to it. Update successor information;
1936 // we will either branch to the default case for the switch, or the jump
1938 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1939 CurMF->insert(BBI, JumpTableBB);
1940 CR.CaseBB->addSuccessor(Default);
1941 CR.CaseBB->addSuccessor(JumpTableBB);
1943 // Build a vector of destination BBs, corresponding to each target
1944 // of the jump table. If the value of the jump table slot corresponds to
1945 // a case statement, push the case's BB onto the vector, otherwise, push
1947 std::vector<MachineBasicBlock*> DestBBs;
1949 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1950 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1951 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1953 if (Low.sle(TEI) && TEI.sle(High)) {
1954 DestBBs.push_back(I->BB);
1958 DestBBs.push_back(Default);
1962 // Update successor info. Add one edge to each unique successor.
1963 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1964 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1965 E = DestBBs.end(); I != E; ++I) {
1966 if (!SuccsHandled[(*I)->getNumber()]) {
1967 SuccsHandled[(*I)->getNumber()] = true;
1968 JumpTableBB->addSuccessor(*I);
1972 // Create a jump table index for this jump table.
1973 unsigned JTEncoding = TLI.getJumpTableEncoding();
1974 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1975 ->createJumpTableIndex(DestBBs);
1977 // Set the jump table information so that we can codegen it as a second
1978 // MachineBasicBlock
1979 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1980 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
1981 if (CR.CaseBB == SwitchBB)
1982 visitJumpTableHeader(JT, JTH, SwitchBB);
1984 JTCases.push_back(JumpTableBlock(JTH, JT));
1989 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1991 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1992 CaseRecVector& WorkList,
1994 MachineBasicBlock *Default,
1995 MachineBasicBlock *SwitchBB) {
1996 // Get the MachineFunction which holds the current MBB. This is used when
1997 // inserting any additional MBBs necessary to represent the switch.
1998 MachineFunction *CurMF = FuncInfo.MF;
2000 // Figure out which block is immediately after the current one.
2001 MachineFunction::iterator BBI = CR.CaseBB;
2004 Case& FrontCase = *CR.Range.first;
2005 Case& BackCase = *(CR.Range.second-1);
2006 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2008 // Size is the number of Cases represented by this range.
2009 unsigned Size = CR.Range.second - CR.Range.first;
2011 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2012 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2014 CaseItr Pivot = CR.Range.first + Size/2;
2016 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2017 // (heuristically) allow us to emit JumpTable's later.
2018 APInt TSize(First.getBitWidth(), 0);
2019 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2023 APInt LSize = FrontCase.size();
2024 APInt RSize = TSize-LSize;
2025 DEBUG(dbgs() << "Selecting best pivot: \n"
2026 << "First: " << First << ", Last: " << Last <<'\n'
2027 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2028 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2030 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2031 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2032 APInt Range = ComputeRange(LEnd, RBegin);
2033 assert((Range - 2ULL).isNonNegative() &&
2034 "Invalid case distance");
2035 // Use volatile double here to avoid excess precision issues on some hosts,
2036 // e.g. that use 80-bit X87 registers.
2037 volatile double LDensity =
2038 (double)LSize.roundToDouble() /
2039 (LEnd - First + 1ULL).roundToDouble();
2040 volatile double RDensity =
2041 (double)RSize.roundToDouble() /
2042 (Last - RBegin + 1ULL).roundToDouble();
2043 double Metric = Range.logBase2()*(LDensity+RDensity);
2044 // Should always split in some non-trivial place
2045 DEBUG(dbgs() <<"=>Step\n"
2046 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2047 << "LDensity: " << LDensity
2048 << ", RDensity: " << RDensity << '\n'
2049 << "Metric: " << Metric << '\n');
2050 if (FMetric < Metric) {
2053 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2059 if (areJTsAllowed(TLI)) {
2060 // If our case is dense we *really* should handle it earlier!
2061 assert((FMetric > 0) && "Should handle dense range earlier!");
2063 Pivot = CR.Range.first + Size/2;
2066 CaseRange LHSR(CR.Range.first, Pivot);
2067 CaseRange RHSR(Pivot, CR.Range.second);
2068 Constant *C = Pivot->Low;
2069 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2071 // We know that we branch to the LHS if the Value being switched on is
2072 // less than the Pivot value, C. We use this to optimize our binary
2073 // tree a bit, by recognizing that if SV is greater than or equal to the
2074 // LHS's Case Value, and that Case Value is exactly one less than the
2075 // Pivot's Value, then we can branch directly to the LHS's Target,
2076 // rather than creating a leaf node for it.
2077 if ((LHSR.second - LHSR.first) == 1 &&
2078 LHSR.first->High == CR.GE &&
2079 cast<ConstantInt>(C)->getValue() ==
2080 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2081 TrueBB = LHSR.first->BB;
2083 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2084 CurMF->insert(BBI, TrueBB);
2085 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2087 // Put SV in a virtual register to make it available from the new blocks.
2088 ExportFromCurrentBlock(SV);
2091 // Similar to the optimization above, if the Value being switched on is
2092 // known to be less than the Constant CR.LT, and the current Case Value
2093 // is CR.LT - 1, then we can branch directly to the target block for
2094 // the current Case Value, rather than emitting a RHS leaf node for it.
2095 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2096 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2097 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2098 FalseBB = RHSR.first->BB;
2100 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2101 CurMF->insert(BBI, FalseBB);
2102 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2104 // Put SV in a virtual register to make it available from the new blocks.
2105 ExportFromCurrentBlock(SV);
2108 // Create a CaseBlock record representing a conditional branch to
2109 // the LHS node if the value being switched on SV is less than C.
2110 // Otherwise, branch to LHS.
2111 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2113 if (CR.CaseBB == SwitchBB)
2114 visitSwitchCase(CB, SwitchBB);
2116 SwitchCases.push_back(CB);
2121 /// handleBitTestsSwitchCase - if current case range has few destination and
2122 /// range span less, than machine word bitwidth, encode case range into series
2123 /// of masks and emit bit tests with these masks.
2124 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2125 CaseRecVector& WorkList,
2127 MachineBasicBlock* Default,
2128 MachineBasicBlock *SwitchBB){
2129 EVT PTy = TLI.getPointerTy();
2130 unsigned IntPtrBits = PTy.getSizeInBits();
2132 Case& FrontCase = *CR.Range.first;
2133 Case& BackCase = *(CR.Range.second-1);
2135 // Get the MachineFunction which holds the current MBB. This is used when
2136 // inserting any additional MBBs necessary to represent the switch.
2137 MachineFunction *CurMF = FuncInfo.MF;
2139 // If target does not have legal shift left, do not emit bit tests at all.
2140 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2144 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2146 // Single case counts one, case range - two.
2147 numCmps += (I->Low == I->High ? 1 : 2);
2150 // Count unique destinations
2151 SmallSet<MachineBasicBlock*, 4> Dests;
2152 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2153 Dests.insert(I->BB);
2154 if (Dests.size() > 3)
2155 // Don't bother the code below, if there are too much unique destinations
2158 DEBUG(dbgs() << "Total number of unique destinations: "
2159 << Dests.size() << '\n'
2160 << "Total number of comparisons: " << numCmps << '\n');
2162 // Compute span of values.
2163 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2164 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2165 APInt cmpRange = maxValue - minValue;
2167 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2168 << "Low bound: " << minValue << '\n'
2169 << "High bound: " << maxValue << '\n');
2171 if (cmpRange.uge(IntPtrBits) ||
2172 (!(Dests.size() == 1 && numCmps >= 3) &&
2173 !(Dests.size() == 2 && numCmps >= 5) &&
2174 !(Dests.size() >= 3 && numCmps >= 6)))
2177 DEBUG(dbgs() << "Emitting bit tests\n");
2178 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2180 // Optimize the case where all the case values fit in a
2181 // word without having to subtract minValue. In this case,
2182 // we can optimize away the subtraction.
2183 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2184 cmpRange = maxValue;
2186 lowBound = minValue;
2189 CaseBitsVector CasesBits;
2190 unsigned i, count = 0;
2192 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2193 MachineBasicBlock* Dest = I->BB;
2194 for (i = 0; i < count; ++i)
2195 if (Dest == CasesBits[i].BB)
2199 assert((count < 3) && "Too much destinations to test!");
2200 CasesBits.push_back(CaseBits(0, Dest, 0));
2204 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2205 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2207 uint64_t lo = (lowValue - lowBound).getZExtValue();
2208 uint64_t hi = (highValue - lowBound).getZExtValue();
2210 for (uint64_t j = lo; j <= hi; j++) {
2211 CasesBits[i].Mask |= 1ULL << j;
2212 CasesBits[i].Bits++;
2216 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2220 // Figure out which block is immediately after the current one.
2221 MachineFunction::iterator BBI = CR.CaseBB;
2224 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2226 DEBUG(dbgs() << "Cases:\n");
2227 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2228 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2229 << ", Bits: " << CasesBits[i].Bits
2230 << ", BB: " << CasesBits[i].BB << '\n');
2232 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2233 CurMF->insert(BBI, CaseBB);
2234 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2238 // Put SV in a virtual register to make it available from the new blocks.
2239 ExportFromCurrentBlock(SV);
2242 BitTestBlock BTB(lowBound, cmpRange, SV,
2243 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2244 CR.CaseBB, Default, BTC);
2246 if (CR.CaseBB == SwitchBB)
2247 visitBitTestHeader(BTB, SwitchBB);
2249 BitTestCases.push_back(BTB);
2254 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2255 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2256 const SwitchInst& SI) {
2259 // Start with "simple" cases
2260 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2261 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2262 Cases.push_back(Case(SI.getSuccessorValue(i),
2263 SI.getSuccessorValue(i),
2266 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2268 // Merge case into clusters
2269 if (Cases.size() >= 2)
2270 // Must recompute end() each iteration because it may be
2271 // invalidated by erase if we hold on to it
2272 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2273 J != Cases.end(); ) {
2274 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2275 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2276 MachineBasicBlock* nextBB = J->BB;
2277 MachineBasicBlock* currentBB = I->BB;
2279 // If the two neighboring cases go to the same destination, merge them
2280 // into a single case.
2281 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2289 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2290 if (I->Low != I->High)
2291 // A range counts double, since it requires two compares.
2298 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2299 MachineBasicBlock *Last) {
2301 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2302 if (JTCases[i].first.HeaderBB == First)
2303 JTCases[i].first.HeaderBB = Last;
2305 // Update BitTestCases.
2306 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2307 if (BitTestCases[i].Parent == First)
2308 BitTestCases[i].Parent = Last;
2311 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2312 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2314 // Figure out which block is immediately after the current one.
2315 MachineBasicBlock *NextBlock = 0;
2316 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2318 // If there is only the default destination, branch to it if it is not the
2319 // next basic block. Otherwise, just fall through.
2320 if (SI.getNumOperands() == 2) {
2321 // Update machine-CFG edges.
2323 // If this is not a fall-through branch, emit the branch.
2324 SwitchMBB->addSuccessor(Default);
2325 if (Default != NextBlock)
2326 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2327 MVT::Other, getControlRoot(),
2328 DAG.getBasicBlock(Default)));
2333 // If there are any non-default case statements, create a vector of Cases
2334 // representing each one, and sort the vector so that we can efficiently
2335 // create a binary search tree from them.
2337 size_t numCmps = Clusterify(Cases, SI);
2338 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2339 << ". Total compares: " << numCmps << '\n');
2342 // Get the Value to be switched on and default basic blocks, which will be
2343 // inserted into CaseBlock records, representing basic blocks in the binary
2345 const Value *SV = SI.getOperand(0);
2347 // Push the initial CaseRec onto the worklist
2348 CaseRecVector WorkList;
2349 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2350 CaseRange(Cases.begin(),Cases.end())));
2352 while (!WorkList.empty()) {
2353 // Grab a record representing a case range to process off the worklist
2354 CaseRec CR = WorkList.back();
2355 WorkList.pop_back();
2357 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2360 // If the range has few cases (two or less) emit a series of specific
2362 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2365 // If the switch has more than 5 blocks, and at least 40% dense, and the
2366 // target supports indirect branches, then emit a jump table rather than
2367 // lowering the switch to a binary tree of conditional branches.
2368 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2371 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2372 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2373 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2377 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2378 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2380 // Update machine-CFG edges with unique successors.
2381 SmallVector<BasicBlock*, 32> succs;
2382 succs.reserve(I.getNumSuccessors());
2383 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2384 succs.push_back(I.getSuccessor(i));
2385 array_pod_sort(succs.begin(), succs.end());
2386 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2387 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2388 IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2390 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2391 MVT::Other, getControlRoot(),
2392 getValue(I.getAddress())));
2395 void SelectionDAGBuilder::visitFSub(const User &I) {
2396 // -0.0 - X --> fneg
2397 const Type *Ty = I.getType();
2398 if (isa<Constant>(I.getOperand(0)) &&
2399 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2400 SDValue Op2 = getValue(I.getOperand(1));
2401 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2402 Op2.getValueType(), Op2));
2406 visitBinary(I, ISD::FSUB);
2409 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2410 SDValue Op1 = getValue(I.getOperand(0));
2411 SDValue Op2 = getValue(I.getOperand(1));
2412 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2413 Op1.getValueType(), Op1, Op2));
2416 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2417 SDValue Op1 = getValue(I.getOperand(0));
2418 SDValue Op2 = getValue(I.getOperand(1));
2420 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
2422 // Coerce the shift amount to the right type if we can.
2423 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2424 unsigned ShiftSize = ShiftTy.getSizeInBits();
2425 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2426 DebugLoc DL = getCurDebugLoc();
2428 // If the operand is smaller than the shift count type, promote it.
2429 if (ShiftSize > Op2Size)
2430 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2432 // If the operand is larger than the shift count type but the shift
2433 // count type has enough bits to represent any shift value, truncate
2434 // it now. This is a common case and it exposes the truncate to
2435 // optimization early.
2436 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2437 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2438 // Otherwise we'll need to temporarily settle for some other convenient
2439 // type. Type legalization will make adjustments once the shiftee is split.
2441 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2444 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2445 Op1.getValueType(), Op1, Op2));
2448 void SelectionDAGBuilder::visitICmp(const User &I) {
2449 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2450 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2451 predicate = IC->getPredicate();
2452 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2453 predicate = ICmpInst::Predicate(IC->getPredicate());
2454 SDValue Op1 = getValue(I.getOperand(0));
2455 SDValue Op2 = getValue(I.getOperand(1));
2456 ISD::CondCode Opcode = getICmpCondCode(predicate);
2458 EVT DestVT = TLI.getValueType(I.getType());
2459 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2462 void SelectionDAGBuilder::visitFCmp(const User &I) {
2463 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2464 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2465 predicate = FC->getPredicate();
2466 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2467 predicate = FCmpInst::Predicate(FC->getPredicate());
2468 SDValue Op1 = getValue(I.getOperand(0));
2469 SDValue Op2 = getValue(I.getOperand(1));
2470 ISD::CondCode Condition = getFCmpCondCode(predicate);
2471 EVT DestVT = TLI.getValueType(I.getType());
2472 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2475 void SelectionDAGBuilder::visitSelect(const User &I) {
2476 SmallVector<EVT, 4> ValueVTs;
2477 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2478 unsigned NumValues = ValueVTs.size();
2479 if (NumValues == 0) return;
2481 SmallVector<SDValue, 4> Values(NumValues);
2482 SDValue Cond = getValue(I.getOperand(0));
2483 SDValue TrueVal = getValue(I.getOperand(1));
2484 SDValue FalseVal = getValue(I.getOperand(2));
2486 for (unsigned i = 0; i != NumValues; ++i)
2487 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2488 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2490 SDValue(TrueVal.getNode(),
2491 TrueVal.getResNo() + i),
2492 SDValue(FalseVal.getNode(),
2493 FalseVal.getResNo() + i));
2495 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2496 DAG.getVTList(&ValueVTs[0], NumValues),
2497 &Values[0], NumValues));
2500 void SelectionDAGBuilder::visitTrunc(const User &I) {
2501 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2502 SDValue N = getValue(I.getOperand(0));
2503 EVT DestVT = TLI.getValueType(I.getType());
2504 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2507 void SelectionDAGBuilder::visitZExt(const User &I) {
2508 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2509 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2510 SDValue N = getValue(I.getOperand(0));
2511 EVT DestVT = TLI.getValueType(I.getType());
2512 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2515 void SelectionDAGBuilder::visitSExt(const User &I) {
2516 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2517 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2518 SDValue N = getValue(I.getOperand(0));
2519 EVT DestVT = TLI.getValueType(I.getType());
2520 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2523 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2524 // FPTrunc is never a no-op cast, no need to check
2525 SDValue N = getValue(I.getOperand(0));
2526 EVT DestVT = TLI.getValueType(I.getType());
2527 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2528 DestVT, N, DAG.getIntPtrConstant(0)));
2531 void SelectionDAGBuilder::visitFPExt(const User &I){
2532 // FPTrunc is never a no-op cast, no need to check
2533 SDValue N = getValue(I.getOperand(0));
2534 EVT DestVT = TLI.getValueType(I.getType());
2535 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2538 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2539 // FPToUI is never a no-op cast, no need to check
2540 SDValue N = getValue(I.getOperand(0));
2541 EVT DestVT = TLI.getValueType(I.getType());
2542 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2545 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2546 // FPToSI is never a no-op cast, no need to check
2547 SDValue N = getValue(I.getOperand(0));
2548 EVT DestVT = TLI.getValueType(I.getType());
2549 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2552 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2553 // UIToFP is never a no-op cast, no need to check
2554 SDValue N = getValue(I.getOperand(0));
2555 EVT DestVT = TLI.getValueType(I.getType());
2556 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2559 void SelectionDAGBuilder::visitSIToFP(const User &I){
2560 // SIToFP is never a no-op cast, no need to check
2561 SDValue N = getValue(I.getOperand(0));
2562 EVT DestVT = TLI.getValueType(I.getType());
2563 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2566 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2567 // What to do depends on the size of the integer and the size of the pointer.
2568 // We can either truncate, zero extend, or no-op, accordingly.
2569 SDValue N = getValue(I.getOperand(0));
2570 EVT DestVT = TLI.getValueType(I.getType());
2571 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2574 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2575 // What to do depends on the size of the integer and the size of the pointer.
2576 // We can either truncate, zero extend, or no-op, accordingly.
2577 SDValue N = getValue(I.getOperand(0));
2578 EVT DestVT = TLI.getValueType(I.getType());
2579 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2582 void SelectionDAGBuilder::visitBitCast(const User &I) {
2583 SDValue N = getValue(I.getOperand(0));
2584 EVT DestVT = TLI.getValueType(I.getType());
2586 // BitCast assures us that source and destination are the same size so this is
2587 // either a BITCAST or a no-op.
2588 if (DestVT != N.getValueType())
2589 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
2590 DestVT, N)); // convert types.
2592 setValue(&I, N); // noop cast.
2595 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2596 SDValue InVec = getValue(I.getOperand(0));
2597 SDValue InVal = getValue(I.getOperand(1));
2598 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2600 getValue(I.getOperand(2)));
2601 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2602 TLI.getValueType(I.getType()),
2603 InVec, InVal, InIdx));
2606 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2607 SDValue InVec = getValue(I.getOperand(0));
2608 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2610 getValue(I.getOperand(1)));
2611 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2612 TLI.getValueType(I.getType()), InVec, InIdx));
2615 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2616 // from SIndx and increasing to the element length (undefs are allowed).
2617 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2618 unsigned MaskNumElts = Mask.size();
2619 for (unsigned i = 0; i != MaskNumElts; ++i)
2620 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2625 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2626 SmallVector<int, 8> Mask;
2627 SDValue Src1 = getValue(I.getOperand(0));
2628 SDValue Src2 = getValue(I.getOperand(1));
2630 // Convert the ConstantVector mask operand into an array of ints, with -1
2631 // representing undef values.
2632 SmallVector<Constant*, 8> MaskElts;
2633 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2634 unsigned MaskNumElts = MaskElts.size();
2635 for (unsigned i = 0; i != MaskNumElts; ++i) {
2636 if (isa<UndefValue>(MaskElts[i]))
2639 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2642 EVT VT = TLI.getValueType(I.getType());
2643 EVT SrcVT = Src1.getValueType();
2644 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2646 if (SrcNumElts == MaskNumElts) {
2647 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2652 // Normalize the shuffle vector since mask and vector length don't match.
2653 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2654 // Mask is longer than the source vectors and is a multiple of the source
2655 // vectors. We can use concatenate vector to make the mask and vectors
2657 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2658 // The shuffle is concatenating two vectors together.
2659 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2664 // Pad both vectors with undefs to make them the same length as the mask.
2665 unsigned NumConcat = MaskNumElts / SrcNumElts;
2666 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2667 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2668 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2670 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2671 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2675 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2676 getCurDebugLoc(), VT,
2677 &MOps1[0], NumConcat);
2678 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2679 getCurDebugLoc(), VT,
2680 &MOps2[0], NumConcat);
2682 // Readjust mask for new input vector length.
2683 SmallVector<int, 8> MappedOps;
2684 for (unsigned i = 0; i != MaskNumElts; ++i) {
2686 if (Idx < (int)SrcNumElts)
2687 MappedOps.push_back(Idx);
2689 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2692 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2697 if (SrcNumElts > MaskNumElts) {
2698 // Analyze the access pattern of the vector to see if we can extract
2699 // two subvectors and do the shuffle. The analysis is done by calculating
2700 // the range of elements the mask access on both vectors.
2701 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2702 int MaxRange[2] = {-1, -1};
2704 for (unsigned i = 0; i != MaskNumElts; ++i) {
2710 if (Idx >= (int)SrcNumElts) {
2714 if (Idx > MaxRange[Input])
2715 MaxRange[Input] = Idx;
2716 if (Idx < MinRange[Input])
2717 MinRange[Input] = Idx;
2720 // Check if the access is smaller than the vector size and can we find
2721 // a reasonable extract index.
2722 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2724 int StartIdx[2]; // StartIdx to extract from
2725 for (int Input=0; Input < 2; ++Input) {
2726 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2727 RangeUse[Input] = 0; // Unused
2728 StartIdx[Input] = 0;
2729 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2730 // Fits within range but we should see if we can find a good
2731 // start index that is a multiple of the mask length.
2732 if (MaxRange[Input] < (int)MaskNumElts) {
2733 RangeUse[Input] = 1; // Extract from beginning of the vector
2734 StartIdx[Input] = 0;
2736 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2737 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2738 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2739 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2744 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2745 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2748 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2749 // Extract appropriate subvector and generate a vector shuffle
2750 for (int Input=0; Input < 2; ++Input) {
2751 SDValue &Src = Input == 0 ? Src1 : Src2;
2752 if (RangeUse[Input] == 0)
2753 Src = DAG.getUNDEF(VT);
2755 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2756 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2759 // Calculate new mask.
2760 SmallVector<int, 8> MappedOps;
2761 for (unsigned i = 0; i != MaskNumElts; ++i) {
2764 MappedOps.push_back(Idx);
2765 else if (Idx < (int)SrcNumElts)
2766 MappedOps.push_back(Idx - StartIdx[0]);
2768 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2771 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2777 // We can't use either concat vectors or extract subvectors so fall back to
2778 // replacing the shuffle with extract and build vector.
2779 // to insert and build vector.
2780 EVT EltVT = VT.getVectorElementType();
2781 EVT PtrVT = TLI.getPointerTy();
2782 SmallVector<SDValue,8> Ops;
2783 for (unsigned i = 0; i != MaskNumElts; ++i) {
2785 Ops.push_back(DAG.getUNDEF(EltVT));
2790 if (Idx < (int)SrcNumElts)
2791 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2792 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2794 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2796 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2802 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2803 VT, &Ops[0], Ops.size()));
2806 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2807 const Value *Op0 = I.getOperand(0);
2808 const Value *Op1 = I.getOperand(1);
2809 const Type *AggTy = I.getType();
2810 const Type *ValTy = Op1->getType();
2811 bool IntoUndef = isa<UndefValue>(Op0);
2812 bool FromUndef = isa<UndefValue>(Op1);
2814 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end());
2816 SmallVector<EVT, 4> AggValueVTs;
2817 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2818 SmallVector<EVT, 4> ValValueVTs;
2819 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2821 unsigned NumAggValues = AggValueVTs.size();
2822 unsigned NumValValues = ValValueVTs.size();
2823 SmallVector<SDValue, 4> Values(NumAggValues);
2825 SDValue Agg = getValue(Op0);
2827 // Copy the beginning value(s) from the original aggregate.
2828 for (; i != LinearIndex; ++i)
2829 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2830 SDValue(Agg.getNode(), Agg.getResNo() + i);
2831 // Copy values from the inserted value(s).
2833 SDValue Val = getValue(Op1);
2834 for (; i != LinearIndex + NumValValues; ++i)
2835 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2836 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2838 // Copy remaining value(s) from the original aggregate.
2839 for (; i != NumAggValues; ++i)
2840 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2841 SDValue(Agg.getNode(), Agg.getResNo() + i);
2843 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2844 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2845 &Values[0], NumAggValues));
2848 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2849 const Value *Op0 = I.getOperand(0);
2850 const Type *AggTy = Op0->getType();
2851 const Type *ValTy = I.getType();
2852 bool OutOfUndef = isa<UndefValue>(Op0);
2854 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end());
2856 SmallVector<EVT, 4> ValValueVTs;
2857 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2859 unsigned NumValValues = ValValueVTs.size();
2861 // Ignore a extractvalue that produces an empty object
2862 if (!NumValValues) {
2863 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2867 SmallVector<SDValue, 4> Values(NumValValues);
2869 SDValue Agg = getValue(Op0);
2870 // Copy out the selected value(s).
2871 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2872 Values[i - LinearIndex] =
2874 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2875 SDValue(Agg.getNode(), Agg.getResNo() + i);
2877 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2878 DAG.getVTList(&ValValueVTs[0], NumValValues),
2879 &Values[0], NumValValues));
2882 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2883 SDValue N = getValue(I.getOperand(0));
2884 const Type *Ty = I.getOperand(0)->getType();
2886 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2888 const Value *Idx = *OI;
2889 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2890 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2893 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2894 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2895 DAG.getIntPtrConstant(Offset));
2898 Ty = StTy->getElementType(Field);
2900 Ty = cast<SequentialType>(Ty)->getElementType();
2902 // If this is a constant subscript, handle it quickly.
2903 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2904 if (CI->isZero()) continue;
2906 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2908 EVT PTy = TLI.getPointerTy();
2909 unsigned PtrBits = PTy.getSizeInBits();
2911 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2913 DAG.getConstant(Offs, MVT::i64));
2915 OffsVal = DAG.getIntPtrConstant(Offs);
2917 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2922 // N = N + Idx * ElementSize;
2923 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2924 TD->getTypeAllocSize(Ty));
2925 SDValue IdxN = getValue(Idx);
2927 // If the index is smaller or larger than intptr_t, truncate or extend
2929 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2931 // If this is a multiply by a power of two, turn it into a shl
2932 // immediately. This is a very common case.
2933 if (ElementSize != 1) {
2934 if (ElementSize.isPowerOf2()) {
2935 unsigned Amt = ElementSize.logBase2();
2936 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2937 N.getValueType(), IdxN,
2938 DAG.getConstant(Amt, TLI.getPointerTy()));
2940 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2941 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2942 N.getValueType(), IdxN, Scale);
2946 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2947 N.getValueType(), N, IdxN);
2954 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2955 // If this is a fixed sized alloca in the entry block of the function,
2956 // allocate it statically on the stack.
2957 if (FuncInfo.StaticAllocaMap.count(&I))
2958 return; // getValue will auto-populate this.
2960 const Type *Ty = I.getAllocatedType();
2961 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2963 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2966 SDValue AllocSize = getValue(I.getArraySize());
2968 EVT IntPtr = TLI.getPointerTy();
2969 if (AllocSize.getValueType() != IntPtr)
2970 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2972 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
2974 DAG.getConstant(TySize, IntPtr));
2976 // Handle alignment. If the requested alignment is less than or equal to
2977 // the stack alignment, ignore it. If the size is greater than or equal to
2978 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2979 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
2980 if (Align <= StackAlign)
2983 // Round the size of the allocation up to the stack alignment size
2984 // by add SA-1 to the size.
2985 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2986 AllocSize.getValueType(), AllocSize,
2987 DAG.getIntPtrConstant(StackAlign-1));
2989 // Mask out the low bits for alignment purposes.
2990 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2991 AllocSize.getValueType(), AllocSize,
2992 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2994 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2995 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2996 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2999 DAG.setRoot(DSA.getValue(1));
3001 // Inform the Frame Information that we have just allocated a variable-sized
3003 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
3006 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3007 const Value *SV = I.getOperand(0);
3008 SDValue Ptr = getValue(SV);
3010 const Type *Ty = I.getType();
3012 bool isVolatile = I.isVolatile();
3013 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3014 unsigned Alignment = I.getAlignment();
3015 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3017 SmallVector<EVT, 4> ValueVTs;
3018 SmallVector<uint64_t, 4> Offsets;
3019 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3020 unsigned NumValues = ValueVTs.size();
3025 bool ConstantMemory = false;
3026 if (I.isVolatile() || NumValues > MaxParallelChains)
3027 // Serialize volatile loads with other side effects.
3029 else if (AA->pointsToConstantMemory(
3030 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3031 // Do not serialize (non-volatile) loads of constant memory with anything.
3032 Root = DAG.getEntryNode();
3033 ConstantMemory = true;
3035 // Do not serialize non-volatile loads against each other.
3036 Root = DAG.getRoot();
3039 SmallVector<SDValue, 4> Values(NumValues);
3040 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3042 EVT PtrVT = Ptr.getValueType();
3043 unsigned ChainI = 0;
3044 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3045 // Serializing loads here may result in excessive register pressure, and
3046 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3047 // could recover a bit by hoisting nodes upward in the chain by recognizing
3048 // they are side-effect free or do not alias. The optimizer should really
3049 // avoid this case by converting large object/array copies to llvm.memcpy
3050 // (MaxParallelChains should always remain as failsafe).
3051 if (ChainI == MaxParallelChains) {
3052 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3053 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3054 MVT::Other, &Chains[0], ChainI);
3058 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3060 DAG.getConstant(Offsets[i], PtrVT));
3061 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
3062 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3063 isNonTemporal, Alignment, TBAAInfo);
3066 Chains[ChainI] = L.getValue(1);
3069 if (!ConstantMemory) {
3070 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3071 MVT::Other, &Chains[0], ChainI);
3075 PendingLoads.push_back(Chain);
3078 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3079 DAG.getVTList(&ValueVTs[0], NumValues),
3080 &Values[0], NumValues));
3083 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3084 const Value *SrcV = I.getOperand(0);
3085 const Value *PtrV = I.getOperand(1);
3087 SmallVector<EVT, 4> ValueVTs;
3088 SmallVector<uint64_t, 4> Offsets;
3089 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3090 unsigned NumValues = ValueVTs.size();
3094 // Get the lowered operands. Note that we do this after
3095 // checking if NumResults is zero, because with zero results
3096 // the operands won't have values in the map.
3097 SDValue Src = getValue(SrcV);
3098 SDValue Ptr = getValue(PtrV);
3100 SDValue Root = getRoot();
3101 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3103 EVT PtrVT = Ptr.getValueType();
3104 bool isVolatile = I.isVolatile();
3105 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3106 unsigned Alignment = I.getAlignment();
3107 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3109 unsigned ChainI = 0;
3110 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3111 // See visitLoad comments.
3112 if (ChainI == MaxParallelChains) {
3113 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3114 MVT::Other, &Chains[0], ChainI);
3118 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3119 DAG.getConstant(Offsets[i], PtrVT));
3120 SDValue St = DAG.getStore(Root, getCurDebugLoc(),
3121 SDValue(Src.getNode(), Src.getResNo() + i),
3122 Add, MachinePointerInfo(PtrV, Offsets[i]),
3123 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3124 Chains[ChainI] = St;
3127 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3128 MVT::Other, &Chains[0], ChainI);
3130 AssignOrderingToNode(StoreNode.getNode());
3131 DAG.setRoot(StoreNode);
3134 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3136 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3137 unsigned Intrinsic) {
3138 bool HasChain = !I.doesNotAccessMemory();
3139 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3141 // Build the operand list.
3142 SmallVector<SDValue, 8> Ops;
3143 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3145 // We don't need to serialize loads against other loads.
3146 Ops.push_back(DAG.getRoot());
3148 Ops.push_back(getRoot());
3152 // Info is set by getTgtMemInstrinsic
3153 TargetLowering::IntrinsicInfo Info;
3154 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3156 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3157 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3158 Info.opc == ISD::INTRINSIC_W_CHAIN)
3159 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3161 // Add all operands of the call to the operand list.
3162 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3163 SDValue Op = getValue(I.getArgOperand(i));
3164 assert(TLI.isTypeLegal(Op.getValueType()) &&
3165 "Intrinsic uses a non-legal type?");
3169 SmallVector<EVT, 4> ValueVTs;
3170 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3172 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3173 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3174 "Intrinsic uses a non-legal type?");
3179 ValueVTs.push_back(MVT::Other);
3181 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3185 if (IsTgtIntrinsic) {
3186 // This is target intrinsic that touches memory
3187 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3188 VTs, &Ops[0], Ops.size(),
3190 MachinePointerInfo(Info.ptrVal, Info.offset),
3191 Info.align, Info.vol,
3192 Info.readMem, Info.writeMem);
3193 } else if (!HasChain) {
3194 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3195 VTs, &Ops[0], Ops.size());
3196 } else if (!I.getType()->isVoidTy()) {
3197 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3198 VTs, &Ops[0], Ops.size());
3200 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3201 VTs, &Ops[0], Ops.size());
3205 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3207 PendingLoads.push_back(Chain);
3212 if (!I.getType()->isVoidTy()) {
3213 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3214 EVT VT = TLI.getValueType(PTy);
3215 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
3218 setValue(&I, Result);
3222 /// GetSignificand - Get the significand and build it into a floating-point
3223 /// number with exponent of 1:
3225 /// Op = (Op & 0x007fffff) | 0x3f800000;
3227 /// where Op is the hexidecimal representation of floating point value.
3229 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3230 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3231 DAG.getConstant(0x007fffff, MVT::i32));
3232 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3233 DAG.getConstant(0x3f800000, MVT::i32));
3234 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3237 /// GetExponent - Get the exponent:
3239 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3241 /// where Op is the hexidecimal representation of floating point value.
3243 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3245 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3246 DAG.getConstant(0x7f800000, MVT::i32));
3247 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3248 DAG.getConstant(23, TLI.getPointerTy()));
3249 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3250 DAG.getConstant(127, MVT::i32));
3251 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3254 /// getF32Constant - Get 32-bit floating point constant.
3256 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3257 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3260 /// Inlined utility function to implement binary input atomic intrinsics for
3261 /// visitIntrinsicCall: I is a call instruction
3262 /// Op is the associated NodeType for I
3264 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
3266 SDValue Root = getRoot();
3268 DAG.getAtomic(Op, getCurDebugLoc(),
3269 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
3271 getValue(I.getArgOperand(0)),
3272 getValue(I.getArgOperand(1)),
3273 I.getArgOperand(0));
3275 DAG.setRoot(L.getValue(1));
3279 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3281 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
3282 SDValue Op1 = getValue(I.getArgOperand(0));
3283 SDValue Op2 = getValue(I.getArgOperand(1));
3285 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3286 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
3290 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3291 /// limited-precision mode.
3293 SelectionDAGBuilder::visitExp(const CallInst &I) {
3295 DebugLoc dl = getCurDebugLoc();
3297 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3298 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3299 SDValue Op = getValue(I.getArgOperand(0));
3301 // Put the exponent in the right bit position for later addition to the
3304 // #define LOG2OFe 1.4426950f
3305 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3306 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3307 getF32Constant(DAG, 0x3fb8aa3b));
3308 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3310 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3311 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3312 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3314 // IntegerPartOfX <<= 23;
3315 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3316 DAG.getConstant(23, TLI.getPointerTy()));
3318 if (LimitFloatPrecision <= 6) {
3319 // For floating-point precision of 6:
3321 // TwoToFractionalPartOfX =
3323 // (0.735607626f + 0.252464424f * x) * x;
3325 // error 0.0144103317, which is 6 bits
3326 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3327 getF32Constant(DAG, 0x3e814304));
3328 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3329 getF32Constant(DAG, 0x3f3c50c8));
3330 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3331 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3332 getF32Constant(DAG, 0x3f7f5e7e));
3333 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
3335 // Add the exponent into the result in integer domain.
3336 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3337 TwoToFracPartOfX, IntegerPartOfX);
3339 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
3340 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3341 // For floating-point precision of 12:
3343 // TwoToFractionalPartOfX =
3346 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3348 // 0.000107046256 error, which is 13 to 14 bits
3349 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3350 getF32Constant(DAG, 0x3da235e3));
3351 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3352 getF32Constant(DAG, 0x3e65b8f3));
3353 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3354 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3355 getF32Constant(DAG, 0x3f324b07));
3356 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3357 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3358 getF32Constant(DAG, 0x3f7ff8fd));
3359 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
3361 // Add the exponent into the result in integer domain.
3362 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3363 TwoToFracPartOfX, IntegerPartOfX);
3365 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
3366 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3367 // For floating-point precision of 18:
3369 // TwoToFractionalPartOfX =
3373 // (0.554906021e-1f +
3374 // (0.961591928e-2f +
3375 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3377 // error 2.47208000*10^(-7), which is better than 18 bits
3378 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3379 getF32Constant(DAG, 0x3924b03e));
3380 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3381 getF32Constant(DAG, 0x3ab24b87));
3382 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3383 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3384 getF32Constant(DAG, 0x3c1d8c17));
3385 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3386 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3387 getF32Constant(DAG, 0x3d634a1d));
3388 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3389 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3390 getF32Constant(DAG, 0x3e75fe14));
3391 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3392 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3393 getF32Constant(DAG, 0x3f317234));
3394 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3395 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3396 getF32Constant(DAG, 0x3f800000));
3397 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
3400 // Add the exponent into the result in integer domain.
3401 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3402 TwoToFracPartOfX, IntegerPartOfX);
3404 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
3407 // No special expansion.
3408 result = DAG.getNode(ISD::FEXP, dl,
3409 getValue(I.getArgOperand(0)).getValueType(),
3410 getValue(I.getArgOperand(0)));
3413 setValue(&I, result);
3416 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3417 /// limited-precision mode.
3419 SelectionDAGBuilder::visitLog(const CallInst &I) {
3421 DebugLoc dl = getCurDebugLoc();
3423 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3424 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3425 SDValue Op = getValue(I.getArgOperand(0));
3426 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3428 // Scale the exponent by log(2) [0.69314718f].
3429 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3430 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3431 getF32Constant(DAG, 0x3f317218));
3433 // Get the significand and build it into a floating-point number with
3435 SDValue X = GetSignificand(DAG, Op1, dl);
3437 if (LimitFloatPrecision <= 6) {
3438 // For floating-point precision of 6:
3442 // (1.4034025f - 0.23903021f * x) * x;
3444 // error 0.0034276066, which is better than 8 bits
3445 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3446 getF32Constant(DAG, 0xbe74c456));
3447 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3448 getF32Constant(DAG, 0x3fb3a2b1));
3449 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3450 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3451 getF32Constant(DAG, 0x3f949a29));
3453 result = DAG.getNode(ISD::FADD, dl,
3454 MVT::f32, LogOfExponent, LogOfMantissa);
3455 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3456 // For floating-point precision of 12:
3462 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3464 // error 0.000061011436, which is 14 bits
3465 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3466 getF32Constant(DAG, 0xbd67b6d6));
3467 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3468 getF32Constant(DAG, 0x3ee4f4b8));
3469 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3470 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3471 getF32Constant(DAG, 0x3fbc278b));
3472 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3473 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3474 getF32Constant(DAG, 0x40348e95));
3475 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3476 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3477 getF32Constant(DAG, 0x3fdef31a));
3479 result = DAG.getNode(ISD::FADD, dl,
3480 MVT::f32, LogOfExponent, LogOfMantissa);
3481 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3482 // For floating-point precision of 18:
3490 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3492 // error 0.0000023660568, which is better than 18 bits
3493 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3494 getF32Constant(DAG, 0xbc91e5ac));
3495 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3496 getF32Constant(DAG, 0x3e4350aa));
3497 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3498 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3499 getF32Constant(DAG, 0x3f60d3e3));
3500 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3501 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3502 getF32Constant(DAG, 0x4011cdf0));
3503 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3504 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3505 getF32Constant(DAG, 0x406cfd1c));
3506 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3507 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3508 getF32Constant(DAG, 0x408797cb));
3509 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3510 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3511 getF32Constant(DAG, 0x4006dcab));
3513 result = DAG.getNode(ISD::FADD, dl,
3514 MVT::f32, LogOfExponent, LogOfMantissa);
3517 // No special expansion.
3518 result = DAG.getNode(ISD::FLOG, dl,
3519 getValue(I.getArgOperand(0)).getValueType(),
3520 getValue(I.getArgOperand(0)));
3523 setValue(&I, result);
3526 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3527 /// limited-precision mode.
3529 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3531 DebugLoc dl = getCurDebugLoc();
3533 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3534 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3535 SDValue Op = getValue(I.getArgOperand(0));
3536 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3538 // Get the exponent.
3539 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3541 // Get the significand and build it into a floating-point number with
3543 SDValue X = GetSignificand(DAG, Op1, dl);
3545 // Different possible minimax approximations of significand in
3546 // floating-point for various degrees of accuracy over [1,2].
3547 if (LimitFloatPrecision <= 6) {
3548 // For floating-point precision of 6:
3550 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3552 // error 0.0049451742, which is more than 7 bits
3553 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3554 getF32Constant(DAG, 0xbeb08fe0));
3555 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3556 getF32Constant(DAG, 0x40019463));
3557 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3558 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3559 getF32Constant(DAG, 0x3fd6633d));
3561 result = DAG.getNode(ISD::FADD, dl,
3562 MVT::f32, LogOfExponent, Log2ofMantissa);
3563 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3564 // For floating-point precision of 12:
3570 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3572 // error 0.0000876136000, which is better than 13 bits
3573 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3574 getF32Constant(DAG, 0xbda7262e));
3575 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3576 getF32Constant(DAG, 0x3f25280b));
3577 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3578 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3579 getF32Constant(DAG, 0x4007b923));
3580 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3581 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3582 getF32Constant(DAG, 0x40823e2f));
3583 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3584 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3585 getF32Constant(DAG, 0x4020d29c));
3587 result = DAG.getNode(ISD::FADD, dl,
3588 MVT::f32, LogOfExponent, Log2ofMantissa);
3589 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3590 // For floating-point precision of 18:
3599 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3601 // error 0.0000018516, which is better than 18 bits
3602 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3603 getF32Constant(DAG, 0xbcd2769e));
3604 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3605 getF32Constant(DAG, 0x3e8ce0b9));
3606 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3607 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3608 getF32Constant(DAG, 0x3fa22ae7));
3609 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3610 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3611 getF32Constant(DAG, 0x40525723));
3612 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3613 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3614 getF32Constant(DAG, 0x40aaf200));
3615 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3616 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3617 getF32Constant(DAG, 0x40c39dad));
3618 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3619 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3620 getF32Constant(DAG, 0x4042902c));
3622 result = DAG.getNode(ISD::FADD, dl,
3623 MVT::f32, LogOfExponent, Log2ofMantissa);
3626 // No special expansion.
3627 result = DAG.getNode(ISD::FLOG2, dl,
3628 getValue(I.getArgOperand(0)).getValueType(),
3629 getValue(I.getArgOperand(0)));
3632 setValue(&I, result);
3635 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3636 /// limited-precision mode.
3638 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3640 DebugLoc dl = getCurDebugLoc();
3642 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3643 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3644 SDValue Op = getValue(I.getArgOperand(0));
3645 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3647 // Scale the exponent by log10(2) [0.30102999f].
3648 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3649 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3650 getF32Constant(DAG, 0x3e9a209a));
3652 // Get the significand and build it into a floating-point number with
3654 SDValue X = GetSignificand(DAG, Op1, dl);
3656 if (LimitFloatPrecision <= 6) {
3657 // For floating-point precision of 6:
3659 // Log10ofMantissa =
3661 // (0.60948995f - 0.10380950f * x) * x;
3663 // error 0.0014886165, which is 6 bits
3664 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3665 getF32Constant(DAG, 0xbdd49a13));
3666 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3667 getF32Constant(DAG, 0x3f1c0789));
3668 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3669 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3670 getF32Constant(DAG, 0x3f011300));
3672 result = DAG.getNode(ISD::FADD, dl,
3673 MVT::f32, LogOfExponent, Log10ofMantissa);
3674 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3675 // For floating-point precision of 12:
3677 // Log10ofMantissa =
3680 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3682 // error 0.00019228036, which is better than 12 bits
3683 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3684 getF32Constant(DAG, 0x3d431f31));
3685 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3686 getF32Constant(DAG, 0x3ea21fb2));
3687 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3688 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3689 getF32Constant(DAG, 0x3f6ae232));
3690 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3691 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3692 getF32Constant(DAG, 0x3f25f7c3));
3694 result = DAG.getNode(ISD::FADD, dl,
3695 MVT::f32, LogOfExponent, Log10ofMantissa);
3696 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3697 // For floating-point precision of 18:
3699 // Log10ofMantissa =
3704 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3706 // error 0.0000037995730, which is better than 18 bits
3707 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3708 getF32Constant(DAG, 0x3c5d51ce));
3709 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3710 getF32Constant(DAG, 0x3e00685a));
3711 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3712 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3713 getF32Constant(DAG, 0x3efb6798));
3714 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3715 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3716 getF32Constant(DAG, 0x3f88d192));
3717 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3718 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3719 getF32Constant(DAG, 0x3fc4316c));
3720 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3721 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3722 getF32Constant(DAG, 0x3f57ce70));
3724 result = DAG.getNode(ISD::FADD, dl,
3725 MVT::f32, LogOfExponent, Log10ofMantissa);
3728 // No special expansion.
3729 result = DAG.getNode(ISD::FLOG10, dl,
3730 getValue(I.getArgOperand(0)).getValueType(),
3731 getValue(I.getArgOperand(0)));
3734 setValue(&I, result);
3737 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3738 /// limited-precision mode.
3740 SelectionDAGBuilder::visitExp2(const CallInst &I) {
3742 DebugLoc dl = getCurDebugLoc();
3744 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3745 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3746 SDValue Op = getValue(I.getArgOperand(0));
3748 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3750 // FractionalPartOfX = x - (float)IntegerPartOfX;
3751 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3752 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3754 // IntegerPartOfX <<= 23;
3755 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3756 DAG.getConstant(23, TLI.getPointerTy()));
3758 if (LimitFloatPrecision <= 6) {
3759 // For floating-point precision of 6:
3761 // TwoToFractionalPartOfX =
3763 // (0.735607626f + 0.252464424f * x) * x;
3765 // error 0.0144103317, which is 6 bits
3766 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3767 getF32Constant(DAG, 0x3e814304));
3768 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3769 getF32Constant(DAG, 0x3f3c50c8));
3770 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3771 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3772 getF32Constant(DAG, 0x3f7f5e7e));
3773 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
3774 SDValue TwoToFractionalPartOfX =
3775 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3777 result = DAG.getNode(ISD::BITCAST, dl,
3778 MVT::f32, TwoToFractionalPartOfX);
3779 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3780 // For floating-point precision of 12:
3782 // TwoToFractionalPartOfX =
3785 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3787 // error 0.000107046256, which is 13 to 14 bits
3788 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3789 getF32Constant(DAG, 0x3da235e3));
3790 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3791 getF32Constant(DAG, 0x3e65b8f3));
3792 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3793 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3794 getF32Constant(DAG, 0x3f324b07));
3795 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3796 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3797 getF32Constant(DAG, 0x3f7ff8fd));
3798 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
3799 SDValue TwoToFractionalPartOfX =
3800 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3802 result = DAG.getNode(ISD::BITCAST, dl,
3803 MVT::f32, TwoToFractionalPartOfX);
3804 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3805 // For floating-point precision of 18:
3807 // TwoToFractionalPartOfX =
3811 // (0.554906021e-1f +
3812 // (0.961591928e-2f +
3813 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3814 // error 2.47208000*10^(-7), which is better than 18 bits
3815 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3816 getF32Constant(DAG, 0x3924b03e));
3817 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3818 getF32Constant(DAG, 0x3ab24b87));
3819 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3820 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3821 getF32Constant(DAG, 0x3c1d8c17));
3822 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3823 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3824 getF32Constant(DAG, 0x3d634a1d));
3825 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3826 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3827 getF32Constant(DAG, 0x3e75fe14));
3828 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3829 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3830 getF32Constant(DAG, 0x3f317234));
3831 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3832 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3833 getF32Constant(DAG, 0x3f800000));
3834 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
3835 SDValue TwoToFractionalPartOfX =
3836 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3838 result = DAG.getNode(ISD::BITCAST, dl,
3839 MVT::f32, TwoToFractionalPartOfX);
3842 // No special expansion.
3843 result = DAG.getNode(ISD::FEXP2, dl,
3844 getValue(I.getArgOperand(0)).getValueType(),
3845 getValue(I.getArgOperand(0)));
3848 setValue(&I, result);
3851 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3852 /// limited-precision mode with x == 10.0f.
3854 SelectionDAGBuilder::visitPow(const CallInst &I) {
3856 const Value *Val = I.getArgOperand(0);
3857 DebugLoc dl = getCurDebugLoc();
3858 bool IsExp10 = false;
3860 if (getValue(Val).getValueType() == MVT::f32 &&
3861 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
3862 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3863 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3864 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3866 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3871 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3872 SDValue Op = getValue(I.getArgOperand(1));
3874 // Put the exponent in the right bit position for later addition to the
3877 // #define LOG2OF10 3.3219281f
3878 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3879 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3880 getF32Constant(DAG, 0x40549a78));
3881 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3883 // FractionalPartOfX = x - (float)IntegerPartOfX;
3884 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3885 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3887 // IntegerPartOfX <<= 23;
3888 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3889 DAG.getConstant(23, TLI.getPointerTy()));
3891 if (LimitFloatPrecision <= 6) {
3892 // For floating-point precision of 6:
3894 // twoToFractionalPartOfX =
3896 // (0.735607626f + 0.252464424f * x) * x;
3898 // error 0.0144103317, which is 6 bits
3899 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3900 getF32Constant(DAG, 0x3e814304));
3901 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3902 getF32Constant(DAG, 0x3f3c50c8));
3903 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3904 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3905 getF32Constant(DAG, 0x3f7f5e7e));
3906 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
3907 SDValue TwoToFractionalPartOfX =
3908 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3910 result = DAG.getNode(ISD::BITCAST, dl,
3911 MVT::f32, TwoToFractionalPartOfX);
3912 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3913 // For floating-point precision of 12:
3915 // TwoToFractionalPartOfX =
3918 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3920 // error 0.000107046256, which is 13 to 14 bits
3921 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3922 getF32Constant(DAG, 0x3da235e3));
3923 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3924 getF32Constant(DAG, 0x3e65b8f3));
3925 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3926 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3927 getF32Constant(DAG, 0x3f324b07));
3928 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3929 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3930 getF32Constant(DAG, 0x3f7ff8fd));
3931 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
3932 SDValue TwoToFractionalPartOfX =
3933 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3935 result = DAG.getNode(ISD::BITCAST, dl,
3936 MVT::f32, TwoToFractionalPartOfX);
3937 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3938 // For floating-point precision of 18:
3940 // TwoToFractionalPartOfX =
3944 // (0.554906021e-1f +
3945 // (0.961591928e-2f +
3946 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3947 // error 2.47208000*10^(-7), which is better than 18 bits
3948 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3949 getF32Constant(DAG, 0x3924b03e));
3950 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3951 getF32Constant(DAG, 0x3ab24b87));
3952 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3953 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3954 getF32Constant(DAG, 0x3c1d8c17));
3955 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3956 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3957 getF32Constant(DAG, 0x3d634a1d));
3958 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3959 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3960 getF32Constant(DAG, 0x3e75fe14));
3961 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3962 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3963 getF32Constant(DAG, 0x3f317234));
3964 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3965 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3966 getF32Constant(DAG, 0x3f800000));
3967 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
3968 SDValue TwoToFractionalPartOfX =
3969 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3971 result = DAG.getNode(ISD::BITCAST, dl,
3972 MVT::f32, TwoToFractionalPartOfX);
3975 // No special expansion.
3976 result = DAG.getNode(ISD::FPOW, dl,
3977 getValue(I.getArgOperand(0)).getValueType(),
3978 getValue(I.getArgOperand(0)),
3979 getValue(I.getArgOperand(1)));
3982 setValue(&I, result);
3986 /// ExpandPowI - Expand a llvm.powi intrinsic.
3987 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3988 SelectionDAG &DAG) {
3989 // If RHS is a constant, we can expand this out to a multiplication tree,
3990 // otherwise we end up lowering to a call to __powidf2 (for example). When
3991 // optimizing for size, we only want to do this if the expansion would produce
3992 // a small number of multiplies, otherwise we do the full expansion.
3993 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3994 // Get the exponent as a positive value.
3995 unsigned Val = RHSC->getSExtValue();
3996 if ((int)Val < 0) Val = -Val;
3998 // powi(x, 0) -> 1.0
4000 return DAG.getConstantFP(1.0, LHS.getValueType());
4002 const Function *F = DAG.getMachineFunction().getFunction();
4003 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
4004 // If optimizing for size, don't insert too many multiplies. This
4005 // inserts up to 5 multiplies.
4006 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4007 // We use the simple binary decomposition method to generate the multiply
4008 // sequence. There are more optimal ways to do this (for example,
4009 // powi(x,15) generates one more multiply than it should), but this has
4010 // the benefit of being both really simple and much better than a libcall.
4011 SDValue Res; // Logically starts equal to 1.0
4012 SDValue CurSquare = LHS;
4016 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4018 Res = CurSquare; // 1.0*CurSquare.
4021 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4022 CurSquare, CurSquare);
4026 // If the original was negative, invert the result, producing 1/(x*x*x).
4027 if (RHSC->getSExtValue() < 0)
4028 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4029 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4034 // Otherwise, expand to a libcall.
4035 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4038 // getTruncatedArgReg - Find underlying register used for an truncated
4040 static unsigned getTruncatedArgReg(const SDValue &N) {
4041 if (N.getOpcode() != ISD::TRUNCATE)
4044 const SDValue &Ext = N.getOperand(0);
4045 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){
4046 const SDValue &CFR = Ext.getOperand(0);
4047 if (CFR.getOpcode() == ISD::CopyFromReg)
4048 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4050 if (CFR.getOpcode() == ISD::TRUNCATE)
4051 return getTruncatedArgReg(CFR);
4056 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4057 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4058 /// At the end of instruction selection, they will be inserted to the entry BB.
4060 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4063 const Argument *Arg = dyn_cast<Argument>(V);
4067 MachineFunction &MF = DAG.getMachineFunction();
4068 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4069 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4071 // Ignore inlined function arguments here.
4072 DIVariable DV(Variable);
4073 if (DV.isInlinedFnArgument(MF.getFunction()))
4077 if (Arg->hasByValAttr()) {
4078 // Byval arguments' frame index is recorded during argument lowering.
4079 // Use this info directly.
4080 Reg = TRI->getFrameRegister(MF);
4081 Offset = FuncInfo.getByValArgumentFrameIndex(Arg);
4082 // If byval argument ofset is not recorded then ignore this.
4088 if (N.getOpcode() == ISD::CopyFromReg)
4089 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4091 Reg = getTruncatedArgReg(N);
4092 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4093 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4094 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4101 // Check if ValueMap has reg number.
4102 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4103 if (VMI != FuncInfo.ValueMap.end())
4107 if (!Reg && N.getNode()) {
4108 // Check if frame index is available.
4109 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4110 if (FrameIndexSDNode *FINode =
4111 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4112 Reg = TRI->getFrameRegister(MF);
4113 Offset = FINode->getIndex();
4120 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4121 TII->get(TargetOpcode::DBG_VALUE))
4122 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
4123 FuncInfo.ArgDbgValues.push_back(&*MIB);
4127 // VisualStudio defines setjmp as _setjmp
4128 #if defined(_MSC_VER) && defined(setjmp) && \
4129 !defined(setjmp_undefined_for_msvc)
4130 # pragma push_macro("setjmp")
4132 # define setjmp_undefined_for_msvc
4135 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4136 /// we want to emit this as a call to a named external function, return the name
4137 /// otherwise lower it and return null.
4139 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4140 DebugLoc dl = getCurDebugLoc();
4143 switch (Intrinsic) {
4145 // By default, turn this into a target intrinsic node.
4146 visitTargetIntrinsic(I, Intrinsic);
4148 case Intrinsic::vastart: visitVAStart(I); return 0;
4149 case Intrinsic::vaend: visitVAEnd(I); return 0;
4150 case Intrinsic::vacopy: visitVACopy(I); return 0;
4151 case Intrinsic::returnaddress:
4152 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4153 getValue(I.getArgOperand(0))));
4155 case Intrinsic::frameaddress:
4156 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4157 getValue(I.getArgOperand(0))));
4159 case Intrinsic::setjmp:
4160 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4161 case Intrinsic::longjmp:
4162 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4163 case Intrinsic::memcpy: {
4164 // Assert for address < 256 since we support only user defined address
4166 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4168 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4170 "Unknown address space");
4171 SDValue Op1 = getValue(I.getArgOperand(0));
4172 SDValue Op2 = getValue(I.getArgOperand(1));
4173 SDValue Op3 = getValue(I.getArgOperand(2));
4174 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4175 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4176 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
4177 MachinePointerInfo(I.getArgOperand(0)),
4178 MachinePointerInfo(I.getArgOperand(1))));
4181 case Intrinsic::memset: {
4182 // Assert for address < 256 since we support only user defined address
4184 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4186 "Unknown address space");
4187 SDValue Op1 = getValue(I.getArgOperand(0));
4188 SDValue Op2 = getValue(I.getArgOperand(1));
4189 SDValue Op3 = getValue(I.getArgOperand(2));
4190 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4191 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4192 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4193 MachinePointerInfo(I.getArgOperand(0))));
4196 case Intrinsic::memmove: {
4197 // Assert for address < 256 since we support only user defined address
4199 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4201 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4203 "Unknown address space");
4204 SDValue Op1 = getValue(I.getArgOperand(0));
4205 SDValue Op2 = getValue(I.getArgOperand(1));
4206 SDValue Op3 = getValue(I.getArgOperand(2));
4207 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4208 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4209 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4210 MachinePointerInfo(I.getArgOperand(0)),
4211 MachinePointerInfo(I.getArgOperand(1))));
4214 case Intrinsic::dbg_declare: {
4215 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4216 MDNode *Variable = DI.getVariable();
4217 const Value *Address = DI.getAddress();
4218 if (!Address || !DIVariable(DI.getVariable()).Verify())
4221 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4222 // but do not always have a corresponding SDNode built. The SDNodeOrder
4223 // absolute, but not relative, values are different depending on whether
4224 // debug info exists.
4227 // Check if address has undef value.
4228 if (isa<UndefValue>(Address) ||
4229 (Address->use_empty() && !isa<Argument>(Address))) {
4230 DEBUG(dbgs() << "Dropping debug info for " << DI);
4234 SDValue &N = NodeMap[Address];
4235 if (!N.getNode() && isa<Argument>(Address))
4236 // Check unused arguments map.
4237 N = UnusedArgNodeMap[Address];
4240 // Parameters are handled specially.
4242 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
4243 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4244 Address = BCI->getOperand(0);
4245 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4247 if (isParameter && !AI) {
4248 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4250 // Byval parameter. We have a frame index at this point.
4251 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4252 0, dl, SDNodeOrder);
4254 // Address is an argument, so try to emit its dbg value using
4255 // virtual register info from the FuncInfo.ValueMap.
4256 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4260 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4261 0, dl, SDNodeOrder);
4263 // Can't do anything with other non-AI cases yet.
4264 DEBUG(dbgs() << "Dropping debug info for " << DI);
4267 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4269 // If Address is an argument then try to emit its dbg value using
4270 // virtual register info from the FuncInfo.ValueMap.
4271 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4272 // If variable is pinned by a alloca in dominating bb then
4273 // use StaticAllocaMap.
4274 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4275 if (AI->getParent() != DI.getParent()) {
4276 DenseMap<const AllocaInst*, int>::iterator SI =
4277 FuncInfo.StaticAllocaMap.find(AI);
4278 if (SI != FuncInfo.StaticAllocaMap.end()) {
4279 SDV = DAG.getDbgValue(Variable, SI->second,
4280 0, dl, SDNodeOrder);
4281 DAG.AddDbgValue(SDV, 0, false);
4286 DEBUG(dbgs() << "Dropping debug info for " << DI);
4291 case Intrinsic::dbg_value: {
4292 const DbgValueInst &DI = cast<DbgValueInst>(I);
4293 if (!DIVariable(DI.getVariable()).Verify())
4296 MDNode *Variable = DI.getVariable();
4297 uint64_t Offset = DI.getOffset();
4298 const Value *V = DI.getValue();
4302 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4303 // but do not always have a corresponding SDNode built. The SDNodeOrder
4304 // absolute, but not relative, values are different depending on whether
4305 // debug info exists.
4308 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
4309 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4310 DAG.AddDbgValue(SDV, 0, false);
4312 // Do not use getValue() in here; we don't want to generate code at
4313 // this point if it hasn't been done yet.
4314 SDValue N = NodeMap[V];
4315 if (!N.getNode() && isa<Argument>(V))
4316 // Check unused arguments map.
4317 N = UnusedArgNodeMap[V];
4319 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4320 SDV = DAG.getDbgValue(Variable, N.getNode(),
4321 N.getResNo(), Offset, dl, SDNodeOrder);
4322 DAG.AddDbgValue(SDV, N.getNode(), false);
4324 } else if (!V->use_empty() ) {
4325 // Do not call getValue(V) yet, as we don't want to generate code.
4326 // Remember it for later.
4327 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4328 DanglingDebugInfoMap[V] = DDI;
4330 // We may expand this to cover more cases. One case where we have no
4331 // data available is an unreferenced parameter.
4332 DEBUG(dbgs() << "Dropping debug info for " << DI);
4336 // Build a debug info table entry.
4337 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4338 V = BCI->getOperand(0);
4339 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4340 // Don't handle byval struct arguments or VLAs, for example.
4343 DenseMap<const AllocaInst*, int>::iterator SI =
4344 FuncInfo.StaticAllocaMap.find(AI);
4345 if (SI == FuncInfo.StaticAllocaMap.end())
4347 int FI = SI->second;
4349 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4350 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4351 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4354 case Intrinsic::eh_exception: {
4355 // Insert the EXCEPTIONADDR instruction.
4356 assert(FuncInfo.MBB->isLandingPad() &&
4357 "Call to eh.exception not in landing pad!");
4358 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4360 Ops[0] = DAG.getRoot();
4361 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4363 DAG.setRoot(Op.getValue(1));
4367 case Intrinsic::eh_selector: {
4368 MachineBasicBlock *CallMBB = FuncInfo.MBB;
4369 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4370 if (CallMBB->isLandingPad())
4371 AddCatchInfo(I, &MMI, CallMBB);
4374 FuncInfo.CatchInfoLost.insert(&I);
4376 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4377 unsigned Reg = TLI.getExceptionSelectorRegister();
4378 if (Reg) FuncInfo.MBB->addLiveIn(Reg);
4381 // Insert the EHSELECTION instruction.
4382 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4384 Ops[0] = getValue(I.getArgOperand(0));
4386 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4387 DAG.setRoot(Op.getValue(1));
4388 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4392 case Intrinsic::eh_typeid_for: {
4393 // Find the type id for the given typeinfo.
4394 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4395 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4396 Res = DAG.getConstant(TypeID, MVT::i32);
4401 case Intrinsic::eh_return_i32:
4402 case Intrinsic::eh_return_i64:
4403 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4404 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4407 getValue(I.getArgOperand(0)),
4408 getValue(I.getArgOperand(1))));
4410 case Intrinsic::eh_unwind_init:
4411 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4413 case Intrinsic::eh_dwarf_cfa: {
4414 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
4415 TLI.getPointerTy());
4416 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4418 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4419 TLI.getPointerTy()),
4421 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4423 DAG.getConstant(0, TLI.getPointerTy()));
4424 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4428 case Intrinsic::eh_sjlj_callsite: {
4429 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4430 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4431 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4432 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4434 MMI.setCurrentCallSite(CI->getZExtValue());
4437 case Intrinsic::eh_sjlj_setjmp: {
4438 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(),
4439 getValue(I.getArgOperand(0))));
4442 case Intrinsic::eh_sjlj_longjmp: {
4443 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
4444 getRoot(), getValue(I.getArgOperand(0))));
4447 case Intrinsic::eh_sjlj_dispatch_setup: {
4448 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
4449 getRoot(), getValue(I.getArgOperand(0))));
4453 case Intrinsic::x86_mmx_pslli_w:
4454 case Intrinsic::x86_mmx_pslli_d:
4455 case Intrinsic::x86_mmx_pslli_q:
4456 case Intrinsic::x86_mmx_psrli_w:
4457 case Intrinsic::x86_mmx_psrli_d:
4458 case Intrinsic::x86_mmx_psrli_q:
4459 case Intrinsic::x86_mmx_psrai_w:
4460 case Intrinsic::x86_mmx_psrai_d: {
4461 SDValue ShAmt = getValue(I.getArgOperand(1));
4462 if (isa<ConstantSDNode>(ShAmt)) {
4463 visitTargetIntrinsic(I, Intrinsic);
4466 unsigned NewIntrinsic = 0;
4467 EVT ShAmtVT = MVT::v2i32;
4468 switch (Intrinsic) {
4469 case Intrinsic::x86_mmx_pslli_w:
4470 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4472 case Intrinsic::x86_mmx_pslli_d:
4473 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4475 case Intrinsic::x86_mmx_pslli_q:
4476 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4478 case Intrinsic::x86_mmx_psrli_w:
4479 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4481 case Intrinsic::x86_mmx_psrli_d:
4482 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4484 case Intrinsic::x86_mmx_psrli_q:
4485 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4487 case Intrinsic::x86_mmx_psrai_w:
4488 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4490 case Intrinsic::x86_mmx_psrai_d:
4491 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4493 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4496 // The vector shift intrinsics with scalars uses 32b shift amounts but
4497 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4499 // We must do this early because v2i32 is not a legal type.
4500 DebugLoc dl = getCurDebugLoc();
4503 ShOps[1] = DAG.getConstant(0, MVT::i32);
4504 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4505 EVT DestVT = TLI.getValueType(I.getType());
4506 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
4507 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4508 DAG.getConstant(NewIntrinsic, MVT::i32),
4509 getValue(I.getArgOperand(0)), ShAmt);
4513 case Intrinsic::convertff:
4514 case Intrinsic::convertfsi:
4515 case Intrinsic::convertfui:
4516 case Intrinsic::convertsif:
4517 case Intrinsic::convertuif:
4518 case Intrinsic::convertss:
4519 case Intrinsic::convertsu:
4520 case Intrinsic::convertus:
4521 case Intrinsic::convertuu: {
4522 ISD::CvtCode Code = ISD::CVT_INVALID;
4523 switch (Intrinsic) {
4524 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4525 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4526 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4527 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4528 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4529 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4530 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4531 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4532 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4534 EVT DestVT = TLI.getValueType(I.getType());
4535 const Value *Op1 = I.getArgOperand(0);
4536 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4537 DAG.getValueType(DestVT),
4538 DAG.getValueType(getValue(Op1).getValueType()),
4539 getValue(I.getArgOperand(1)),
4540 getValue(I.getArgOperand(2)),
4545 case Intrinsic::sqrt:
4546 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4547 getValue(I.getArgOperand(0)).getValueType(),
4548 getValue(I.getArgOperand(0))));
4550 case Intrinsic::powi:
4551 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4552 getValue(I.getArgOperand(1)), DAG));
4554 case Intrinsic::sin:
4555 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4556 getValue(I.getArgOperand(0)).getValueType(),
4557 getValue(I.getArgOperand(0))));
4559 case Intrinsic::cos:
4560 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4561 getValue(I.getArgOperand(0)).getValueType(),
4562 getValue(I.getArgOperand(0))));
4564 case Intrinsic::log:
4567 case Intrinsic::log2:
4570 case Intrinsic::log10:
4573 case Intrinsic::exp:
4576 case Intrinsic::exp2:
4579 case Intrinsic::pow:
4582 case Intrinsic::convert_to_fp16:
4583 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4584 MVT::i16, getValue(I.getArgOperand(0))));
4586 case Intrinsic::convert_from_fp16:
4587 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4588 MVT::f32, getValue(I.getArgOperand(0))));
4590 case Intrinsic::pcmarker: {
4591 SDValue Tmp = getValue(I.getArgOperand(0));
4592 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4595 case Intrinsic::readcyclecounter: {
4596 SDValue Op = getRoot();
4597 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4598 DAG.getVTList(MVT::i64, MVT::Other),
4601 DAG.setRoot(Res.getValue(1));
4604 case Intrinsic::bswap:
4605 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4606 getValue(I.getArgOperand(0)).getValueType(),
4607 getValue(I.getArgOperand(0))));
4609 case Intrinsic::cttz: {
4610 SDValue Arg = getValue(I.getArgOperand(0));
4611 EVT Ty = Arg.getValueType();
4612 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4615 case Intrinsic::ctlz: {
4616 SDValue Arg = getValue(I.getArgOperand(0));
4617 EVT Ty = Arg.getValueType();
4618 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4621 case Intrinsic::ctpop: {
4622 SDValue Arg = getValue(I.getArgOperand(0));
4623 EVT Ty = Arg.getValueType();
4624 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4627 case Intrinsic::stacksave: {
4628 SDValue Op = getRoot();
4629 Res = DAG.getNode(ISD::STACKSAVE, dl,
4630 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4632 DAG.setRoot(Res.getValue(1));
4635 case Intrinsic::stackrestore: {
4636 Res = getValue(I.getArgOperand(0));
4637 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4640 case Intrinsic::stackprotector: {
4641 // Emit code into the DAG to store the stack guard onto the stack.
4642 MachineFunction &MF = DAG.getMachineFunction();
4643 MachineFrameInfo *MFI = MF.getFrameInfo();
4644 EVT PtrTy = TLI.getPointerTy();
4646 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4647 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4649 int FI = FuncInfo.StaticAllocaMap[Slot];
4650 MFI->setStackProtectorIndex(FI);
4652 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4654 // Store the stack protector onto the stack.
4655 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4656 MachinePointerInfo::getFixedStack(FI),
4662 case Intrinsic::objectsize: {
4663 // If we don't know by now, we're never going to know.
4664 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4666 assert(CI && "Non-constant type in __builtin_object_size?");
4668 SDValue Arg = getValue(I.getCalledValue());
4669 EVT Ty = Arg.getValueType();
4672 Res = DAG.getConstant(-1ULL, Ty);
4674 Res = DAG.getConstant(0, Ty);
4679 case Intrinsic::var_annotation:
4680 // Discard annotate attributes
4683 case Intrinsic::init_trampoline: {
4684 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4688 Ops[1] = getValue(I.getArgOperand(0));
4689 Ops[2] = getValue(I.getArgOperand(1));
4690 Ops[3] = getValue(I.getArgOperand(2));
4691 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4692 Ops[5] = DAG.getSrcValue(F);
4694 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4695 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4699 DAG.setRoot(Res.getValue(1));
4702 case Intrinsic::gcroot:
4704 const Value *Alloca = I.getArgOperand(0);
4705 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4707 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4708 GFI->addStackRoot(FI->getIndex(), TypeMap);
4711 case Intrinsic::gcread:
4712 case Intrinsic::gcwrite:
4713 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4715 case Intrinsic::flt_rounds:
4716 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4718 case Intrinsic::trap: {
4719 StringRef TrapFuncName = getTrapFunctionName();
4720 if (TrapFuncName.empty()) {
4721 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4724 TargetLowering::ArgListTy Args;
4725 std::pair<SDValue, SDValue> Result =
4726 TLI.LowerCallTo(getRoot(), I.getType(),
4727 false, false, false, false, 0, CallingConv::C,
4728 /*isTailCall=*/false, /*isReturnValueUsed=*/true,
4729 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
4730 Args, DAG, getCurDebugLoc());
4731 DAG.setRoot(Result.second);
4734 case Intrinsic::uadd_with_overflow:
4735 return implVisitAluOverflow(I, ISD::UADDO);
4736 case Intrinsic::sadd_with_overflow:
4737 return implVisitAluOverflow(I, ISD::SADDO);
4738 case Intrinsic::usub_with_overflow:
4739 return implVisitAluOverflow(I, ISD::USUBO);
4740 case Intrinsic::ssub_with_overflow:
4741 return implVisitAluOverflow(I, ISD::SSUBO);
4742 case Intrinsic::umul_with_overflow:
4743 return implVisitAluOverflow(I, ISD::UMULO);
4744 case Intrinsic::smul_with_overflow:
4745 return implVisitAluOverflow(I, ISD::SMULO);
4747 case Intrinsic::prefetch: {
4749 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4751 Ops[1] = getValue(I.getArgOperand(0));
4752 Ops[2] = getValue(I.getArgOperand(1));
4753 Ops[3] = getValue(I.getArgOperand(2));
4754 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
4755 DAG.getVTList(MVT::Other),
4757 EVT::getIntegerVT(*Context, 8),
4758 MachinePointerInfo(I.getArgOperand(0)),
4760 false, /* volatile */
4762 rw==1)); /* write */
4765 case Intrinsic::memory_barrier: {
4768 for (int x = 1; x < 6; ++x)
4769 Ops[x] = getValue(I.getArgOperand(x - 1));
4771 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4774 case Intrinsic::atomic_cmp_swap: {
4775 SDValue Root = getRoot();
4777 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4778 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
4780 getValue(I.getArgOperand(0)),
4781 getValue(I.getArgOperand(1)),
4782 getValue(I.getArgOperand(2)),
4783 MachinePointerInfo(I.getArgOperand(0)));
4785 DAG.setRoot(L.getValue(1));
4788 case Intrinsic::atomic_load_add:
4789 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4790 case Intrinsic::atomic_load_sub:
4791 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4792 case Intrinsic::atomic_load_or:
4793 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4794 case Intrinsic::atomic_load_xor:
4795 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4796 case Intrinsic::atomic_load_and:
4797 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4798 case Intrinsic::atomic_load_nand:
4799 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4800 case Intrinsic::atomic_load_max:
4801 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4802 case Intrinsic::atomic_load_min:
4803 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4804 case Intrinsic::atomic_load_umin:
4805 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4806 case Intrinsic::atomic_load_umax:
4807 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4808 case Intrinsic::atomic_swap:
4809 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4811 case Intrinsic::invariant_start:
4812 case Intrinsic::lifetime_start:
4813 // Discard region information.
4814 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4816 case Intrinsic::invariant_end:
4817 case Intrinsic::lifetime_end:
4818 // Discard region information.
4823 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
4825 MachineBasicBlock *LandingPad) {
4826 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4827 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4828 const Type *RetTy = FTy->getReturnType();
4829 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4830 MCSymbol *BeginLabel = 0;
4832 TargetLowering::ArgListTy Args;
4833 TargetLowering::ArgListEntry Entry;
4834 Args.reserve(CS.arg_size());
4836 // Check whether the function can return without sret-demotion.
4837 SmallVector<ISD::OutputArg, 4> Outs;
4838 SmallVector<uint64_t, 4> Offsets;
4839 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4840 Outs, TLI, &Offsets);
4842 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4843 FTy->isVarArg(), Outs, FTy->getContext());
4845 SDValue DemoteStackSlot;
4846 int DemoteStackIdx = -100;
4848 if (!CanLowerReturn) {
4849 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4850 FTy->getReturnType());
4851 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4852 FTy->getReturnType());
4853 MachineFunction &MF = DAG.getMachineFunction();
4854 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4855 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4857 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
4858 Entry.Node = DemoteStackSlot;
4859 Entry.Ty = StackSlotPtrType;
4860 Entry.isSExt = false;
4861 Entry.isZExt = false;
4862 Entry.isInReg = false;
4863 Entry.isSRet = true;
4864 Entry.isNest = false;
4865 Entry.isByVal = false;
4866 Entry.Alignment = Align;
4867 Args.push_back(Entry);
4868 RetTy = Type::getVoidTy(FTy->getContext());
4871 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4873 const Value *V = *i;
4876 if (V->getType()->isEmptyTy())
4879 SDValue ArgNode = getValue(V);
4880 Entry.Node = ArgNode; Entry.Ty = V->getType();
4882 unsigned attrInd = i - CS.arg_begin() + 1;
4883 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4884 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4885 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4886 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4887 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4888 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4889 Entry.Alignment = CS.getParamAlignment(attrInd);
4890 Args.push_back(Entry);
4894 // Insert a label before the invoke call to mark the try range. This can be
4895 // used to detect deletion of the invoke via the MachineModuleInfo.
4896 BeginLabel = MMI.getContext().CreateTempSymbol();
4898 // For SjLj, keep track of which landing pads go with which invokes
4899 // so as to maintain the ordering of pads in the LSDA.
4900 unsigned CallSiteIndex = MMI.getCurrentCallSite();
4901 if (CallSiteIndex) {
4902 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4903 // Now that the call site is handled, stop tracking it.
4904 MMI.setCurrentCallSite(0);
4907 // Both PendingLoads and PendingExports must be flushed here;
4908 // this call might not return.
4910 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
4913 // Check if target-independent constraints permit a tail call here.
4914 // Target-dependent constraints are checked within TLI.LowerCallTo.
4916 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4919 // If there's a possibility that fast-isel has already selected some amount
4920 // of the current basic block, don't emit a tail call.
4921 if (isTailCall && EnableFastISel)
4924 std::pair<SDValue,SDValue> Result =
4925 TLI.LowerCallTo(getRoot(), RetTy,
4926 CS.paramHasAttr(0, Attribute::SExt),
4927 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4928 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4929 CS.getCallingConv(),
4931 !CS.getInstruction()->use_empty(),
4932 Callee, Args, DAG, getCurDebugLoc());
4933 assert((isTailCall || Result.second.getNode()) &&
4934 "Non-null chain expected with non-tail call!");
4935 assert((Result.second.getNode() || !Result.first.getNode()) &&
4936 "Null value expected with tail call!");
4937 if (Result.first.getNode()) {
4938 setValue(CS.getInstruction(), Result.first);
4939 } else if (!CanLowerReturn && Result.second.getNode()) {
4940 // The instruction result is the result of loading from the
4941 // hidden sret parameter.
4942 SmallVector<EVT, 1> PVTs;
4943 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4945 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4946 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4947 EVT PtrVT = PVTs[0];
4948 unsigned NumValues = Outs.size();
4949 SmallVector<SDValue, 4> Values(NumValues);
4950 SmallVector<SDValue, 4> Chains(NumValues);
4952 for (unsigned i = 0; i < NumValues; ++i) {
4953 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4955 DAG.getConstant(Offsets[i], PtrVT));
4956 SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second,
4958 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
4961 Chains[i] = L.getValue(1);
4964 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4965 MVT::Other, &Chains[0], NumValues);
4966 PendingLoads.push_back(Chain);
4968 // Collect the legal value parts into potentially illegal values
4969 // that correspond to the original function's return values.
4970 SmallVector<EVT, 4> RetTys;
4971 RetTy = FTy->getReturnType();
4972 ComputeValueVTs(TLI, RetTy, RetTys);
4973 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4974 SmallVector<SDValue, 4> ReturnValues;
4975 unsigned CurReg = 0;
4976 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4978 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4979 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4981 SDValue ReturnValue =
4982 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
4983 RegisterVT, VT, AssertOp);
4984 ReturnValues.push_back(ReturnValue);
4988 setValue(CS.getInstruction(),
4989 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4990 DAG.getVTList(&RetTys[0], RetTys.size()),
4991 &ReturnValues[0], ReturnValues.size()));
4994 // Assign order to nodes here. If the call does not produce a result, it won't
4995 // be mapped to a SDNode and visit() will not assign it an order number.
4996 if (!Result.second.getNode()) {
4997 // As a special case, a null chain means that a tail call has been emitted and
4998 // the DAG root is already updated.
5001 AssignOrderingToNode(DAG.getRoot().getNode());
5003 DAG.setRoot(Result.second);
5005 AssignOrderingToNode(Result.second.getNode());
5009 // Insert a label at the end of the invoke call to mark the try range. This
5010 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5011 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5012 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
5014 // Inform MachineModuleInfo of range.
5015 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5019 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5020 /// value is equal or not-equal to zero.
5021 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5022 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
5024 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5025 if (IC->isEquality())
5026 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5027 if (C->isNullValue())
5029 // Unknown instruction.
5035 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5037 SelectionDAGBuilder &Builder) {
5039 // Check to see if this load can be trivially constant folded, e.g. if the
5040 // input is from a string literal.
5041 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5042 // Cast pointer to the type we really want to load.
5043 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5044 PointerType::getUnqual(LoadTy));
5046 if (const Constant *LoadCst =
5047 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5049 return Builder.getValue(LoadCst);
5052 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5053 // still constant memory, the input chain can be the entry node.
5055 bool ConstantMemory = false;
5057 // Do not serialize (non-volatile) loads of constant memory with anything.
5058 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5059 Root = Builder.DAG.getEntryNode();
5060 ConstantMemory = true;
5062 // Do not serialize non-volatile loads against each other.
5063 Root = Builder.DAG.getRoot();
5066 SDValue Ptr = Builder.getValue(PtrVal);
5067 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
5068 Ptr, MachinePointerInfo(PtrVal),
5070 false /*nontemporal*/, 1 /* align=1 */);
5072 if (!ConstantMemory)
5073 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5078 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5079 /// If so, return true and lower it, otherwise return false and it will be
5080 /// lowered like a normal call.
5081 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5082 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5083 if (I.getNumArgOperands() != 3)
5086 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5087 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5088 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5089 !I.getType()->isIntegerTy())
5092 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
5094 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5095 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5096 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5097 bool ActuallyDoIt = true;
5100 switch (Size->getZExtValue()) {
5102 LoadVT = MVT::Other;
5104 ActuallyDoIt = false;
5108 LoadTy = Type::getInt16Ty(Size->getContext());
5112 LoadTy = Type::getInt32Ty(Size->getContext());
5116 LoadTy = Type::getInt64Ty(Size->getContext());
5120 LoadVT = MVT::v4i32;
5121 LoadTy = Type::getInt32Ty(Size->getContext());
5122 LoadTy = VectorType::get(LoadTy, 4);
5127 // This turns into unaligned loads. We only do this if the target natively
5128 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5129 // we'll only produce a small number of byte loads.
5131 // Require that we can find a legal MVT, and only do this if the target
5132 // supports unaligned loads of that type. Expanding into byte loads would
5134 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5135 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5136 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5137 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5138 ActuallyDoIt = false;
5142 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5143 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5145 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5147 EVT CallVT = TLI.getValueType(I.getType(), true);
5148 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5158 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5159 // Handle inline assembly differently.
5160 if (isa<InlineAsm>(I.getCalledValue())) {
5165 // See if any floating point values are being passed to this function. This is
5166 // used to emit an undefined reference to fltused on Windows.
5167 const FunctionType *FT =
5168 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
5169 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5170 if (FT->isVarArg() &&
5171 !MMI.callsExternalVAFunctionWithFloatingPointArguments()) {
5172 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
5173 const Type* T = I.getArgOperand(i)->getType();
5174 for (po_iterator<const Type*> i = po_begin(T), e = po_end(T);
5176 if (!i->isFloatingPointTy()) continue;
5177 MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true);
5183 const char *RenameFn = 0;
5184 if (Function *F = I.getCalledFunction()) {
5185 if (F->isDeclaration()) {
5186 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5187 if (unsigned IID = II->getIntrinsicID(F)) {
5188 RenameFn = visitIntrinsicCall(I, IID);
5193 if (unsigned IID = F->getIntrinsicID()) {
5194 RenameFn = visitIntrinsicCall(I, IID);
5200 // Check for well-known libc/libm calls. If the function is internal, it
5201 // can't be a library call.
5202 if (!F->hasLocalLinkage() && F->hasName()) {
5203 StringRef Name = F->getName();
5204 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
5205 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5206 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5207 I.getType() == I.getArgOperand(0)->getType() &&
5208 I.getType() == I.getArgOperand(1)->getType()) {
5209 SDValue LHS = getValue(I.getArgOperand(0));
5210 SDValue RHS = getValue(I.getArgOperand(1));
5211 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5212 LHS.getValueType(), LHS, RHS));
5215 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5216 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5217 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5218 I.getType() == I.getArgOperand(0)->getType()) {
5219 SDValue Tmp = getValue(I.getArgOperand(0));
5220 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
5221 Tmp.getValueType(), Tmp));
5224 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5225 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5226 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5227 I.getType() == I.getArgOperand(0)->getType() &&
5228 I.onlyReadsMemory()) {
5229 SDValue Tmp = getValue(I.getArgOperand(0));
5230 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5231 Tmp.getValueType(), Tmp));
5234 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5235 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5236 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5237 I.getType() == I.getArgOperand(0)->getType() &&
5238 I.onlyReadsMemory()) {
5239 SDValue Tmp = getValue(I.getArgOperand(0));
5240 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5241 Tmp.getValueType(), Tmp));
5244 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5245 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5246 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5247 I.getType() == I.getArgOperand(0)->getType() &&
5248 I.onlyReadsMemory()) {
5249 SDValue Tmp = getValue(I.getArgOperand(0));
5250 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5251 Tmp.getValueType(), Tmp));
5254 } else if (Name == "memcmp") {
5255 if (visitMemCmpCall(I))
5263 Callee = getValue(I.getCalledValue());
5265 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5267 // Check if we can potentially perform a tail call. More detailed checking is
5268 // be done within LowerCallTo, after more information about the call is known.
5269 LowerCallTo(&I, Callee, I.isTailCall());
5274 /// AsmOperandInfo - This contains information for each constraint that we are
5276 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
5278 /// CallOperand - If this is the result output operand or a clobber
5279 /// this is null, otherwise it is the incoming operand to the CallInst.
5280 /// This gets modified as the asm is processed.
5281 SDValue CallOperand;
5283 /// AssignedRegs - If this is a register or register class operand, this
5284 /// contains the set of register corresponding to the operand.
5285 RegsForValue AssignedRegs;
5287 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5288 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5291 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5292 /// busy in OutputRegs/InputRegs.
5293 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5294 std::set<unsigned> &OutputRegs,
5295 std::set<unsigned> &InputRegs,
5296 const TargetRegisterInfo &TRI) const {
5298 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5299 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5302 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5303 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5307 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5308 /// corresponds to. If there is no Value* for this operand, it returns
5310 EVT getCallOperandValEVT(LLVMContext &Context,
5311 const TargetLowering &TLI,
5312 const TargetData *TD) const {
5313 if (CallOperandVal == 0) return MVT::Other;
5315 if (isa<BasicBlock>(CallOperandVal))
5316 return TLI.getPointerTy();
5318 const llvm::Type *OpTy = CallOperandVal->getType();
5320 // FIXME: code duplicated from TargetLowering::ParseConstraints().
5321 // If this is an indirect operand, the operand is a pointer to the
5324 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5326 report_fatal_error("Indirect operand for inline asm not a pointer!");
5327 OpTy = PtrTy->getElementType();
5330 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5331 if (const StructType *STy = dyn_cast<StructType>(OpTy))
5332 if (STy->getNumElements() == 1)
5333 OpTy = STy->getElementType(0);
5335 // If OpTy is not a single value, it may be a struct/union that we
5336 // can tile with integers.
5337 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5338 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5347 OpTy = IntegerType::get(Context, BitSize);
5352 return TLI.getValueType(OpTy, true);
5356 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5358 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5359 const TargetRegisterInfo &TRI) {
5360 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5362 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5363 for (; *Aliases; ++Aliases)
5364 Regs.insert(*Aliases);
5368 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5370 } // end anonymous namespace
5372 /// isAllocatableRegister - If the specified register is safe to allocate,
5373 /// i.e. it isn't a stack pointer or some other special register, return the
5374 /// register class for the register. Otherwise, return null.
5375 static const TargetRegisterClass *
5376 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5377 const TargetLowering &TLI,
5378 const TargetRegisterInfo *TRI) {
5379 EVT FoundVT = MVT::Other;
5380 const TargetRegisterClass *FoundRC = 0;
5381 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5382 E = TRI->regclass_end(); RCI != E; ++RCI) {
5383 EVT ThisVT = MVT::Other;
5385 const TargetRegisterClass *RC = *RCI;
5386 // If none of the value types for this register class are valid, we
5387 // can't use it. For example, 64-bit reg classes on 32-bit targets.
5388 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5390 if (TLI.isTypeLegal(*I)) {
5391 // If we have already found this register in a different register class,
5392 // choose the one with the largest VT specified. For example, on
5393 // PowerPC, we favor f64 register classes over f32.
5394 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5401 if (ThisVT == MVT::Other) continue;
5403 // NOTE: This isn't ideal. In particular, this might allocate the
5404 // frame pointer in functions that need it (due to them not being taken
5405 // out of allocation, because a variable sized allocation hasn't been seen
5406 // yet). This is a slight code pessimization, but should still work.
5407 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5408 E = RC->allocation_order_end(MF); I != E; ++I)
5410 // We found a matching register class. Keep looking at others in case
5411 // we find one with larger registers that this physreg is also in.
5420 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5421 /// specified operand. We prefer to assign virtual registers, to allow the
5422 /// register allocator to handle the assignment process. However, if the asm
5423 /// uses features that we can't model on machineinstrs, we have SDISel do the
5424 /// allocation. This produces generally horrible, but correct, code.
5426 /// OpInfo describes the operand.
5427 /// Input and OutputRegs are the set of already allocated physical registers.
5429 static void GetRegistersForValue(SelectionDAG &DAG,
5430 const TargetLowering &TLI,
5432 SDISelAsmOperandInfo &OpInfo,
5433 std::set<unsigned> &OutputRegs,
5434 std::set<unsigned> &InputRegs) {
5435 LLVMContext &Context = *DAG.getContext();
5437 // Compute whether this value requires an input register, an output register,
5439 bool isOutReg = false;
5440 bool isInReg = false;
5441 switch (OpInfo.Type) {
5442 case InlineAsm::isOutput:
5445 // If there is an input constraint that matches this, we need to reserve
5446 // the input register so no other inputs allocate to it.
5447 isInReg = OpInfo.hasMatchingInput();
5449 case InlineAsm::isInput:
5453 case InlineAsm::isClobber:
5460 MachineFunction &MF = DAG.getMachineFunction();
5461 SmallVector<unsigned, 4> Regs;
5463 // If this is a constraint for a single physreg, or a constraint for a
5464 // register class, find it.
5465 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5466 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5467 OpInfo.ConstraintVT);
5469 unsigned NumRegs = 1;
5470 if (OpInfo.ConstraintVT != MVT::Other) {
5471 // If this is a FP input in an integer register (or visa versa) insert a bit
5472 // cast of the input value. More generally, handle any case where the input
5473 // value disagrees with the register class we plan to stick this in.
5474 if (OpInfo.Type == InlineAsm::isInput &&
5475 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5476 // Try to convert to the first EVT that the reg class contains. If the
5477 // types are identical size, use a bitcast to convert (e.g. two differing
5479 EVT RegVT = *PhysReg.second->vt_begin();
5480 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5481 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5482 RegVT, OpInfo.CallOperand);
5483 OpInfo.ConstraintVT = RegVT;
5484 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5485 // If the input is a FP value and we want it in FP registers, do a
5486 // bitcast to the corresponding integer type. This turns an f64 value
5487 // into i64, which can be passed with two i32 values on a 32-bit
5489 RegVT = EVT::getIntegerVT(Context,
5490 OpInfo.ConstraintVT.getSizeInBits());
5491 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5492 RegVT, OpInfo.CallOperand);
5493 OpInfo.ConstraintVT = RegVT;
5497 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5501 EVT ValueVT = OpInfo.ConstraintVT;
5503 // If this is a constraint for a specific physical register, like {r17},
5505 if (unsigned AssignedReg = PhysReg.first) {
5506 const TargetRegisterClass *RC = PhysReg.second;
5507 if (OpInfo.ConstraintVT == MVT::Other)
5508 ValueVT = *RC->vt_begin();
5510 // Get the actual register value type. This is important, because the user
5511 // may have asked for (e.g.) the AX register in i32 type. We need to
5512 // remember that AX is actually i16 to get the right extension.
5513 RegVT = *RC->vt_begin();
5515 // This is a explicit reference to a physical register.
5516 Regs.push_back(AssignedReg);
5518 // If this is an expanded reference, add the rest of the regs to Regs.
5520 TargetRegisterClass::iterator I = RC->begin();
5521 for (; *I != AssignedReg; ++I)
5522 assert(I != RC->end() && "Didn't find reg!");
5524 // Already added the first reg.
5526 for (; NumRegs; --NumRegs, ++I) {
5527 assert(I != RC->end() && "Ran out of registers to allocate!");
5532 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5533 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5534 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5538 // Otherwise, if this was a reference to an LLVM register class, create vregs
5539 // for this reference.
5540 if (const TargetRegisterClass *RC = PhysReg.second) {
5541 RegVT = *RC->vt_begin();
5542 if (OpInfo.ConstraintVT == MVT::Other)
5545 // Create the appropriate number of virtual registers.
5546 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5547 for (; NumRegs; --NumRegs)
5548 Regs.push_back(RegInfo.createVirtualRegister(RC));
5550 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5554 // This is a reference to a register class that doesn't directly correspond
5555 // to an LLVM register class. Allocate NumRegs consecutive, available,
5556 // registers from the class.
5557 std::vector<unsigned> RegClassRegs
5558 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5559 OpInfo.ConstraintVT);
5561 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5562 unsigned NumAllocated = 0;
5563 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5564 unsigned Reg = RegClassRegs[i];
5565 // See if this register is available.
5566 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5567 (isInReg && InputRegs.count(Reg))) { // Already used.
5568 // Make sure we find consecutive registers.
5573 // Check to see if this register is allocatable (i.e. don't give out the
5575 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5576 if (!RC) { // Couldn't allocate this register.
5577 // Reset NumAllocated to make sure we return consecutive registers.
5582 // Okay, this register is good, we can use it.
5585 // If we allocated enough consecutive registers, succeed.
5586 if (NumAllocated == NumRegs) {
5587 unsigned RegStart = (i-NumAllocated)+1;
5588 unsigned RegEnd = i+1;
5589 // Mark all of the allocated registers used.
5590 for (unsigned i = RegStart; i != RegEnd; ++i)
5591 Regs.push_back(RegClassRegs[i]);
5593 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
5594 OpInfo.ConstraintVT);
5595 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5600 // Otherwise, we couldn't allocate enough registers for this.
5603 /// visitInlineAsm - Handle a call to an InlineAsm object.
5605 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5606 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5608 /// ConstraintOperands - Information about all of the constraints.
5609 SDISelAsmOperandInfoVector ConstraintOperands;
5611 std::set<unsigned> OutputRegs, InputRegs;
5613 TargetLowering::AsmOperandInfoVector
5614 TargetConstraints = TLI.ParseConstraints(CS);
5616 bool hasMemory = false;
5618 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5619 unsigned ResNo = 0; // ResNo - The result number of the next output.
5620 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5621 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
5622 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5624 EVT OpVT = MVT::Other;
5626 // Compute the value type for each operand.
5627 switch (OpInfo.Type) {
5628 case InlineAsm::isOutput:
5629 // Indirect outputs just consume an argument.
5630 if (OpInfo.isIndirect) {
5631 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5635 // The return value of the call is this value. As such, there is no
5636 // corresponding argument.
5637 assert(!CS.getType()->isVoidTy() &&
5639 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5640 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5642 assert(ResNo == 0 && "Asm only has one result!");
5643 OpVT = TLI.getValueType(CS.getType());
5647 case InlineAsm::isInput:
5648 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5650 case InlineAsm::isClobber:
5655 // If this is an input or an indirect output, process the call argument.
5656 // BasicBlocks are labels, currently appearing only in asm's.
5657 if (OpInfo.CallOperandVal) {
5658 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5659 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5661 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5664 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5667 OpInfo.ConstraintVT = OpVT;
5669 // Indirect operand accesses access memory.
5670 if (OpInfo.isIndirect)
5673 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
5674 TargetLowering::ConstraintType
5675 CType = TLI.getConstraintType(OpInfo.Codes[j]);
5676 if (CType == TargetLowering::C_Memory) {
5684 SDValue Chain, Flag;
5686 // We won't need to flush pending loads if this asm doesn't touch
5687 // memory and is nonvolatile.
5688 if (hasMemory || IA->hasSideEffects())
5691 Chain = DAG.getRoot();
5693 // Second pass over the constraints: compute which constraint option to use
5694 // and assign registers to constraints that want a specific physreg.
5695 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5696 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5698 // If this is an output operand with a matching input operand, look up the
5699 // matching input. If their types mismatch, e.g. one is an integer, the
5700 // other is floating point, or their sizes are different, flag it as an
5702 if (OpInfo.hasMatchingInput()) {
5703 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5705 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5706 if ((OpInfo.ConstraintVT.isInteger() !=
5707 Input.ConstraintVT.isInteger()) ||
5708 (OpInfo.ConstraintVT.getSizeInBits() !=
5709 Input.ConstraintVT.getSizeInBits())) {
5710 report_fatal_error("Unsupported asm: input constraint"
5711 " with a matching output constraint of"
5712 " incompatible type!");
5714 Input.ConstraintVT = OpInfo.ConstraintVT;
5718 // Compute the constraint code and ConstraintType to use.
5719 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5721 // If this is a memory input, and if the operand is not indirect, do what we
5722 // need to to provide an address for the memory input.
5723 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5724 !OpInfo.isIndirect) {
5725 assert((OpInfo.isMultipleAlternative ||
5726 (OpInfo.Type == InlineAsm::isInput)) &&
5727 "Can only indirectify direct input operands!");
5729 // Memory operands really want the address of the value. If we don't have
5730 // an indirect input, put it in the constpool if we can, otherwise spill
5731 // it to a stack slot.
5733 // If the operand is a float, integer, or vector constant, spill to a
5734 // constant pool entry to get its address.
5735 const Value *OpVal = OpInfo.CallOperandVal;
5736 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5737 isa<ConstantVector>(OpVal)) {
5738 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5739 TLI.getPointerTy());
5741 // Otherwise, create a stack slot and emit a store to it before the
5743 const Type *Ty = OpVal->getType();
5744 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5745 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5746 MachineFunction &MF = DAG.getMachineFunction();
5747 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5748 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5749 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5750 OpInfo.CallOperand, StackSlot,
5751 MachinePointerInfo::getFixedStack(SSFI),
5753 OpInfo.CallOperand = StackSlot;
5756 // There is no longer a Value* corresponding to this operand.
5757 OpInfo.CallOperandVal = 0;
5759 // It is now an indirect operand.
5760 OpInfo.isIndirect = true;
5763 // If this constraint is for a specific register, allocate it before
5765 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5766 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
5770 // Second pass - Loop over all of the operands, assigning virtual or physregs
5771 // to register class operands.
5772 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5773 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5775 // C_Register operands have already been allocated, Other/Memory don't need
5777 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5778 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
5782 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5783 std::vector<SDValue> AsmNodeOperands;
5784 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5785 AsmNodeOperands.push_back(
5786 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5787 TLI.getPointerTy()));
5789 // If we have a !srcloc metadata node associated with it, we want to attach
5790 // this to the ultimately generated inline asm machineinstr. To do this, we
5791 // pass in the third operand as this (potentially null) inline asm MDNode.
5792 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
5793 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
5795 // Remember the HasSideEffect and AlignStack bits as operand 3.
5796 unsigned ExtraInfo = 0;
5797 if (IA->hasSideEffects())
5798 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
5799 if (IA->isAlignStack())
5800 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
5801 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
5802 TLI.getPointerTy()));
5804 // Loop over all of the inputs, copying the operand values into the
5805 // appropriate registers and processing the output regs.
5806 RegsForValue RetValRegs;
5808 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5809 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5811 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5812 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5814 switch (OpInfo.Type) {
5815 case InlineAsm::isOutput: {
5816 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5817 OpInfo.ConstraintType != TargetLowering::C_Register) {
5818 // Memory output, or 'other' output (e.g. 'X' constraint).
5819 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5821 // Add information to the INLINEASM node to know about this output.
5822 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5823 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
5824 TLI.getPointerTy()));
5825 AsmNodeOperands.push_back(OpInfo.CallOperand);
5829 // Otherwise, this is a register or register class output.
5831 // Copy the output from the appropriate register. Find a register that
5833 if (OpInfo.AssignedRegs.Regs.empty())
5834 report_fatal_error("Couldn't allocate output reg for constraint '" +
5835 Twine(OpInfo.ConstraintCode) + "'!");
5837 // If this is an indirect operand, store through the pointer after the
5839 if (OpInfo.isIndirect) {
5840 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5841 OpInfo.CallOperandVal));
5843 // This is the result value of the call.
5844 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5845 // Concatenate this output onto the outputs list.
5846 RetValRegs.append(OpInfo.AssignedRegs);
5849 // Add information to the INLINEASM node to know that this register is
5851 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5852 InlineAsm::Kind_RegDefEarlyClobber :
5853 InlineAsm::Kind_RegDef,
5860 case InlineAsm::isInput: {
5861 SDValue InOperandVal = OpInfo.CallOperand;
5863 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5864 // If this is required to match an output register we have already set,
5865 // just use its register.
5866 unsigned OperandNo = OpInfo.getMatchedOperand();
5868 // Scan until we find the definition we already emitted of this operand.
5869 // When we find it, create a RegsForValue operand.
5870 unsigned CurOp = InlineAsm::Op_FirstOperand;
5871 for (; OperandNo; --OperandNo) {
5872 // Advance to the next operand.
5874 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5875 assert((InlineAsm::isRegDefKind(OpFlag) ||
5876 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
5877 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
5878 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5882 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5883 if (InlineAsm::isRegDefKind(OpFlag) ||
5884 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
5885 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5886 if (OpInfo.isIndirect) {
5887 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
5888 LLVMContext &Ctx = *DAG.getContext();
5889 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
5890 " don't know how to handle tied "
5891 "indirect register inputs");
5894 RegsForValue MatchedRegs;
5895 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5896 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5897 MatchedRegs.RegVTs.push_back(RegVT);
5898 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5899 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5901 MatchedRegs.Regs.push_back
5902 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5904 // Use the produced MatchedRegs object to
5905 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5907 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
5908 true, OpInfo.getMatchedOperand(),
5909 DAG, AsmNodeOperands);
5913 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
5914 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
5915 "Unexpected number of operands");
5916 // Add information to the INLINEASM node to know about this input.
5917 // See InlineAsm.h isUseOperandTiedToDef.
5918 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
5919 OpInfo.getMatchedOperand());
5920 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5921 TLI.getPointerTy()));
5922 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5926 // Treat indirect 'X' constraint as memory.
5927 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
5929 OpInfo.ConstraintType = TargetLowering::C_Memory;
5931 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5932 std::vector<SDValue> Ops;
5933 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5936 report_fatal_error("Invalid operand for inline asm constraint '" +
5937 Twine(OpInfo.ConstraintCode) + "'!");
5939 // Add information to the INLINEASM node to know about this input.
5940 unsigned ResOpType =
5941 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
5942 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5943 TLI.getPointerTy()));
5944 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5948 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5949 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5950 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5951 "Memory operands expect pointer values");
5953 // Add information to the INLINEASM node to know about this input.
5954 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5955 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5956 TLI.getPointerTy()));
5957 AsmNodeOperands.push_back(InOperandVal);
5961 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5962 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5963 "Unknown constraint type!");
5964 assert(!OpInfo.isIndirect &&
5965 "Don't know how to handle indirect register inputs yet!");
5967 // Copy the input into the appropriate registers.
5968 if (OpInfo.AssignedRegs.Regs.empty() ||
5969 !OpInfo.AssignedRegs.areValueTypesLegal(TLI))
5970 report_fatal_error("Couldn't allocate input reg for constraint '" +
5971 Twine(OpInfo.ConstraintCode) + "'!");
5973 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5976 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
5977 DAG, AsmNodeOperands);
5980 case InlineAsm::isClobber: {
5981 // Add the clobbered value to the operand list, so that the register
5982 // allocator is aware that the physreg got clobbered.
5983 if (!OpInfo.AssignedRegs.Regs.empty())
5984 OpInfo.AssignedRegs.AddInlineAsmOperands(
5985 InlineAsm::Kind_RegDefEarlyClobber,
5993 // Finish up input operands. Set the input chain and add the flag last.
5994 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
5995 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5997 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5998 DAG.getVTList(MVT::Other, MVT::Glue),
5999 &AsmNodeOperands[0], AsmNodeOperands.size());
6000 Flag = Chain.getValue(1);
6002 // If this asm returns a register value, copy the result from that register
6003 // and set it as the value of the call.
6004 if (!RetValRegs.Regs.empty()) {
6005 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6008 // FIXME: Why don't we do this for inline asms with MRVs?
6009 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6010 EVT ResultType = TLI.getValueType(CS.getType());
6012 // If any of the results of the inline asm is a vector, it may have the
6013 // wrong width/num elts. This can happen for register classes that can
6014 // contain multiple different value types. The preg or vreg allocated may
6015 // not have the same VT as was expected. Convert it to the right type
6016 // with bit_convert.
6017 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6018 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
6021 } else if (ResultType != Val.getValueType() &&
6022 ResultType.isInteger() && Val.getValueType().isInteger()) {
6023 // If a result value was tied to an input value, the computed result may
6024 // have a wider width than the expected result. Extract the relevant
6026 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
6029 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6032 setValue(CS.getInstruction(), Val);
6033 // Don't need to use this as a chain in this case.
6034 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6038 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6040 // Process indirect outputs, first output all of the flagged copies out of
6042 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6043 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6044 const Value *Ptr = IndirectStoresToEmit[i].second;
6045 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6047 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6050 // Emit the non-flagged stores from the physregs.
6051 SmallVector<SDValue, 8> OutChains;
6052 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6053 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6054 StoresToEmit[i].first,
6055 getValue(StoresToEmit[i].second),
6056 MachinePointerInfo(StoresToEmit[i].second),
6058 OutChains.push_back(Val);
6061 if (!OutChains.empty())
6062 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
6063 &OutChains[0], OutChains.size());
6068 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6069 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6070 MVT::Other, getRoot(),
6071 getValue(I.getArgOperand(0)),
6072 DAG.getSrcValue(I.getArgOperand(0))));
6075 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6076 const TargetData &TD = *TLI.getTargetData();
6077 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6078 getRoot(), getValue(I.getOperand(0)),
6079 DAG.getSrcValue(I.getOperand(0)),
6080 TD.getABITypeAlignment(I.getType()));
6082 DAG.setRoot(V.getValue(1));
6085 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6086 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6087 MVT::Other, getRoot(),
6088 getValue(I.getArgOperand(0)),
6089 DAG.getSrcValue(I.getArgOperand(0))));
6092 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6093 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6094 MVT::Other, getRoot(),
6095 getValue(I.getArgOperand(0)),
6096 getValue(I.getArgOperand(1)),
6097 DAG.getSrcValue(I.getArgOperand(0)),
6098 DAG.getSrcValue(I.getArgOperand(1))));
6101 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6102 /// implementation, which just calls LowerCall.
6103 /// FIXME: When all targets are
6104 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6105 std::pair<SDValue, SDValue>
6106 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
6107 bool RetSExt, bool RetZExt, bool isVarArg,
6108 bool isInreg, unsigned NumFixedArgs,
6109 CallingConv::ID CallConv, bool isTailCall,
6110 bool isReturnValueUsed,
6112 ArgListTy &Args, SelectionDAG &DAG,
6113 DebugLoc dl) const {
6114 // Handle all of the outgoing arguments.
6115 SmallVector<ISD::OutputArg, 32> Outs;
6116 SmallVector<SDValue, 32> OutVals;
6117 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6118 SmallVector<EVT, 4> ValueVTs;
6119 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6120 for (unsigned Value = 0, NumValues = ValueVTs.size();
6121 Value != NumValues; ++Value) {
6122 EVT VT = ValueVTs[Value];
6123 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6124 SDValue Op = SDValue(Args[i].Node.getNode(),
6125 Args[i].Node.getResNo() + Value);
6126 ISD::ArgFlagsTy Flags;
6127 unsigned OriginalAlignment =
6128 getTargetData()->getABITypeAlignment(ArgTy);
6134 if (Args[i].isInReg)
6138 if (Args[i].isByVal) {
6140 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
6141 const Type *ElementTy = Ty->getElementType();
6142 Flags.setByValSize(getTargetData()->getTypeAllocSize(ElementTy));
6143 // For ByVal, alignment should come from FE. BE will guess if this
6144 // info is not there but there are cases it cannot get right.
6145 unsigned FrameAlign;
6146 if (Args[i].Alignment)
6147 FrameAlign = Args[i].Alignment;
6149 FrameAlign = getByValTypeAlignment(ElementTy);
6150 Flags.setByValAlign(FrameAlign);
6154 Flags.setOrigAlign(OriginalAlignment);
6156 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6157 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6158 SmallVector<SDValue, 4> Parts(NumParts);
6159 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6162 ExtendKind = ISD::SIGN_EXTEND;
6163 else if (Args[i].isZExt)
6164 ExtendKind = ISD::ZERO_EXTEND;
6166 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
6167 PartVT, ExtendKind);
6169 for (unsigned j = 0; j != NumParts; ++j) {
6170 // if it isn't first piece, alignment must be 1
6171 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
6173 if (NumParts > 1 && j == 0)
6174 MyFlags.Flags.setSplit();
6176 MyFlags.Flags.setOrigAlign(1);
6178 Outs.push_back(MyFlags);
6179 OutVals.push_back(Parts[j]);
6184 // Handle the incoming return values from the call.
6185 SmallVector<ISD::InputArg, 32> Ins;
6186 SmallVector<EVT, 4> RetTys;
6187 ComputeValueVTs(*this, RetTy, RetTys);
6188 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6190 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6191 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6192 for (unsigned i = 0; i != NumRegs; ++i) {
6193 ISD::InputArg MyFlags;
6194 MyFlags.VT = RegisterVT.getSimpleVT();
6195 MyFlags.Used = isReturnValueUsed;
6197 MyFlags.Flags.setSExt();
6199 MyFlags.Flags.setZExt();
6201 MyFlags.Flags.setInReg();
6202 Ins.push_back(MyFlags);
6206 SmallVector<SDValue, 4> InVals;
6207 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6208 Outs, OutVals, Ins, dl, DAG, InVals);
6210 // Verify that the target's LowerCall behaved as expected.
6211 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6212 "LowerCall didn't return a valid chain!");
6213 assert((!isTailCall || InVals.empty()) &&
6214 "LowerCall emitted a return value for a tail call!");
6215 assert((isTailCall || InVals.size() == Ins.size()) &&
6216 "LowerCall didn't emit the correct number of values!");
6218 // For a tail call, the return value is merely live-out and there aren't
6219 // any nodes in the DAG representing it. Return a special value to
6220 // indicate that a tail call has been emitted and no more Instructions
6221 // should be processed in the current block.
6224 return std::make_pair(SDValue(), SDValue());
6227 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6228 assert(InVals[i].getNode() &&
6229 "LowerCall emitted a null value!");
6230 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6231 "LowerCall emitted a value with the wrong type!");
6234 // Collect the legal value parts into potentially illegal values
6235 // that correspond to the original function's return values.
6236 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6238 AssertOp = ISD::AssertSext;
6240 AssertOp = ISD::AssertZext;
6241 SmallVector<SDValue, 4> ReturnValues;
6242 unsigned CurReg = 0;
6243 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6245 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6246 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6248 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
6249 NumRegs, RegisterVT, VT,
6254 // For a function returning void, there is no return value. We can't create
6255 // such a node, so we just return a null return value in that case. In
6256 // that case, nothing will actually look at the value.
6257 if (ReturnValues.empty())
6258 return std::make_pair(SDValue(), Chain);
6260 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6261 DAG.getVTList(&RetTys[0], RetTys.size()),
6262 &ReturnValues[0], ReturnValues.size());
6263 return std::make_pair(Res, Chain);
6266 void TargetLowering::LowerOperationWrapper(SDNode *N,
6267 SmallVectorImpl<SDValue> &Results,
6268 SelectionDAG &DAG) const {
6269 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6271 Results.push_back(Res);
6274 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6275 llvm_unreachable("LowerOperation not implemented for this target!");
6280 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
6281 SDValue Op = getNonRegisterValue(V);
6282 assert((Op.getOpcode() != ISD::CopyFromReg ||
6283 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6284 "Copy from a reg to the same reg!");
6285 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6287 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6288 SDValue Chain = DAG.getEntryNode();
6289 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
6290 PendingExports.push_back(Chain);
6293 #include "llvm/CodeGen/SelectionDAGISel.h"
6295 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
6296 /// entry block, return true. This includes arguments used by switches, since
6297 /// the switch may expand into multiple basic blocks.
6298 static bool isOnlyUsedInEntryBlock(const Argument *A) {
6299 // With FastISel active, we may be splitting blocks, so force creation
6300 // of virtual registers for all non-dead arguments.
6302 return A->use_empty();
6304 const BasicBlock *Entry = A->getParent()->begin();
6305 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
6307 const User *U = *UI;
6308 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
6309 return false; // Use not in entry block.
6314 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
6315 // If this is the entry block, emit arguments.
6316 const Function &F = *LLVMBB->getParent();
6317 SelectionDAG &DAG = SDB->DAG;
6318 DebugLoc dl = SDB->getCurDebugLoc();
6319 const TargetData *TD = TLI.getTargetData();
6320 SmallVector<ISD::InputArg, 16> Ins;
6322 // Check whether the function can return without sret-demotion.
6323 SmallVector<ISD::OutputArg, 4> Outs;
6324 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6327 if (!FuncInfo->CanLowerReturn) {
6328 // Put in an sret pointer parameter before all the other parameters.
6329 SmallVector<EVT, 1> ValueVTs;
6330 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6332 // NOTE: Assuming that a pointer will never break down to more than one VT
6334 ISD::ArgFlagsTy Flags;
6336 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
6337 ISD::InputArg RetArg(Flags, RegisterVT, true);
6338 Ins.push_back(RetArg);
6341 // Set up the incoming argument description vector.
6343 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
6344 I != E; ++I, ++Idx) {
6345 SmallVector<EVT, 4> ValueVTs;
6346 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6347 bool isArgValueUsed = !I->use_empty();
6348 for (unsigned Value = 0, NumValues = ValueVTs.size();
6349 Value != NumValues; ++Value) {
6350 EVT VT = ValueVTs[Value];
6351 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6352 ISD::ArgFlagsTy Flags;
6353 unsigned OriginalAlignment =
6354 TD->getABITypeAlignment(ArgTy);
6356 if (F.paramHasAttr(Idx, Attribute::ZExt))
6358 if (F.paramHasAttr(Idx, Attribute::SExt))
6360 if (F.paramHasAttr(Idx, Attribute::InReg))
6362 if (F.paramHasAttr(Idx, Attribute::StructRet))
6364 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6366 const PointerType *Ty = cast<PointerType>(I->getType());
6367 const Type *ElementTy = Ty->getElementType();
6368 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
6369 // For ByVal, alignment should be passed from FE. BE will guess if
6370 // this info is not there but there are cases it cannot get right.
6371 unsigned FrameAlign;
6372 if (F.getParamAlignment(Idx))
6373 FrameAlign = F.getParamAlignment(Idx);
6375 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6376 Flags.setByValAlign(FrameAlign);
6378 if (F.paramHasAttr(Idx, Attribute::Nest))
6380 Flags.setOrigAlign(OriginalAlignment);
6382 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6383 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6384 for (unsigned i = 0; i != NumRegs; ++i) {
6385 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6386 if (NumRegs > 1 && i == 0)
6387 MyFlags.Flags.setSplit();
6388 // if it isn't first piece, alignment must be 1
6390 MyFlags.Flags.setOrigAlign(1);
6391 Ins.push_back(MyFlags);
6396 // Call the target to set up the argument values.
6397 SmallVector<SDValue, 8> InVals;
6398 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6402 // Verify that the target's LowerFormalArguments behaved as expected.
6403 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6404 "LowerFormalArguments didn't return a valid chain!");
6405 assert(InVals.size() == Ins.size() &&
6406 "LowerFormalArguments didn't emit the correct number of values!");
6408 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6409 assert(InVals[i].getNode() &&
6410 "LowerFormalArguments emitted a null value!");
6411 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6412 "LowerFormalArguments emitted a value with the wrong type!");
6416 // Update the DAG with the new chain value resulting from argument lowering.
6417 DAG.setRoot(NewRoot);
6419 // Set up the argument values.
6422 if (!FuncInfo->CanLowerReturn) {
6423 // Create a virtual register for the sret pointer, and put in a copy
6424 // from the sret argument into it.
6425 SmallVector<EVT, 1> ValueVTs;
6426 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6427 EVT VT = ValueVTs[0];
6428 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6429 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6430 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6431 RegVT, VT, AssertOp);
6433 MachineFunction& MF = SDB->DAG.getMachineFunction();
6434 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6435 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6436 FuncInfo->DemoteRegister = SRetReg;
6437 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6439 DAG.setRoot(NewRoot);
6441 // i indexes lowered arguments. Bump it past the hidden sret argument.
6442 // Idx indexes LLVM arguments. Don't touch it.
6446 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6448 SmallVector<SDValue, 4> ArgValues;
6449 SmallVector<EVT, 4> ValueVTs;
6450 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6451 unsigned NumValues = ValueVTs.size();
6453 // If this argument is unused then remember its value. It is used to generate
6454 // debugging information.
6455 if (I->use_empty() && NumValues)
6456 SDB->setUnusedArgValue(I, InVals[i]);
6458 for (unsigned Val = 0; Val != NumValues; ++Val) {
6459 EVT VT = ValueVTs[Val];
6460 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6461 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6463 if (!I->use_empty()) {
6464 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6465 if (F.paramHasAttr(Idx, Attribute::SExt))
6466 AssertOp = ISD::AssertSext;
6467 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6468 AssertOp = ISD::AssertZext;
6470 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6471 NumParts, PartVT, VT,
6478 // We don't need to do anything else for unused arguments.
6479 if (ArgValues.empty())
6482 // Note down frame index for byval arguments.
6483 if (I->hasByValAttr())
6484 if (FrameIndexSDNode *FI =
6485 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
6486 FuncInfo->setByValArgumentFrameIndex(I, FI->getIndex());
6488 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6489 SDB->getCurDebugLoc());
6490 SDB->setValue(I, Res);
6492 // If this argument is live outside of the entry block, insert a copy from
6493 // wherever we got it to the vreg that other BB's will reference it as.
6494 if (!EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
6495 // If we can, though, try to skip creating an unnecessary vreg.
6496 // FIXME: This isn't very clean... it would be nice to make this more
6497 // general. It's also subtly incompatible with the hacks FastISel
6499 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
6500 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
6501 FuncInfo->ValueMap[I] = Reg;
6505 if (!isOnlyUsedInEntryBlock(I)) {
6506 FuncInfo->InitializeRegForValue(I);
6507 SDB->CopyToExportRegsIfNeeded(I);
6511 assert(i == InVals.size() && "Argument register count mismatch!");
6513 // Finally, if the target has anything special to do, allow it to do so.
6514 // FIXME: this should insert code into the DAG!
6515 EmitFunctionEntryCode();
6518 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6519 /// ensure constants are generated when needed. Remember the virtual registers
6520 /// that need to be added to the Machine PHI nodes as input. We cannot just
6521 /// directly add them, because expansion might result in multiple MBB's for one
6522 /// BB. As such, the start of the BB might correspond to a different MBB than
6526 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6527 const TerminatorInst *TI = LLVMBB->getTerminator();
6529 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6531 // Check successor nodes' PHI nodes that expect a constant to be available
6533 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6534 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6535 if (!isa<PHINode>(SuccBB->begin())) continue;
6536 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
6538 // If this terminator has multiple identical successors (common for
6539 // switches), only handle each succ once.
6540 if (!SuccsHandled.insert(SuccMBB)) continue;
6542 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6544 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6545 // nodes and Machine PHI nodes, but the incoming operands have not been
6547 for (BasicBlock::const_iterator I = SuccBB->begin();
6548 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6549 // Ignore dead phi's.
6550 if (PN->use_empty()) continue;
6553 if (PN->getType()->isEmptyTy())
6557 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6559 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6560 unsigned &RegOut = ConstantsOut[C];
6562 RegOut = FuncInfo.CreateRegs(C->getType());
6563 CopyValueToVirtualRegister(C, RegOut);
6567 DenseMap<const Value *, unsigned>::iterator I =
6568 FuncInfo.ValueMap.find(PHIOp);
6569 if (I != FuncInfo.ValueMap.end())
6572 assert(isa<AllocaInst>(PHIOp) &&
6573 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6574 "Didn't codegen value into a register!??");
6575 Reg = FuncInfo.CreateRegs(PHIOp->getType());
6576 CopyValueToVirtualRegister(PHIOp, Reg);
6580 // Remember that this register needs to added to the machine PHI node as
6581 // the input for this MBB.
6582 SmallVector<EVT, 4> ValueVTs;
6583 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6584 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6585 EVT VT = ValueVTs[vti];
6586 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6587 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6588 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6589 Reg += NumRegisters;
6593 ConstantsOut.clear();