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/Compiler.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
62 /// LimitFloatPrecision - Generate low-precision inline sequences for
63 /// some float libcalls (6, 8 or 12 bits).
64 static unsigned LimitFloatPrecision;
66 static cl::opt<unsigned, true>
67 LimitFPPrecision("limit-float-precision",
68 cl::desc("Generate low-precision inline sequences "
69 "for some float libcalls"),
70 cl::location(LimitFloatPrecision),
73 // Limit the width of DAG chains. This is important in general to prevent
74 // prevent DAG-based analysis from blowing up. For example, alias analysis and
75 // load clustering may not complete in reasonable time. It is difficult to
76 // recognize and avoid this situation within each individual analysis, and
77 // future analyses are likely to have the same behavior. Limiting DAG width is
78 // the safe approach, and will be especially important with global DAGs.
80 // MaxParallelChains default is arbitrarily high to avoid affecting
81 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
82 // sequence over this should have been converted to llvm.memcpy by the
83 // frontend. It easy to induce this behavior with .ll code such as:
84 // %buffer = alloca [4096 x i8]
85 // %data = load [4096 x i8]* %argPtr
86 // store [4096 x i8] %data, [4096 x i8]* %buffer
87 static const unsigned MaxParallelChains = 64;
89 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
90 const SDValue *Parts, unsigned NumParts,
91 EVT PartVT, EVT ValueVT);
93 /// getCopyFromParts - Create a value that contains the specified legal parts
94 /// combined into the value they represent. If the parts combine to a type
95 /// larger then ValueVT then AssertOp can be used to specify whether the extra
96 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
97 /// (ISD::AssertSext).
98 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL,
100 unsigned NumParts, EVT PartVT, EVT ValueVT,
101 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
102 if (ValueVT.isVector())
103 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT);
105 assert(NumParts > 0 && "No parts to assemble!");
106 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
107 SDValue Val = Parts[0];
110 // Assemble the value from multiple parts.
111 if (ValueVT.isInteger()) {
112 unsigned PartBits = PartVT.getSizeInBits();
113 unsigned ValueBits = ValueVT.getSizeInBits();
115 // Assemble the power of 2 part.
116 unsigned RoundParts = NumParts & (NumParts - 1) ?
117 1 << Log2_32(NumParts) : NumParts;
118 unsigned RoundBits = PartBits * RoundParts;
119 EVT RoundVT = RoundBits == ValueBits ?
120 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
123 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
125 if (RoundParts > 2) {
126 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
128 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
129 RoundParts / 2, PartVT, HalfVT);
131 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
132 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
135 if (TLI.isBigEndian())
138 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
140 if (RoundParts < NumParts) {
141 // Assemble the trailing non-power-of-2 part.
142 unsigned OddParts = NumParts - RoundParts;
143 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
144 Hi = getCopyFromParts(DAG, DL,
145 Parts + RoundParts, OddParts, PartVT, OddVT);
147 // Combine the round and odd parts.
149 if (TLI.isBigEndian())
151 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
152 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
153 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
154 DAG.getConstant(Lo.getValueType().getSizeInBits(),
155 TLI.getPointerTy()));
156 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
157 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
159 } else if (PartVT.isFloatingPoint()) {
160 // FP split into multiple FP parts (for ppcf128)
161 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
164 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
165 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
166 if (TLI.isBigEndian())
168 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
170 // FP split into integer parts (soft fp)
171 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
172 !PartVT.isVector() && "Unexpected split");
173 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
174 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT);
178 // There is now one part, held in Val. Correct it to match ValueVT.
179 PartVT = Val.getValueType();
181 if (PartVT == ValueVT)
184 if (PartVT.isInteger() && ValueVT.isInteger()) {
185 if (ValueVT.bitsLT(PartVT)) {
186 // For a truncate, see if we have any information to
187 // indicate whether the truncated bits will always be
188 // zero or sign-extension.
189 if (AssertOp != ISD::DELETED_NODE)
190 Val = DAG.getNode(AssertOp, DL, PartVT, Val,
191 DAG.getValueType(ValueVT));
192 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
194 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
197 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
198 // FP_ROUND's are always exact here.
199 if (ValueVT.bitsLT(Val.getValueType()))
200 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
201 DAG.getIntPtrConstant(1));
203 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
206 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
207 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
209 llvm_unreachable("Unknown mismatch!");
213 /// getCopyFromParts - Create a value that contains the specified legal parts
214 /// combined into the value they represent. If the parts combine to a type
215 /// larger then ValueVT then AssertOp can be used to specify whether the extra
216 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
217 /// (ISD::AssertSext).
218 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
219 const SDValue *Parts, unsigned NumParts,
220 EVT PartVT, EVT ValueVT) {
221 assert(ValueVT.isVector() && "Not a vector value");
222 assert(NumParts > 0 && "No parts to assemble!");
223 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
224 SDValue Val = Parts[0];
226 // Handle a multi-element vector.
228 EVT IntermediateVT, RegisterVT;
229 unsigned NumIntermediates;
231 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
232 NumIntermediates, RegisterVT);
233 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
234 NumParts = NumRegs; // Silence a compiler warning.
235 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
236 assert(RegisterVT == Parts[0].getValueType() &&
237 "Part type doesn't match part!");
239 // Assemble the parts into intermediate operands.
240 SmallVector<SDValue, 8> Ops(NumIntermediates);
241 if (NumIntermediates == NumParts) {
242 // If the register was not expanded, truncate or copy the value,
244 for (unsigned i = 0; i != NumParts; ++i)
245 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
246 PartVT, IntermediateVT);
247 } else if (NumParts > 0) {
248 // If the intermediate type was expanded, build the intermediate
249 // operands from the parts.
250 assert(NumParts % NumIntermediates == 0 &&
251 "Must expand into a divisible number of parts!");
252 unsigned Factor = NumParts / NumIntermediates;
253 for (unsigned i = 0; i != NumIntermediates; ++i)
254 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
255 PartVT, IntermediateVT);
258 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
259 // intermediate operands.
260 Val = DAG.getNode(IntermediateVT.isVector() ?
261 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
262 ValueVT, &Ops[0], NumIntermediates);
265 // There is now one part, held in Val. Correct it to match ValueVT.
266 PartVT = Val.getValueType();
268 if (PartVT == ValueVT)
271 if (PartVT.isVector()) {
272 // If the element type of the source/dest vectors are the same, but the
273 // parts vector has more elements than the value vector, then we have a
274 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
276 if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
277 assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
278 "Cannot narrow, it would be a lossy transformation");
279 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
280 DAG.getIntPtrConstant(0));
283 // Vector/Vector bitcast.
284 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
287 assert(ValueVT.getVectorElementType() == PartVT &&
288 ValueVT.getVectorNumElements() == 1 &&
289 "Only trivial scalar-to-vector conversions should get here!");
290 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
296 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl,
297 SDValue Val, SDValue *Parts, unsigned NumParts,
300 /// getCopyToParts - Create a series of nodes that contain the specified value
301 /// split into legal parts. If the parts contain more bits than Val, then, for
302 /// integers, ExtendKind can be used to specify how to generate the extra bits.
303 static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL,
304 SDValue Val, SDValue *Parts, unsigned NumParts,
306 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
307 EVT ValueVT = Val.getValueType();
309 // Handle the vector case separately.
310 if (ValueVT.isVector())
311 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT);
313 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
314 unsigned PartBits = PartVT.getSizeInBits();
315 unsigned OrigNumParts = NumParts;
316 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
321 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
322 if (PartVT == ValueVT) {
323 assert(NumParts == 1 && "No-op copy with multiple parts!");
328 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
329 // If the parts cover more bits than the value has, promote the value.
330 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
331 assert(NumParts == 1 && "Do not know what to promote to!");
332 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
334 assert(PartVT.isInteger() && ValueVT.isInteger() &&
335 "Unknown mismatch!");
336 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
337 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
339 } else if (PartBits == ValueVT.getSizeInBits()) {
340 // Different types of the same size.
341 assert(NumParts == 1 && PartVT != ValueVT);
342 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
343 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
344 // If the parts cover less bits than value has, truncate the value.
345 assert(PartVT.isInteger() && ValueVT.isInteger() &&
346 "Unknown mismatch!");
347 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
348 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
351 // The value may have changed - recompute ValueVT.
352 ValueVT = Val.getValueType();
353 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
354 "Failed to tile the value with PartVT!");
357 assert(PartVT == ValueVT && "Type conversion failed!");
362 // Expand the value into multiple parts.
363 if (NumParts & (NumParts - 1)) {
364 // The number of parts is not a power of 2. Split off and copy the tail.
365 assert(PartVT.isInteger() && ValueVT.isInteger() &&
366 "Do not know what to expand to!");
367 unsigned RoundParts = 1 << Log2_32(NumParts);
368 unsigned RoundBits = RoundParts * PartBits;
369 unsigned OddParts = NumParts - RoundParts;
370 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
371 DAG.getIntPtrConstant(RoundBits));
372 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT);
374 if (TLI.isBigEndian())
375 // The odd parts were reversed by getCopyToParts - unreverse them.
376 std::reverse(Parts + RoundParts, Parts + NumParts);
378 NumParts = RoundParts;
379 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
380 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
383 // The number of parts is a power of 2. Repeatedly bisect the value using
385 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
386 EVT::getIntegerVT(*DAG.getContext(),
387 ValueVT.getSizeInBits()),
390 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
391 for (unsigned i = 0; i < NumParts; i += StepSize) {
392 unsigned ThisBits = StepSize * PartBits / 2;
393 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
394 SDValue &Part0 = Parts[i];
395 SDValue &Part1 = Parts[i+StepSize/2];
397 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
398 ThisVT, Part0, DAG.getIntPtrConstant(1));
399 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
400 ThisVT, Part0, DAG.getIntPtrConstant(0));
402 if (ThisBits == PartBits && ThisVT != PartVT) {
403 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
404 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
409 if (TLI.isBigEndian())
410 std::reverse(Parts, Parts + OrigNumParts);
414 /// getCopyToPartsVector - Create a series of nodes that contain the specified
415 /// value split into legal parts.
416 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL,
417 SDValue Val, SDValue *Parts, unsigned NumParts,
419 EVT ValueVT = Val.getValueType();
420 assert(ValueVT.isVector() && "Not a vector");
421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
424 if (PartVT == ValueVT) {
426 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
427 // Bitconvert vector->vector case.
428 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
429 } else if (PartVT.isVector() &&
430 PartVT.getVectorElementType() == ValueVT.getVectorElementType()&&
431 PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
432 EVT ElementVT = PartVT.getVectorElementType();
433 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
435 SmallVector<SDValue, 16> Ops;
436 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
437 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
438 ElementVT, Val, DAG.getIntPtrConstant(i)));
440 for (unsigned i = ValueVT.getVectorNumElements(),
441 e = PartVT.getVectorNumElements(); i != e; ++i)
442 Ops.push_back(DAG.getUNDEF(ElementVT));
444 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
446 // FIXME: Use CONCAT for 2x -> 4x.
448 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
449 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
451 // Vector -> scalar conversion.
452 assert(ValueVT.getVectorElementType() == PartVT &&
453 ValueVT.getVectorNumElements() == 1 &&
454 "Only trivial vector-to-scalar conversions should get here!");
455 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
456 PartVT, Val, DAG.getIntPtrConstant(0));
463 // Handle a multi-element vector.
464 EVT IntermediateVT, RegisterVT;
465 unsigned NumIntermediates;
466 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
468 NumIntermediates, RegisterVT);
469 unsigned NumElements = ValueVT.getVectorNumElements();
471 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
472 NumParts = NumRegs; // Silence a compiler warning.
473 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
475 // Split the vector into intermediate operands.
476 SmallVector<SDValue, 8> Ops(NumIntermediates);
477 for (unsigned i = 0; i != NumIntermediates; ++i) {
478 if (IntermediateVT.isVector())
479 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
481 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates)));
483 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
484 IntermediateVT, Val, DAG.getIntPtrConstant(i));
487 // Split the intermediate operands into legal parts.
488 if (NumParts == NumIntermediates) {
489 // If the register was not expanded, promote or copy the value,
491 for (unsigned i = 0; i != NumParts; ++i)
492 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT);
493 } else if (NumParts > 0) {
494 // If the intermediate type was expanded, split each the value into
496 assert(NumParts % NumIntermediates == 0 &&
497 "Must expand into a divisible number of parts!");
498 unsigned Factor = NumParts / NumIntermediates;
499 for (unsigned i = 0; i != NumIntermediates; ++i)
500 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT);
508 /// RegsForValue - This struct represents the registers (physical or virtual)
509 /// that a particular set of values is assigned, and the type information
510 /// about the value. The most common situation is to represent one value at a
511 /// time, but struct or array values are handled element-wise as multiple
512 /// values. The splitting of aggregates is performed recursively, so that we
513 /// never have aggregate-typed registers. The values at this point do not
514 /// necessarily have legal types, so each value may require one or more
515 /// registers of some legal type.
517 struct RegsForValue {
518 /// ValueVTs - The value types of the values, which may not be legal, and
519 /// may need be promoted or synthesized from one or more registers.
521 SmallVector<EVT, 4> ValueVTs;
523 /// RegVTs - The value types of the registers. This is the same size as
524 /// ValueVTs and it records, for each value, what the type of the assigned
525 /// register or registers are. (Individual values are never synthesized
526 /// from more than one type of register.)
528 /// With virtual registers, the contents of RegVTs is redundant with TLI's
529 /// getRegisterType member function, however when with physical registers
530 /// it is necessary to have a separate record of the types.
532 SmallVector<EVT, 4> RegVTs;
534 /// Regs - This list holds the registers assigned to the values.
535 /// Each legal or promoted value requires one register, and each
536 /// expanded value requires multiple registers.
538 SmallVector<unsigned, 4> Regs;
542 RegsForValue(const SmallVector<unsigned, 4> ®s,
543 EVT regvt, EVT valuevt)
544 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
546 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
547 unsigned Reg, const Type *Ty) {
548 ComputeValueVTs(tli, Ty, ValueVTs);
550 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
551 EVT ValueVT = ValueVTs[Value];
552 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
553 EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
554 for (unsigned i = 0; i != NumRegs; ++i)
555 Regs.push_back(Reg + i);
556 RegVTs.push_back(RegisterVT);
561 /// areValueTypesLegal - Return true if types of all the values are legal.
562 bool areValueTypesLegal(const TargetLowering &TLI) {
563 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
564 EVT RegisterVT = RegVTs[Value];
565 if (!TLI.isTypeLegal(RegisterVT))
571 /// append - Add the specified values to this one.
572 void append(const RegsForValue &RHS) {
573 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
574 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
575 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
578 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
579 /// this value and returns the result as a ValueVTs value. This uses
580 /// Chain/Flag as the input and updates them for the output Chain/Flag.
581 /// If the Flag pointer is NULL, no flag is used.
582 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
584 SDValue &Chain, SDValue *Flag) const;
586 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
587 /// specified value into the registers specified by this object. This uses
588 /// Chain/Flag as the input and updates them for the output Chain/Flag.
589 /// If the Flag pointer is NULL, no flag is used.
590 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
591 SDValue &Chain, SDValue *Flag) const;
593 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
594 /// operand list. This adds the code marker, matching input operand index
595 /// (if applicable), and includes the number of values added into it.
596 void AddInlineAsmOperands(unsigned Kind,
597 bool HasMatching, unsigned MatchingIdx,
599 std::vector<SDValue> &Ops) const;
603 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
604 /// this value and returns the result as a ValueVT value. This uses
605 /// Chain/Flag as the input and updates them for the output Chain/Flag.
606 /// If the Flag pointer is NULL, no flag is used.
607 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
608 FunctionLoweringInfo &FuncInfo,
610 SDValue &Chain, SDValue *Flag) const {
611 // A Value with type {} or [0 x %t] needs no registers.
612 if (ValueVTs.empty())
615 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
617 // Assemble the legal parts into the final values.
618 SmallVector<SDValue, 4> Values(ValueVTs.size());
619 SmallVector<SDValue, 8> Parts;
620 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
621 // Copy the legal parts from the registers.
622 EVT ValueVT = ValueVTs[Value];
623 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
624 EVT RegisterVT = RegVTs[Value];
626 Parts.resize(NumRegs);
627 for (unsigned i = 0; i != NumRegs; ++i) {
630 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
632 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
633 *Flag = P.getValue(2);
636 Chain = P.getValue(1);
639 // If the source register was virtual and if we know something about it,
640 // add an assert node.
641 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
642 !RegisterVT.isInteger() || RegisterVT.isVector())
645 const FunctionLoweringInfo::LiveOutInfo *LOI =
646 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
650 unsigned RegSize = RegisterVT.getSizeInBits();
651 unsigned NumSignBits = LOI->NumSignBits;
652 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
654 // FIXME: We capture more information than the dag can represent. For
655 // now, just use the tightest assertzext/assertsext possible.
657 EVT FromVT(MVT::Other);
658 if (NumSignBits == RegSize)
659 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
660 else if (NumZeroBits >= RegSize-1)
661 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
662 else if (NumSignBits > RegSize-8)
663 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
664 else if (NumZeroBits >= RegSize-8)
665 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
666 else if (NumSignBits > RegSize-16)
667 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
668 else if (NumZeroBits >= RegSize-16)
669 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
670 else if (NumSignBits > RegSize-32)
671 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
672 else if (NumZeroBits >= RegSize-32)
673 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
677 // Add an assertion node.
678 assert(FromVT != MVT::Other);
679 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
680 RegisterVT, P, DAG.getValueType(FromVT));
683 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
684 NumRegs, RegisterVT, ValueVT);
689 return DAG.getNode(ISD::MERGE_VALUES, dl,
690 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
691 &Values[0], ValueVTs.size());
694 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
695 /// specified value into the registers specified by this object. This uses
696 /// Chain/Flag as the input and updates them for the output Chain/Flag.
697 /// If the Flag pointer is NULL, no flag is used.
698 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
699 SDValue &Chain, SDValue *Flag) const {
700 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
702 // Get the list of the values's legal parts.
703 unsigned NumRegs = Regs.size();
704 SmallVector<SDValue, 8> Parts(NumRegs);
705 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
706 EVT ValueVT = ValueVTs[Value];
707 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
708 EVT RegisterVT = RegVTs[Value];
710 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
711 &Parts[Part], NumParts, RegisterVT);
715 // Copy the parts into the registers.
716 SmallVector<SDValue, 8> Chains(NumRegs);
717 for (unsigned i = 0; i != NumRegs; ++i) {
720 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
722 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
723 *Flag = Part.getValue(1);
726 Chains[i] = Part.getValue(0);
729 if (NumRegs == 1 || Flag)
730 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
731 // flagged to it. That is the CopyToReg nodes and the user are considered
732 // a single scheduling unit. If we create a TokenFactor and return it as
733 // chain, then the TokenFactor is both a predecessor (operand) of the
734 // user as well as a successor (the TF operands are flagged to the user).
735 // c1, f1 = CopyToReg
736 // c2, f2 = CopyToReg
737 // c3 = TokenFactor c1, c2
740 Chain = Chains[NumRegs-1];
742 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
745 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
746 /// operand list. This adds the code marker and includes the number of
747 /// values added into it.
748 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
749 unsigned MatchingIdx,
751 std::vector<SDValue> &Ops) const {
752 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
754 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
756 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
757 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
760 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
761 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
762 EVT RegisterVT = RegVTs[Value];
763 for (unsigned i = 0; i != NumRegs; ++i) {
764 assert(Reg < Regs.size() && "Mismatch in # registers expected");
765 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
770 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
773 TD = DAG.getTarget().getTargetData();
776 /// clear - Clear out the current SelectionDAG and the associated
777 /// state and prepare this SelectionDAGBuilder object to be used
778 /// for a new block. This doesn't clear out information about
779 /// additional blocks that are needed to complete switch lowering
780 /// or PHI node updating; that information is cleared out as it is
782 void SelectionDAGBuilder::clear() {
784 UnusedArgNodeMap.clear();
785 PendingLoads.clear();
786 PendingExports.clear();
787 DanglingDebugInfoMap.clear();
788 CurDebugLoc = DebugLoc();
792 /// getRoot - Return the current virtual root of the Selection DAG,
793 /// flushing any PendingLoad items. This must be done before emitting
794 /// a store or any other node that may need to be ordered after any
795 /// prior load instructions.
797 SDValue SelectionDAGBuilder::getRoot() {
798 if (PendingLoads.empty())
799 return DAG.getRoot();
801 if (PendingLoads.size() == 1) {
802 SDValue Root = PendingLoads[0];
804 PendingLoads.clear();
808 // Otherwise, we have to make a token factor node.
809 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
810 &PendingLoads[0], PendingLoads.size());
811 PendingLoads.clear();
816 /// getControlRoot - Similar to getRoot, but instead of flushing all the
817 /// PendingLoad items, flush all the PendingExports items. It is necessary
818 /// to do this before emitting a terminator instruction.
820 SDValue SelectionDAGBuilder::getControlRoot() {
821 SDValue Root = DAG.getRoot();
823 if (PendingExports.empty())
826 // Turn all of the CopyToReg chains into one factored node.
827 if (Root.getOpcode() != ISD::EntryToken) {
828 unsigned i = 0, e = PendingExports.size();
829 for (; i != e; ++i) {
830 assert(PendingExports[i].getNode()->getNumOperands() > 1);
831 if (PendingExports[i].getNode()->getOperand(0) == Root)
832 break; // Don't add the root if we already indirectly depend on it.
836 PendingExports.push_back(Root);
839 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
841 PendingExports.size());
842 PendingExports.clear();
847 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
848 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
849 DAG.AssignOrdering(Node, SDNodeOrder);
851 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
852 AssignOrderingToNode(Node->getOperand(I).getNode());
855 void SelectionDAGBuilder::visit(const Instruction &I) {
856 // Set up outgoing PHI node register values before emitting the terminator.
857 if (isa<TerminatorInst>(&I))
858 HandlePHINodesInSuccessorBlocks(I.getParent());
860 CurDebugLoc = I.getDebugLoc();
862 visit(I.getOpcode(), I);
864 if (!isa<TerminatorInst>(&I) && !HasTailCall)
865 CopyToExportRegsIfNeeded(&I);
867 CurDebugLoc = DebugLoc();
870 void SelectionDAGBuilder::visitPHI(const PHINode &) {
871 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
874 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
875 // Note: this doesn't use InstVisitor, because it has to work with
876 // ConstantExpr's in addition to instructions.
878 default: llvm_unreachable("Unknown instruction type encountered!");
879 // Build the switch statement using the Instruction.def file.
880 #define HANDLE_INST(NUM, OPCODE, CLASS) \
881 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
882 #include "llvm/Instruction.def"
885 // Assign the ordering to the freshly created DAG nodes.
886 if (NodeMap.count(&I)) {
888 AssignOrderingToNode(getValue(&I).getNode());
892 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
893 // generate the debug data structures now that we've seen its definition.
894 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
896 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
898 const DbgValueInst *DI = DDI.getDI();
899 DebugLoc dl = DDI.getdl();
900 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
901 MDNode *Variable = DI->getVariable();
902 uint64_t Offset = DI->getOffset();
905 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
906 SDV = DAG.getDbgValue(Variable, Val.getNode(),
907 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
908 DAG.AddDbgValue(SDV, Val.getNode(), false);
911 DEBUG(dbgs() << "Dropping debug info for " << DI);
912 DanglingDebugInfoMap[V] = DanglingDebugInfo();
916 // getValue - Return an SDValue for the given Value.
917 SDValue SelectionDAGBuilder::getValue(const Value *V) {
918 // If we already have an SDValue for this value, use it. It's important
919 // to do this first, so that we don't create a CopyFromReg if we already
920 // have a regular SDValue.
921 SDValue &N = NodeMap[V];
922 if (N.getNode()) return N;
924 // If there's a virtual register allocated and initialized for this
926 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
927 if (It != FuncInfo.ValueMap.end()) {
928 unsigned InReg = It->second;
929 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
930 SDValue Chain = DAG.getEntryNode();
931 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain,NULL);
932 resolveDanglingDebugInfo(V, N);
936 // Otherwise create a new SDValue and remember it.
937 SDValue Val = getValueImpl(V);
939 resolveDanglingDebugInfo(V, Val);
943 /// getNonRegisterValue - Return an SDValue for the given Value, but
944 /// don't look in FuncInfo.ValueMap for a virtual register.
945 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
946 // If we already have an SDValue for this value, use it.
947 SDValue &N = NodeMap[V];
948 if (N.getNode()) return N;
950 // Otherwise create a new SDValue and remember it.
951 SDValue Val = getValueImpl(V);
953 resolveDanglingDebugInfo(V, Val);
957 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
958 /// Create an SDValue for the given value.
959 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
960 if (const Constant *C = dyn_cast<Constant>(V)) {
961 EVT VT = TLI.getValueType(V->getType(), true);
963 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
964 return DAG.getConstant(*CI, VT);
966 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
967 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT);
969 if (isa<ConstantPointerNull>(C))
970 return DAG.getConstant(0, TLI.getPointerTy());
972 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
973 return DAG.getConstantFP(*CFP, VT);
975 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
976 return DAG.getUNDEF(VT);
978 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
979 visit(CE->getOpcode(), *CE);
980 SDValue N1 = NodeMap[V];
981 assert(N1.getNode() && "visit didn't populate the NodeMap!");
985 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
986 SmallVector<SDValue, 4> Constants;
987 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
989 SDNode *Val = getValue(*OI).getNode();
990 // If the operand is an empty aggregate, there are no values.
992 // Add each leaf value from the operand to the Constants list
993 // to form a flattened list of all the values.
994 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
995 Constants.push_back(SDValue(Val, i));
998 return DAG.getMergeValues(&Constants[0], Constants.size(),
1002 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1003 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1004 "Unknown struct or array constant!");
1006 SmallVector<EVT, 4> ValueVTs;
1007 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1008 unsigned NumElts = ValueVTs.size();
1010 return SDValue(); // empty struct
1011 SmallVector<SDValue, 4> Constants(NumElts);
1012 for (unsigned i = 0; i != NumElts; ++i) {
1013 EVT EltVT = ValueVTs[i];
1014 if (isa<UndefValue>(C))
1015 Constants[i] = DAG.getUNDEF(EltVT);
1016 else if (EltVT.isFloatingPoint())
1017 Constants[i] = DAG.getConstantFP(0, EltVT);
1019 Constants[i] = DAG.getConstant(0, EltVT);
1022 return DAG.getMergeValues(&Constants[0], NumElts,
1026 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1027 return DAG.getBlockAddress(BA, VT);
1029 const VectorType *VecTy = cast<VectorType>(V->getType());
1030 unsigned NumElements = VecTy->getNumElements();
1032 // Now that we know the number and type of the elements, get that number of
1033 // elements into the Ops array based on what kind of constant it is.
1034 SmallVector<SDValue, 16> Ops;
1035 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1036 for (unsigned i = 0; i != NumElements; ++i)
1037 Ops.push_back(getValue(CP->getOperand(i)));
1039 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1040 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1043 if (EltVT.isFloatingPoint())
1044 Op = DAG.getConstantFP(0, EltVT);
1046 Op = DAG.getConstant(0, EltVT);
1047 Ops.assign(NumElements, Op);
1050 // Create a BUILD_VECTOR node.
1051 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1052 VT, &Ops[0], Ops.size());
1055 // If this is a static alloca, generate it as the frameindex instead of
1057 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1058 DenseMap<const AllocaInst*, int>::iterator SI =
1059 FuncInfo.StaticAllocaMap.find(AI);
1060 if (SI != FuncInfo.StaticAllocaMap.end())
1061 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1064 // If this is an instruction which fast-isel has deferred, select it now.
1065 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1066 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1067 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1068 SDValue Chain = DAG.getEntryNode();
1069 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
1072 llvm_unreachable("Can't get register for value!");
1076 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1077 SDValue Chain = getControlRoot();
1078 SmallVector<ISD::OutputArg, 8> Outs;
1079 SmallVector<SDValue, 8> OutVals;
1081 if (!FuncInfo.CanLowerReturn) {
1082 unsigned DemoteReg = FuncInfo.DemoteRegister;
1083 const Function *F = I.getParent()->getParent();
1085 // Emit a store of the return value through the virtual register.
1086 // Leave Outs empty so that LowerReturn won't try to load return
1087 // registers the usual way.
1088 SmallVector<EVT, 1> PtrValueVTs;
1089 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1092 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1093 SDValue RetOp = getValue(I.getOperand(0));
1095 SmallVector<EVT, 4> ValueVTs;
1096 SmallVector<uint64_t, 4> Offsets;
1097 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1098 unsigned NumValues = ValueVTs.size();
1100 SmallVector<SDValue, 4> Chains(NumValues);
1101 for (unsigned i = 0; i != NumValues; ++i) {
1102 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(),
1103 RetPtr.getValueType(), RetPtr,
1104 DAG.getIntPtrConstant(Offsets[i]));
1106 DAG.getStore(Chain, getCurDebugLoc(),
1107 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1108 // FIXME: better loc info would be nice.
1109 Add, MachinePointerInfo(), false, false, 0);
1112 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1113 MVT::Other, &Chains[0], NumValues);
1114 } else if (I.getNumOperands() != 0) {
1115 SmallVector<EVT, 4> ValueVTs;
1116 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1117 unsigned NumValues = ValueVTs.size();
1119 SDValue RetOp = getValue(I.getOperand(0));
1120 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1121 EVT VT = ValueVTs[j];
1123 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1125 const Function *F = I.getParent()->getParent();
1126 if (F->paramHasAttr(0, Attribute::SExt))
1127 ExtendKind = ISD::SIGN_EXTEND;
1128 else if (F->paramHasAttr(0, Attribute::ZExt))
1129 ExtendKind = ISD::ZERO_EXTEND;
1131 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1132 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1134 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1135 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1136 SmallVector<SDValue, 4> Parts(NumParts);
1137 getCopyToParts(DAG, getCurDebugLoc(),
1138 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1139 &Parts[0], NumParts, PartVT, ExtendKind);
1141 // 'inreg' on function refers to return value
1142 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1143 if (F->paramHasAttr(0, Attribute::InReg))
1146 // Propagate extension type if any
1147 if (ExtendKind == ISD::SIGN_EXTEND)
1149 else if (ExtendKind == ISD::ZERO_EXTEND)
1152 for (unsigned i = 0; i < NumParts; ++i) {
1153 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1155 OutVals.push_back(Parts[i]);
1161 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1162 CallingConv::ID CallConv =
1163 DAG.getMachineFunction().getFunction()->getCallingConv();
1164 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1165 Outs, OutVals, getCurDebugLoc(), DAG);
1167 // Verify that the target's LowerReturn behaved as expected.
1168 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1169 "LowerReturn didn't return a valid chain!");
1171 // Update the DAG with the new chain value resulting from return lowering.
1175 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1176 /// created for it, emit nodes to copy the value into the virtual
1178 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1179 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1180 if (VMI != FuncInfo.ValueMap.end()) {
1181 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1182 CopyValueToVirtualRegister(V, VMI->second);
1186 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1187 /// the current basic block, add it to ValueMap now so that we'll get a
1189 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1190 // No need to export constants.
1191 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1193 // Already exported?
1194 if (FuncInfo.isExportedInst(V)) return;
1196 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1197 CopyValueToVirtualRegister(V, Reg);
1200 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1201 const BasicBlock *FromBB) {
1202 // The operands of the setcc have to be in this block. We don't know
1203 // how to export them from some other block.
1204 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1205 // Can export from current BB.
1206 if (VI->getParent() == FromBB)
1209 // Is already exported, noop.
1210 return FuncInfo.isExportedInst(V);
1213 // If this is an argument, we can export it if the BB is the entry block or
1214 // if it is already exported.
1215 if (isa<Argument>(V)) {
1216 if (FromBB == &FromBB->getParent()->getEntryBlock())
1219 // Otherwise, can only export this if it is already exported.
1220 return FuncInfo.isExportedInst(V);
1223 // Otherwise, constants can always be exported.
1227 static bool InBlock(const Value *V, const BasicBlock *BB) {
1228 if (const Instruction *I = dyn_cast<Instruction>(V))
1229 return I->getParent() == BB;
1233 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1234 /// This function emits a branch and is used at the leaves of an OR or an
1235 /// AND operator tree.
1238 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1239 MachineBasicBlock *TBB,
1240 MachineBasicBlock *FBB,
1241 MachineBasicBlock *CurBB,
1242 MachineBasicBlock *SwitchBB) {
1243 const BasicBlock *BB = CurBB->getBasicBlock();
1245 // If the leaf of the tree is a comparison, merge the condition into
1247 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1248 // The operands of the cmp have to be in this block. We don't know
1249 // how to export them from some other block. If this is the first block
1250 // of the sequence, no exporting is needed.
1251 if (CurBB == SwitchBB ||
1252 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1253 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1254 ISD::CondCode Condition;
1255 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1256 Condition = getICmpCondCode(IC->getPredicate());
1257 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1258 Condition = getFCmpCondCode(FC->getPredicate());
1260 Condition = ISD::SETEQ; // silence warning.
1261 llvm_unreachable("Unknown compare instruction");
1264 CaseBlock CB(Condition, BOp->getOperand(0),
1265 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1266 SwitchCases.push_back(CB);
1271 // Create a CaseBlock record representing this branch.
1272 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1273 NULL, TBB, FBB, CurBB);
1274 SwitchCases.push_back(CB);
1277 /// FindMergedConditions - If Cond is an expression like
1278 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1279 MachineBasicBlock *TBB,
1280 MachineBasicBlock *FBB,
1281 MachineBasicBlock *CurBB,
1282 MachineBasicBlock *SwitchBB,
1284 // If this node is not part of the or/and tree, emit it as a branch.
1285 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1286 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1287 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1288 BOp->getParent() != CurBB->getBasicBlock() ||
1289 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1290 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1291 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1295 // Create TmpBB after CurBB.
1296 MachineFunction::iterator BBI = CurBB;
1297 MachineFunction &MF = DAG.getMachineFunction();
1298 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1299 CurBB->getParent()->insert(++BBI, TmpBB);
1301 if (Opc == Instruction::Or) {
1302 // Codegen X | Y as:
1310 // Emit the LHS condition.
1311 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1313 // Emit the RHS condition into TmpBB.
1314 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1316 assert(Opc == Instruction::And && "Unknown merge op!");
1317 // Codegen X & Y as:
1324 // This requires creation of TmpBB after CurBB.
1326 // Emit the LHS condition.
1327 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1329 // Emit the RHS condition into TmpBB.
1330 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1334 /// If the set of cases should be emitted as a series of branches, return true.
1335 /// If we should emit this as a bunch of and/or'd together conditions, return
1338 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1339 if (Cases.size() != 2) return true;
1341 // If this is two comparisons of the same values or'd or and'd together, they
1342 // will get folded into a single comparison, so don't emit two blocks.
1343 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1344 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1345 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1346 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1350 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1351 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1352 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1353 Cases[0].CC == Cases[1].CC &&
1354 isa<Constant>(Cases[0].CmpRHS) &&
1355 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1356 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1358 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1365 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1366 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1368 // Update machine-CFG edges.
1369 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1371 // Figure out which block is immediately after the current one.
1372 MachineBasicBlock *NextBlock = 0;
1373 MachineFunction::iterator BBI = BrMBB;
1374 if (++BBI != FuncInfo.MF->end())
1377 if (I.isUnconditional()) {
1378 // Update machine-CFG edges.
1379 BrMBB->addSuccessor(Succ0MBB);
1381 // If this is not a fall-through branch, emit the branch.
1382 if (Succ0MBB != NextBlock)
1383 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1384 MVT::Other, getControlRoot(),
1385 DAG.getBasicBlock(Succ0MBB)));
1390 // If this condition is one of the special cases we handle, do special stuff
1392 const Value *CondVal = I.getCondition();
1393 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1395 // If this is a series of conditions that are or'd or and'd together, emit
1396 // this as a sequence of branches instead of setcc's with and/or operations.
1397 // As long as jumps are not expensive, this should improve performance.
1398 // For example, instead of something like:
1411 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1412 if (!TLI.isJumpExpensive() &&
1414 (BOp->getOpcode() == Instruction::And ||
1415 BOp->getOpcode() == Instruction::Or)) {
1416 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1418 // If the compares in later blocks need to use values not currently
1419 // exported from this block, export them now. This block should always
1420 // be the first entry.
1421 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1423 // Allow some cases to be rejected.
1424 if (ShouldEmitAsBranches(SwitchCases)) {
1425 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1426 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1427 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1430 // Emit the branch for this block.
1431 visitSwitchCase(SwitchCases[0], BrMBB);
1432 SwitchCases.erase(SwitchCases.begin());
1436 // Okay, we decided not to do this, remove any inserted MBB's and clear
1438 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1439 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1441 SwitchCases.clear();
1445 // Create a CaseBlock record representing this branch.
1446 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1447 NULL, Succ0MBB, Succ1MBB, BrMBB);
1449 // Use visitSwitchCase to actually insert the fast branch sequence for this
1451 visitSwitchCase(CB, BrMBB);
1454 /// visitSwitchCase - Emits the necessary code to represent a single node in
1455 /// the binary search tree resulting from lowering a switch instruction.
1456 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1457 MachineBasicBlock *SwitchBB) {
1459 SDValue CondLHS = getValue(CB.CmpLHS);
1460 DebugLoc dl = getCurDebugLoc();
1462 // Build the setcc now.
1463 if (CB.CmpMHS == NULL) {
1464 // Fold "(X == true)" to X and "(X == false)" to !X to
1465 // handle common cases produced by branch lowering.
1466 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1467 CB.CC == ISD::SETEQ)
1469 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1470 CB.CC == ISD::SETEQ) {
1471 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1472 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1474 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1476 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1478 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1479 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1481 SDValue CmpOp = getValue(CB.CmpMHS);
1482 EVT VT = CmpOp.getValueType();
1484 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1485 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1488 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1489 VT, CmpOp, DAG.getConstant(Low, VT));
1490 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1491 DAG.getConstant(High-Low, VT), ISD::SETULE);
1495 // Update successor info
1496 SwitchBB->addSuccessor(CB.TrueBB);
1497 SwitchBB->addSuccessor(CB.FalseBB);
1499 // Set NextBlock to be the MBB immediately after the current one, if any.
1500 // This is used to avoid emitting unnecessary branches to the next block.
1501 MachineBasicBlock *NextBlock = 0;
1502 MachineFunction::iterator BBI = SwitchBB;
1503 if (++BBI != FuncInfo.MF->end())
1506 // If the lhs block is the next block, invert the condition so that we can
1507 // fall through to the lhs instead of the rhs block.
1508 if (CB.TrueBB == NextBlock) {
1509 std::swap(CB.TrueBB, CB.FalseBB);
1510 SDValue True = DAG.getConstant(1, Cond.getValueType());
1511 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1514 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1515 MVT::Other, getControlRoot(), Cond,
1516 DAG.getBasicBlock(CB.TrueBB));
1518 // Insert the false branch. Do this even if it's a fall through branch,
1519 // this makes it easier to do DAG optimizations which require inverting
1520 // the branch condition.
1521 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1522 DAG.getBasicBlock(CB.FalseBB));
1524 DAG.setRoot(BrCond);
1527 /// visitJumpTable - Emit JumpTable node in the current MBB
1528 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1529 // Emit the code for the jump table
1530 assert(JT.Reg != -1U && "Should lower JT Header first!");
1531 EVT PTy = TLI.getPointerTy();
1532 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1534 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1535 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1536 MVT::Other, Index.getValue(1),
1538 DAG.setRoot(BrJumpTable);
1541 /// visitJumpTableHeader - This function emits necessary code to produce index
1542 /// in the JumpTable from switch case.
1543 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1544 JumpTableHeader &JTH,
1545 MachineBasicBlock *SwitchBB) {
1546 // Subtract the lowest switch case value from the value being switched on and
1547 // conditional branch to default mbb if the result is greater than the
1548 // difference between smallest and largest cases.
1549 SDValue SwitchOp = getValue(JTH.SValue);
1550 EVT VT = SwitchOp.getValueType();
1551 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1552 DAG.getConstant(JTH.First, VT));
1554 // The SDNode we just created, which holds the value being switched on minus
1555 // the smallest case value, needs to be copied to a virtual register so it
1556 // can be used as an index into the jump table in a subsequent basic block.
1557 // This value may be smaller or larger than the target's pointer type, and
1558 // therefore require extension or truncating.
1559 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1561 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1562 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1563 JumpTableReg, SwitchOp);
1564 JT.Reg = JumpTableReg;
1566 // Emit the range check for the jump table, and branch to the default block
1567 // for the switch statement if the value being switched on exceeds the largest
1568 // case in the switch.
1569 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1570 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1571 DAG.getConstant(JTH.Last-JTH.First,VT),
1574 // Set NextBlock to be the MBB immediately after the current one, if any.
1575 // This is used to avoid emitting unnecessary branches to the next block.
1576 MachineBasicBlock *NextBlock = 0;
1577 MachineFunction::iterator BBI = SwitchBB;
1579 if (++BBI != FuncInfo.MF->end())
1582 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1583 MVT::Other, CopyTo, CMP,
1584 DAG.getBasicBlock(JT.Default));
1586 if (JT.MBB != NextBlock)
1587 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1588 DAG.getBasicBlock(JT.MBB));
1590 DAG.setRoot(BrCond);
1593 /// visitBitTestHeader - This function emits necessary code to produce value
1594 /// suitable for "bit tests"
1595 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1596 MachineBasicBlock *SwitchBB) {
1597 // Subtract the minimum value
1598 SDValue SwitchOp = getValue(B.SValue);
1599 EVT VT = SwitchOp.getValueType();
1600 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1601 DAG.getConstant(B.First, VT));
1604 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1605 TLI.getSetCCResultType(Sub.getValueType()),
1606 Sub, DAG.getConstant(B.Range, VT),
1609 // Determine the type of the test operands.
1610 bool UsePtrType = false;
1611 if (!TLI.isTypeLegal(VT))
1614 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1615 if ((uint64_t)((int64_t)B.Cases[i].Mask >> VT.getSizeInBits()) + 1 >= 2) {
1616 // Switch table case range are encoded into series of masks.
1617 // Just use pointer type, it's guaranteed to fit.
1623 VT = TLI.getPointerTy();
1624 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
1628 B.Reg = FuncInfo.CreateReg(VT);
1629 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1632 // Set NextBlock to be the MBB immediately after the current one, if any.
1633 // This is used to avoid emitting unnecessary branches to the next block.
1634 MachineBasicBlock *NextBlock = 0;
1635 MachineFunction::iterator BBI = SwitchBB;
1636 if (++BBI != FuncInfo.MF->end())
1639 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1641 SwitchBB->addSuccessor(B.Default);
1642 SwitchBB->addSuccessor(MBB);
1644 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1645 MVT::Other, CopyTo, RangeCmp,
1646 DAG.getBasicBlock(B.Default));
1648 if (MBB != NextBlock)
1649 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1650 DAG.getBasicBlock(MBB));
1652 DAG.setRoot(BrRange);
1655 /// visitBitTestCase - this function produces one "bit test"
1656 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1657 MachineBasicBlock* NextMBB,
1660 MachineBasicBlock *SwitchBB) {
1662 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1665 if (CountPopulation_64(B.Mask) == 1) {
1666 // Testing for a single bit; just compare the shift count with what it
1667 // would need to be to shift a 1 bit in that position.
1668 Cmp = DAG.getSetCC(getCurDebugLoc(),
1669 TLI.getSetCCResultType(VT),
1671 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
1674 // Make desired shift
1675 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
1676 DAG.getConstant(1, VT), ShiftOp);
1678 // Emit bit tests and jumps
1679 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1680 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1681 Cmp = DAG.getSetCC(getCurDebugLoc(),
1682 TLI.getSetCCResultType(VT),
1683 AndOp, DAG.getConstant(0, VT),
1687 SwitchBB->addSuccessor(B.TargetBB);
1688 SwitchBB->addSuccessor(NextMBB);
1690 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1691 MVT::Other, getControlRoot(),
1692 Cmp, DAG.getBasicBlock(B.TargetBB));
1694 // Set NextBlock to be the MBB immediately after the current one, if any.
1695 // This is used to avoid emitting unnecessary branches to the next block.
1696 MachineBasicBlock *NextBlock = 0;
1697 MachineFunction::iterator BBI = SwitchBB;
1698 if (++BBI != FuncInfo.MF->end())
1701 if (NextMBB != NextBlock)
1702 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1703 DAG.getBasicBlock(NextMBB));
1708 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1709 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1711 // Retrieve successors.
1712 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1713 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1715 const Value *Callee(I.getCalledValue());
1716 if (isa<InlineAsm>(Callee))
1719 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1721 // If the value of the invoke is used outside of its defining block, make it
1722 // available as a virtual register.
1723 CopyToExportRegsIfNeeded(&I);
1725 // Update successor info
1726 InvokeMBB->addSuccessor(Return);
1727 InvokeMBB->addSuccessor(LandingPad);
1729 // Drop into normal successor.
1730 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1731 MVT::Other, getControlRoot(),
1732 DAG.getBasicBlock(Return)));
1735 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1738 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1739 /// small case ranges).
1740 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1741 CaseRecVector& WorkList,
1743 MachineBasicBlock *Default,
1744 MachineBasicBlock *SwitchBB) {
1745 Case& BackCase = *(CR.Range.second-1);
1747 // Size is the number of Cases represented by this range.
1748 size_t Size = CR.Range.second - CR.Range.first;
1752 // Get the MachineFunction which holds the current MBB. This is used when
1753 // inserting any additional MBBs necessary to represent the switch.
1754 MachineFunction *CurMF = FuncInfo.MF;
1756 // Figure out which block is immediately after the current one.
1757 MachineBasicBlock *NextBlock = 0;
1758 MachineFunction::iterator BBI = CR.CaseBB;
1760 if (++BBI != FuncInfo.MF->end())
1763 // If any two of the cases has the same destination, and if one value
1764 // is the same as the other, but has one bit unset that the other has set,
1765 // use bit manipulation to do two compares at once. For example:
1766 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1767 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
1768 // TODO: Handle cases where CR.CaseBB != SwitchBB.
1769 if (Size == 2 && CR.CaseBB == SwitchBB) {
1770 Case &Small = *CR.Range.first;
1771 Case &Big = *(CR.Range.second-1);
1773 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
1774 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
1775 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
1777 // Check that there is only one bit different.
1778 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
1779 (SmallValue | BigValue) == BigValue) {
1780 // Isolate the common bit.
1781 APInt CommonBit = BigValue & ~SmallValue;
1782 assert((SmallValue | CommonBit) == BigValue &&
1783 CommonBit.countPopulation() == 1 && "Not a common bit?");
1785 SDValue CondLHS = getValue(SV);
1786 EVT VT = CondLHS.getValueType();
1787 DebugLoc DL = getCurDebugLoc();
1789 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
1790 DAG.getConstant(CommonBit, VT));
1791 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
1792 Or, DAG.getConstant(BigValue, VT),
1795 // Update successor info.
1796 SwitchBB->addSuccessor(Small.BB);
1797 SwitchBB->addSuccessor(Default);
1799 // Insert the true branch.
1800 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
1801 getControlRoot(), Cond,
1802 DAG.getBasicBlock(Small.BB));
1804 // Insert the false branch.
1805 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
1806 DAG.getBasicBlock(Default));
1808 DAG.setRoot(BrCond);
1814 // Rearrange the case blocks so that the last one falls through if possible.
1815 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1816 // The last case block won't fall through into 'NextBlock' if we emit the
1817 // branches in this order. See if rearranging a case value would help.
1818 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1819 if (I->BB == NextBlock) {
1820 std::swap(*I, BackCase);
1826 // Create a CaseBlock record representing a conditional branch to
1827 // the Case's target mbb if the value being switched on SV is equal
1829 MachineBasicBlock *CurBlock = CR.CaseBB;
1830 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1831 MachineBasicBlock *FallThrough;
1833 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1834 CurMF->insert(BBI, FallThrough);
1836 // Put SV in a virtual register to make it available from the new blocks.
1837 ExportFromCurrentBlock(SV);
1839 // If the last case doesn't match, go to the default block.
1840 FallThrough = Default;
1843 const Value *RHS, *LHS, *MHS;
1845 if (I->High == I->Low) {
1846 // This is just small small case range :) containing exactly 1 case
1848 LHS = SV; RHS = I->High; MHS = NULL;
1851 LHS = I->Low; MHS = SV; RHS = I->High;
1853 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1855 // If emitting the first comparison, just call visitSwitchCase to emit the
1856 // code into the current block. Otherwise, push the CaseBlock onto the
1857 // vector to be later processed by SDISel, and insert the node's MBB
1858 // before the next MBB.
1859 if (CurBlock == SwitchBB)
1860 visitSwitchCase(CB, SwitchBB);
1862 SwitchCases.push_back(CB);
1864 CurBlock = FallThrough;
1870 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1871 return !DisableJumpTables &&
1872 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1873 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1876 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1877 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1878 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
1879 return (LastExt - FirstExt + 1ULL);
1882 /// handleJTSwitchCase - Emit jumptable for current switch case range
1883 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1884 CaseRecVector& WorkList,
1886 MachineBasicBlock* Default,
1887 MachineBasicBlock *SwitchBB) {
1888 Case& FrontCase = *CR.Range.first;
1889 Case& BackCase = *(CR.Range.second-1);
1891 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1892 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1894 APInt TSize(First.getBitWidth(), 0);
1895 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1899 if (!areJTsAllowed(TLI) || TSize.ult(4))
1902 APInt Range = ComputeRange(First, Last);
1903 double Density = TSize.roundToDouble() / Range.roundToDouble();
1907 DEBUG(dbgs() << "Lowering jump table\n"
1908 << "First entry: " << First << ". Last entry: " << Last << '\n'
1909 << "Range: " << Range
1910 << ". Size: " << TSize << ". Density: " << Density << "\n\n");
1912 // Get the MachineFunction which holds the current MBB. This is used when
1913 // inserting any additional MBBs necessary to represent the switch.
1914 MachineFunction *CurMF = FuncInfo.MF;
1916 // Figure out which block is immediately after the current one.
1917 MachineFunction::iterator BBI = CR.CaseBB;
1920 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1922 // Create a new basic block to hold the code for loading the address
1923 // of the jump table, and jumping to it. Update successor information;
1924 // we will either branch to the default case for the switch, or the jump
1926 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1927 CurMF->insert(BBI, JumpTableBB);
1928 CR.CaseBB->addSuccessor(Default);
1929 CR.CaseBB->addSuccessor(JumpTableBB);
1931 // Build a vector of destination BBs, corresponding to each target
1932 // of the jump table. If the value of the jump table slot corresponds to
1933 // a case statement, push the case's BB onto the vector, otherwise, push
1935 std::vector<MachineBasicBlock*> DestBBs;
1937 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1938 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1939 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1941 if (Low.sle(TEI) && TEI.sle(High)) {
1942 DestBBs.push_back(I->BB);
1946 DestBBs.push_back(Default);
1950 // Update successor info. Add one edge to each unique successor.
1951 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1952 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1953 E = DestBBs.end(); I != E; ++I) {
1954 if (!SuccsHandled[(*I)->getNumber()]) {
1955 SuccsHandled[(*I)->getNumber()] = true;
1956 JumpTableBB->addSuccessor(*I);
1960 // Create a jump table index for this jump table.
1961 unsigned JTEncoding = TLI.getJumpTableEncoding();
1962 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1963 ->createJumpTableIndex(DestBBs);
1965 // Set the jump table information so that we can codegen it as a second
1966 // MachineBasicBlock
1967 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1968 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
1969 if (CR.CaseBB == SwitchBB)
1970 visitJumpTableHeader(JT, JTH, SwitchBB);
1972 JTCases.push_back(JumpTableBlock(JTH, JT));
1977 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1979 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1980 CaseRecVector& WorkList,
1982 MachineBasicBlock *Default,
1983 MachineBasicBlock *SwitchBB) {
1984 // Get the MachineFunction which holds the current MBB. This is used when
1985 // inserting any additional MBBs necessary to represent the switch.
1986 MachineFunction *CurMF = FuncInfo.MF;
1988 // Figure out which block is immediately after the current one.
1989 MachineFunction::iterator BBI = CR.CaseBB;
1992 Case& FrontCase = *CR.Range.first;
1993 Case& BackCase = *(CR.Range.second-1);
1994 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1996 // Size is the number of Cases represented by this range.
1997 unsigned Size = CR.Range.second - CR.Range.first;
1999 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2000 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2002 CaseItr Pivot = CR.Range.first + Size/2;
2004 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2005 // (heuristically) allow us to emit JumpTable's later.
2006 APInt TSize(First.getBitWidth(), 0);
2007 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2011 APInt LSize = FrontCase.size();
2012 APInt RSize = TSize-LSize;
2013 DEBUG(dbgs() << "Selecting best pivot: \n"
2014 << "First: " << First << ", Last: " << Last <<'\n'
2015 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2016 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2018 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2019 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2020 APInt Range = ComputeRange(LEnd, RBegin);
2021 assert((Range - 2ULL).isNonNegative() &&
2022 "Invalid case distance");
2023 double LDensity = (double)LSize.roundToDouble() /
2024 (LEnd - First + 1ULL).roundToDouble();
2025 double RDensity = (double)RSize.roundToDouble() /
2026 (Last - RBegin + 1ULL).roundToDouble();
2027 double Metric = Range.logBase2()*(LDensity+RDensity);
2028 // Should always split in some non-trivial place
2029 DEBUG(dbgs() <<"=>Step\n"
2030 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2031 << "LDensity: " << LDensity
2032 << ", RDensity: " << RDensity << '\n'
2033 << "Metric: " << Metric << '\n');
2034 if (FMetric < Metric) {
2037 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2043 if (areJTsAllowed(TLI)) {
2044 // If our case is dense we *really* should handle it earlier!
2045 assert((FMetric > 0) && "Should handle dense range earlier!");
2047 Pivot = CR.Range.first + Size/2;
2050 CaseRange LHSR(CR.Range.first, Pivot);
2051 CaseRange RHSR(Pivot, CR.Range.second);
2052 Constant *C = Pivot->Low;
2053 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2055 // We know that we branch to the LHS if the Value being switched on is
2056 // less than the Pivot value, C. We use this to optimize our binary
2057 // tree a bit, by recognizing that if SV is greater than or equal to the
2058 // LHS's Case Value, and that Case Value is exactly one less than the
2059 // Pivot's Value, then we can branch directly to the LHS's Target,
2060 // rather than creating a leaf node for it.
2061 if ((LHSR.second - LHSR.first) == 1 &&
2062 LHSR.first->High == CR.GE &&
2063 cast<ConstantInt>(C)->getValue() ==
2064 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2065 TrueBB = LHSR.first->BB;
2067 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2068 CurMF->insert(BBI, TrueBB);
2069 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2071 // Put SV in a virtual register to make it available from the new blocks.
2072 ExportFromCurrentBlock(SV);
2075 // Similar to the optimization above, if the Value being switched on is
2076 // known to be less than the Constant CR.LT, and the current Case Value
2077 // is CR.LT - 1, then we can branch directly to the target block for
2078 // the current Case Value, rather than emitting a RHS leaf node for it.
2079 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2080 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2081 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2082 FalseBB = RHSR.first->BB;
2084 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2085 CurMF->insert(BBI, FalseBB);
2086 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2088 // Put SV in a virtual register to make it available from the new blocks.
2089 ExportFromCurrentBlock(SV);
2092 // Create a CaseBlock record representing a conditional branch to
2093 // the LHS node if the value being switched on SV is less than C.
2094 // Otherwise, branch to LHS.
2095 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2097 if (CR.CaseBB == SwitchBB)
2098 visitSwitchCase(CB, SwitchBB);
2100 SwitchCases.push_back(CB);
2105 /// handleBitTestsSwitchCase - if current case range has few destination and
2106 /// range span less, than machine word bitwidth, encode case range into series
2107 /// of masks and emit bit tests with these masks.
2108 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2109 CaseRecVector& WorkList,
2111 MachineBasicBlock* Default,
2112 MachineBasicBlock *SwitchBB){
2113 EVT PTy = TLI.getPointerTy();
2114 unsigned IntPtrBits = PTy.getSizeInBits();
2116 Case& FrontCase = *CR.Range.first;
2117 Case& BackCase = *(CR.Range.second-1);
2119 // Get the MachineFunction which holds the current MBB. This is used when
2120 // inserting any additional MBBs necessary to represent the switch.
2121 MachineFunction *CurMF = FuncInfo.MF;
2123 // If target does not have legal shift left, do not emit bit tests at all.
2124 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2128 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2130 // Single case counts one, case range - two.
2131 numCmps += (I->Low == I->High ? 1 : 2);
2134 // Count unique destinations
2135 SmallSet<MachineBasicBlock*, 4> Dests;
2136 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2137 Dests.insert(I->BB);
2138 if (Dests.size() > 3)
2139 // Don't bother the code below, if there are too much unique destinations
2142 DEBUG(dbgs() << "Total number of unique destinations: "
2143 << Dests.size() << '\n'
2144 << "Total number of comparisons: " << numCmps << '\n');
2146 // Compute span of values.
2147 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2148 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2149 APInt cmpRange = maxValue - minValue;
2151 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2152 << "Low bound: " << minValue << '\n'
2153 << "High bound: " << maxValue << '\n');
2155 if (cmpRange.uge(IntPtrBits) ||
2156 (!(Dests.size() == 1 && numCmps >= 3) &&
2157 !(Dests.size() == 2 && numCmps >= 5) &&
2158 !(Dests.size() >= 3 && numCmps >= 6)))
2161 DEBUG(dbgs() << "Emitting bit tests\n");
2162 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2164 // Optimize the case where all the case values fit in a
2165 // word without having to subtract minValue. In this case,
2166 // we can optimize away the subtraction.
2167 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2168 cmpRange = maxValue;
2170 lowBound = minValue;
2173 CaseBitsVector CasesBits;
2174 unsigned i, count = 0;
2176 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2177 MachineBasicBlock* Dest = I->BB;
2178 for (i = 0; i < count; ++i)
2179 if (Dest == CasesBits[i].BB)
2183 assert((count < 3) && "Too much destinations to test!");
2184 CasesBits.push_back(CaseBits(0, Dest, 0));
2188 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2189 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2191 uint64_t lo = (lowValue - lowBound).getZExtValue();
2192 uint64_t hi = (highValue - lowBound).getZExtValue();
2194 for (uint64_t j = lo; j <= hi; j++) {
2195 CasesBits[i].Mask |= 1ULL << j;
2196 CasesBits[i].Bits++;
2200 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2204 // Figure out which block is immediately after the current one.
2205 MachineFunction::iterator BBI = CR.CaseBB;
2208 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2210 DEBUG(dbgs() << "Cases:\n");
2211 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2212 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2213 << ", Bits: " << CasesBits[i].Bits
2214 << ", BB: " << CasesBits[i].BB << '\n');
2216 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2217 CurMF->insert(BBI, CaseBB);
2218 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2222 // Put SV in a virtual register to make it available from the new blocks.
2223 ExportFromCurrentBlock(SV);
2226 BitTestBlock BTB(lowBound, cmpRange, SV,
2227 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2228 CR.CaseBB, Default, BTC);
2230 if (CR.CaseBB == SwitchBB)
2231 visitBitTestHeader(BTB, SwitchBB);
2233 BitTestCases.push_back(BTB);
2238 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2239 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2240 const SwitchInst& SI) {
2243 // Start with "simple" cases
2244 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2245 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2246 Cases.push_back(Case(SI.getSuccessorValue(i),
2247 SI.getSuccessorValue(i),
2250 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2252 // Merge case into clusters
2253 if (Cases.size() >= 2)
2254 // Must recompute end() each iteration because it may be
2255 // invalidated by erase if we hold on to it
2256 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2257 J != Cases.end(); ) {
2258 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2259 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2260 MachineBasicBlock* nextBB = J->BB;
2261 MachineBasicBlock* currentBB = I->BB;
2263 // If the two neighboring cases go to the same destination, merge them
2264 // into a single case.
2265 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2273 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2274 if (I->Low != I->High)
2275 // A range counts double, since it requires two compares.
2282 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2283 MachineBasicBlock *Last) {
2285 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2286 if (JTCases[i].first.HeaderBB == First)
2287 JTCases[i].first.HeaderBB = Last;
2289 // Update BitTestCases.
2290 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2291 if (BitTestCases[i].Parent == First)
2292 BitTestCases[i].Parent = Last;
2295 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2296 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2298 // Figure out which block is immediately after the current one.
2299 MachineBasicBlock *NextBlock = 0;
2300 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2302 // If there is only the default destination, branch to it if it is not the
2303 // next basic block. Otherwise, just fall through.
2304 if (SI.getNumOperands() == 2) {
2305 // Update machine-CFG edges.
2307 // If this is not a fall-through branch, emit the branch.
2308 SwitchMBB->addSuccessor(Default);
2309 if (Default != NextBlock)
2310 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2311 MVT::Other, getControlRoot(),
2312 DAG.getBasicBlock(Default)));
2317 // If there are any non-default case statements, create a vector of Cases
2318 // representing each one, and sort the vector so that we can efficiently
2319 // create a binary search tree from them.
2321 size_t numCmps = Clusterify(Cases, SI);
2322 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2323 << ". Total compares: " << numCmps << '\n');
2326 // Get the Value to be switched on and default basic blocks, which will be
2327 // inserted into CaseBlock records, representing basic blocks in the binary
2329 const Value *SV = SI.getOperand(0);
2331 // Push the initial CaseRec onto the worklist
2332 CaseRecVector WorkList;
2333 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2334 CaseRange(Cases.begin(),Cases.end())));
2336 while (!WorkList.empty()) {
2337 // Grab a record representing a case range to process off the worklist
2338 CaseRec CR = WorkList.back();
2339 WorkList.pop_back();
2341 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2344 // If the range has few cases (two or less) emit a series of specific
2346 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2349 // If the switch has more than 5 blocks, and at least 40% dense, and the
2350 // target supports indirect branches, then emit a jump table rather than
2351 // lowering the switch to a binary tree of conditional branches.
2352 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2355 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2356 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2357 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2361 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2362 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2364 // Update machine-CFG edges with unique successors.
2365 SmallVector<BasicBlock*, 32> succs;
2366 succs.reserve(I.getNumSuccessors());
2367 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2368 succs.push_back(I.getSuccessor(i));
2369 array_pod_sort(succs.begin(), succs.end());
2370 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2371 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2372 IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2374 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2375 MVT::Other, getControlRoot(),
2376 getValue(I.getAddress())));
2379 void SelectionDAGBuilder::visitFSub(const User &I) {
2380 // -0.0 - X --> fneg
2381 const Type *Ty = I.getType();
2382 if (isa<Constant>(I.getOperand(0)) &&
2383 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2384 SDValue Op2 = getValue(I.getOperand(1));
2385 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2386 Op2.getValueType(), Op2));
2390 visitBinary(I, ISD::FSUB);
2393 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2394 SDValue Op1 = getValue(I.getOperand(0));
2395 SDValue Op2 = getValue(I.getOperand(1));
2396 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2397 Op1.getValueType(), Op1, Op2));
2400 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2401 SDValue Op1 = getValue(I.getOperand(0));
2402 SDValue Op2 = getValue(I.getOperand(1));
2404 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
2406 // Coerce the shift amount to the right type if we can.
2407 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2408 unsigned ShiftSize = ShiftTy.getSizeInBits();
2409 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2410 DebugLoc DL = getCurDebugLoc();
2412 // If the operand is smaller than the shift count type, promote it.
2413 if (ShiftSize > Op2Size)
2414 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2416 // If the operand is larger than the shift count type but the shift
2417 // count type has enough bits to represent any shift value, truncate
2418 // it now. This is a common case and it exposes the truncate to
2419 // optimization early.
2420 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2421 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2422 // Otherwise we'll need to temporarily settle for some other convenient
2423 // type. Type legalization will make adjustments once the shiftee is split.
2425 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2428 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2429 Op1.getValueType(), Op1, Op2));
2432 void SelectionDAGBuilder::visitICmp(const User &I) {
2433 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2434 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2435 predicate = IC->getPredicate();
2436 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2437 predicate = ICmpInst::Predicate(IC->getPredicate());
2438 SDValue Op1 = getValue(I.getOperand(0));
2439 SDValue Op2 = getValue(I.getOperand(1));
2440 ISD::CondCode Opcode = getICmpCondCode(predicate);
2442 EVT DestVT = TLI.getValueType(I.getType());
2443 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2446 void SelectionDAGBuilder::visitFCmp(const User &I) {
2447 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2448 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2449 predicate = FC->getPredicate();
2450 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2451 predicate = FCmpInst::Predicate(FC->getPredicate());
2452 SDValue Op1 = getValue(I.getOperand(0));
2453 SDValue Op2 = getValue(I.getOperand(1));
2454 ISD::CondCode Condition = getFCmpCondCode(predicate);
2455 EVT DestVT = TLI.getValueType(I.getType());
2456 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2459 void SelectionDAGBuilder::visitSelect(const User &I) {
2460 SmallVector<EVT, 4> ValueVTs;
2461 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2462 unsigned NumValues = ValueVTs.size();
2463 if (NumValues == 0) return;
2465 SmallVector<SDValue, 4> Values(NumValues);
2466 SDValue Cond = getValue(I.getOperand(0));
2467 SDValue TrueVal = getValue(I.getOperand(1));
2468 SDValue FalseVal = getValue(I.getOperand(2));
2470 for (unsigned i = 0; i != NumValues; ++i)
2471 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2472 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2474 SDValue(TrueVal.getNode(),
2475 TrueVal.getResNo() + i),
2476 SDValue(FalseVal.getNode(),
2477 FalseVal.getResNo() + i));
2479 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2480 DAG.getVTList(&ValueVTs[0], NumValues),
2481 &Values[0], NumValues));
2484 void SelectionDAGBuilder::visitTrunc(const User &I) {
2485 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2486 SDValue N = getValue(I.getOperand(0));
2487 EVT DestVT = TLI.getValueType(I.getType());
2488 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2491 void SelectionDAGBuilder::visitZExt(const User &I) {
2492 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2493 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2494 SDValue N = getValue(I.getOperand(0));
2495 EVT DestVT = TLI.getValueType(I.getType());
2496 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2499 void SelectionDAGBuilder::visitSExt(const User &I) {
2500 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2501 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2502 SDValue N = getValue(I.getOperand(0));
2503 EVT DestVT = TLI.getValueType(I.getType());
2504 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2507 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2508 // FPTrunc is never a no-op cast, no need to check
2509 SDValue N = getValue(I.getOperand(0));
2510 EVT DestVT = TLI.getValueType(I.getType());
2511 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2512 DestVT, N, DAG.getIntPtrConstant(0)));
2515 void SelectionDAGBuilder::visitFPExt(const User &I){
2516 // FPTrunc is never a no-op cast, no need to check
2517 SDValue N = getValue(I.getOperand(0));
2518 EVT DestVT = TLI.getValueType(I.getType());
2519 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2522 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2523 // FPToUI is never a no-op cast, no need to check
2524 SDValue N = getValue(I.getOperand(0));
2525 EVT DestVT = TLI.getValueType(I.getType());
2526 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2529 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2530 // FPToSI is never a no-op cast, no need to check
2531 SDValue N = getValue(I.getOperand(0));
2532 EVT DestVT = TLI.getValueType(I.getType());
2533 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2536 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2537 // UIToFP is never a no-op cast, no need to check
2538 SDValue N = getValue(I.getOperand(0));
2539 EVT DestVT = TLI.getValueType(I.getType());
2540 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2543 void SelectionDAGBuilder::visitSIToFP(const User &I){
2544 // SIToFP is never a no-op cast, no need to check
2545 SDValue N = getValue(I.getOperand(0));
2546 EVT DestVT = TLI.getValueType(I.getType());
2547 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2550 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2551 // What to do depends on the size of the integer and the size of the pointer.
2552 // We can either truncate, zero extend, or no-op, accordingly.
2553 SDValue N = getValue(I.getOperand(0));
2554 EVT DestVT = TLI.getValueType(I.getType());
2555 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2558 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2559 // What to do depends on the size of the integer and the size of the pointer.
2560 // We can either truncate, zero extend, or no-op, accordingly.
2561 SDValue N = getValue(I.getOperand(0));
2562 EVT DestVT = TLI.getValueType(I.getType());
2563 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2566 void SelectionDAGBuilder::visitBitCast(const User &I) {
2567 SDValue N = getValue(I.getOperand(0));
2568 EVT DestVT = TLI.getValueType(I.getType());
2570 // BitCast assures us that source and destination are the same size so this is
2571 // either a BITCAST or a no-op.
2572 if (DestVT != N.getValueType())
2573 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
2574 DestVT, N)); // convert types.
2576 setValue(&I, N); // noop cast.
2579 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2580 SDValue InVec = getValue(I.getOperand(0));
2581 SDValue InVal = getValue(I.getOperand(1));
2582 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2584 getValue(I.getOperand(2)));
2585 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2586 TLI.getValueType(I.getType()),
2587 InVec, InVal, InIdx));
2590 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2591 SDValue InVec = getValue(I.getOperand(0));
2592 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2594 getValue(I.getOperand(1)));
2595 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2596 TLI.getValueType(I.getType()), InVec, InIdx));
2599 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2600 // from SIndx and increasing to the element length (undefs are allowed).
2601 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2602 unsigned MaskNumElts = Mask.size();
2603 for (unsigned i = 0; i != MaskNumElts; ++i)
2604 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2609 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2610 SmallVector<int, 8> Mask;
2611 SDValue Src1 = getValue(I.getOperand(0));
2612 SDValue Src2 = getValue(I.getOperand(1));
2614 // Convert the ConstantVector mask operand into an array of ints, with -1
2615 // representing undef values.
2616 SmallVector<Constant*, 8> MaskElts;
2617 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2618 unsigned MaskNumElts = MaskElts.size();
2619 for (unsigned i = 0; i != MaskNumElts; ++i) {
2620 if (isa<UndefValue>(MaskElts[i]))
2623 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2626 EVT VT = TLI.getValueType(I.getType());
2627 EVT SrcVT = Src1.getValueType();
2628 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2630 if (SrcNumElts == MaskNumElts) {
2631 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2636 // Normalize the shuffle vector since mask and vector length don't match.
2637 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2638 // Mask is longer than the source vectors and is a multiple of the source
2639 // vectors. We can use concatenate vector to make the mask and vectors
2641 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2642 // The shuffle is concatenating two vectors together.
2643 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2648 // Pad both vectors with undefs to make them the same length as the mask.
2649 unsigned NumConcat = MaskNumElts / SrcNumElts;
2650 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2651 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2652 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2654 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2655 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2659 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2660 getCurDebugLoc(), VT,
2661 &MOps1[0], NumConcat);
2662 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2663 getCurDebugLoc(), VT,
2664 &MOps2[0], NumConcat);
2666 // Readjust mask for new input vector length.
2667 SmallVector<int, 8> MappedOps;
2668 for (unsigned i = 0; i != MaskNumElts; ++i) {
2670 if (Idx < (int)SrcNumElts)
2671 MappedOps.push_back(Idx);
2673 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2676 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2681 if (SrcNumElts > MaskNumElts) {
2682 // Analyze the access pattern of the vector to see if we can extract
2683 // two subvectors and do the shuffle. The analysis is done by calculating
2684 // the range of elements the mask access on both vectors.
2685 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2686 int MaxRange[2] = {-1, -1};
2688 for (unsigned i = 0; i != MaskNumElts; ++i) {
2694 if (Idx >= (int)SrcNumElts) {
2698 if (Idx > MaxRange[Input])
2699 MaxRange[Input] = Idx;
2700 if (Idx < MinRange[Input])
2701 MinRange[Input] = Idx;
2704 // Check if the access is smaller than the vector size and can we find
2705 // a reasonable extract index.
2706 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2708 int StartIdx[2]; // StartIdx to extract from
2709 for (int Input=0; Input < 2; ++Input) {
2710 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2711 RangeUse[Input] = 0; // Unused
2712 StartIdx[Input] = 0;
2713 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2714 // Fits within range but we should see if we can find a good
2715 // start index that is a multiple of the mask length.
2716 if (MaxRange[Input] < (int)MaskNumElts) {
2717 RangeUse[Input] = 1; // Extract from beginning of the vector
2718 StartIdx[Input] = 0;
2720 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2721 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2722 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2723 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2728 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2729 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2732 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2733 // Extract appropriate subvector and generate a vector shuffle
2734 for (int Input=0; Input < 2; ++Input) {
2735 SDValue &Src = Input == 0 ? Src1 : Src2;
2736 if (RangeUse[Input] == 0)
2737 Src = DAG.getUNDEF(VT);
2739 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2740 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2743 // Calculate new mask.
2744 SmallVector<int, 8> MappedOps;
2745 for (unsigned i = 0; i != MaskNumElts; ++i) {
2748 MappedOps.push_back(Idx);
2749 else if (Idx < (int)SrcNumElts)
2750 MappedOps.push_back(Idx - StartIdx[0]);
2752 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2755 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2761 // We can't use either concat vectors or extract subvectors so fall back to
2762 // replacing the shuffle with extract and build vector.
2763 // to insert and build vector.
2764 EVT EltVT = VT.getVectorElementType();
2765 EVT PtrVT = TLI.getPointerTy();
2766 SmallVector<SDValue,8> Ops;
2767 for (unsigned i = 0; i != MaskNumElts; ++i) {
2769 Ops.push_back(DAG.getUNDEF(EltVT));
2774 if (Idx < (int)SrcNumElts)
2775 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2776 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2778 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2780 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2786 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2787 VT, &Ops[0], Ops.size()));
2790 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2791 const Value *Op0 = I.getOperand(0);
2792 const Value *Op1 = I.getOperand(1);
2793 const Type *AggTy = I.getType();
2794 const Type *ValTy = Op1->getType();
2795 bool IntoUndef = isa<UndefValue>(Op0);
2796 bool FromUndef = isa<UndefValue>(Op1);
2798 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end());
2800 SmallVector<EVT, 4> AggValueVTs;
2801 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2802 SmallVector<EVT, 4> ValValueVTs;
2803 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2805 unsigned NumAggValues = AggValueVTs.size();
2806 unsigned NumValValues = ValValueVTs.size();
2807 SmallVector<SDValue, 4> Values(NumAggValues);
2809 SDValue Agg = getValue(Op0);
2810 SDValue Val = getValue(Op1);
2812 // Copy the beginning value(s) from the original aggregate.
2813 for (; i != LinearIndex; ++i)
2814 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2815 SDValue(Agg.getNode(), Agg.getResNo() + i);
2816 // Copy values from the inserted value(s).
2817 for (; i != LinearIndex + NumValValues; ++i)
2818 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2819 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2820 // Copy remaining value(s) from the original aggregate.
2821 for (; i != NumAggValues; ++i)
2822 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2823 SDValue(Agg.getNode(), Agg.getResNo() + i);
2825 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2826 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2827 &Values[0], NumAggValues));
2830 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2831 const Value *Op0 = I.getOperand(0);
2832 const Type *AggTy = Op0->getType();
2833 const Type *ValTy = I.getType();
2834 bool OutOfUndef = isa<UndefValue>(Op0);
2836 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end());
2838 SmallVector<EVT, 4> ValValueVTs;
2839 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2841 unsigned NumValValues = ValValueVTs.size();
2842 SmallVector<SDValue, 4> Values(NumValValues);
2844 SDValue Agg = getValue(Op0);
2845 // Copy out the selected value(s).
2846 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2847 Values[i - LinearIndex] =
2849 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2850 SDValue(Agg.getNode(), Agg.getResNo() + i);
2852 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2853 DAG.getVTList(&ValValueVTs[0], NumValValues),
2854 &Values[0], NumValValues));
2857 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2858 SDValue N = getValue(I.getOperand(0));
2859 const Type *Ty = I.getOperand(0)->getType();
2861 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2863 const Value *Idx = *OI;
2864 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2865 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2868 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2869 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2870 DAG.getIntPtrConstant(Offset));
2873 Ty = StTy->getElementType(Field);
2875 Ty = cast<SequentialType>(Ty)->getElementType();
2877 // If this is a constant subscript, handle it quickly.
2878 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2879 if (CI->isZero()) continue;
2881 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2883 EVT PTy = TLI.getPointerTy();
2884 unsigned PtrBits = PTy.getSizeInBits();
2886 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2888 DAG.getConstant(Offs, MVT::i64));
2890 OffsVal = DAG.getIntPtrConstant(Offs);
2892 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2897 // N = N + Idx * ElementSize;
2898 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2899 TD->getTypeAllocSize(Ty));
2900 SDValue IdxN = getValue(Idx);
2902 // If the index is smaller or larger than intptr_t, truncate or extend
2904 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2906 // If this is a multiply by a power of two, turn it into a shl
2907 // immediately. This is a very common case.
2908 if (ElementSize != 1) {
2909 if (ElementSize.isPowerOf2()) {
2910 unsigned Amt = ElementSize.logBase2();
2911 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2912 N.getValueType(), IdxN,
2913 DAG.getConstant(Amt, TLI.getPointerTy()));
2915 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2916 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2917 N.getValueType(), IdxN, Scale);
2921 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2922 N.getValueType(), N, IdxN);
2929 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2930 // If this is a fixed sized alloca in the entry block of the function,
2931 // allocate it statically on the stack.
2932 if (FuncInfo.StaticAllocaMap.count(&I))
2933 return; // getValue will auto-populate this.
2935 const Type *Ty = I.getAllocatedType();
2936 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2938 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2941 SDValue AllocSize = getValue(I.getArraySize());
2943 EVT IntPtr = TLI.getPointerTy();
2944 if (AllocSize.getValueType() != IntPtr)
2945 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2947 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
2949 DAG.getConstant(TySize, IntPtr));
2951 // Handle alignment. If the requested alignment is less than or equal to
2952 // the stack alignment, ignore it. If the size is greater than or equal to
2953 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2954 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
2955 if (Align <= StackAlign)
2958 // Round the size of the allocation up to the stack alignment size
2959 // by add SA-1 to the size.
2960 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2961 AllocSize.getValueType(), AllocSize,
2962 DAG.getIntPtrConstant(StackAlign-1));
2964 // Mask out the low bits for alignment purposes.
2965 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2966 AllocSize.getValueType(), AllocSize,
2967 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2969 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2970 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2971 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2974 DAG.setRoot(DSA.getValue(1));
2976 // Inform the Frame Information that we have just allocated a variable-sized
2978 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
2981 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
2982 const Value *SV = I.getOperand(0);
2983 SDValue Ptr = getValue(SV);
2985 const Type *Ty = I.getType();
2987 bool isVolatile = I.isVolatile();
2988 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
2989 unsigned Alignment = I.getAlignment();
2990 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
2992 SmallVector<EVT, 4> ValueVTs;
2993 SmallVector<uint64_t, 4> Offsets;
2994 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2995 unsigned NumValues = ValueVTs.size();
3000 bool ConstantMemory = false;
3001 if (I.isVolatile() || NumValues > MaxParallelChains)
3002 // Serialize volatile loads with other side effects.
3004 else if (AA->pointsToConstantMemory(
3005 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3006 // Do not serialize (non-volatile) loads of constant memory with anything.
3007 Root = DAG.getEntryNode();
3008 ConstantMemory = true;
3010 // Do not serialize non-volatile loads against each other.
3011 Root = DAG.getRoot();
3014 SmallVector<SDValue, 4> Values(NumValues);
3015 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3017 EVT PtrVT = Ptr.getValueType();
3018 unsigned ChainI = 0;
3019 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3020 // Serializing loads here may result in excessive register pressure, and
3021 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3022 // could recover a bit by hoisting nodes upward in the chain by recognizing
3023 // they are side-effect free or do not alias. The optimizer should really
3024 // avoid this case by converting large object/array copies to llvm.memcpy
3025 // (MaxParallelChains should always remain as failsafe).
3026 if (ChainI == MaxParallelChains) {
3027 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3028 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3029 MVT::Other, &Chains[0], ChainI);
3033 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3035 DAG.getConstant(Offsets[i], PtrVT));
3036 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
3037 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3038 isNonTemporal, Alignment, TBAAInfo);
3041 Chains[ChainI] = L.getValue(1);
3044 if (!ConstantMemory) {
3045 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3046 MVT::Other, &Chains[0], ChainI);
3050 PendingLoads.push_back(Chain);
3053 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3054 DAG.getVTList(&ValueVTs[0], NumValues),
3055 &Values[0], NumValues));
3058 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3059 const Value *SrcV = I.getOperand(0);
3060 const Value *PtrV = I.getOperand(1);
3062 SmallVector<EVT, 4> ValueVTs;
3063 SmallVector<uint64_t, 4> Offsets;
3064 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3065 unsigned NumValues = ValueVTs.size();
3069 // Get the lowered operands. Note that we do this after
3070 // checking if NumResults is zero, because with zero results
3071 // the operands won't have values in the map.
3072 SDValue Src = getValue(SrcV);
3073 SDValue Ptr = getValue(PtrV);
3075 SDValue Root = getRoot();
3076 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3078 EVT PtrVT = Ptr.getValueType();
3079 bool isVolatile = I.isVolatile();
3080 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3081 unsigned Alignment = I.getAlignment();
3082 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3084 unsigned ChainI = 0;
3085 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3086 // See visitLoad comments.
3087 if (ChainI == MaxParallelChains) {
3088 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3089 MVT::Other, &Chains[0], ChainI);
3093 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3094 DAG.getConstant(Offsets[i], PtrVT));
3095 SDValue St = DAG.getStore(Root, getCurDebugLoc(),
3096 SDValue(Src.getNode(), Src.getResNo() + i),
3097 Add, MachinePointerInfo(PtrV, Offsets[i]),
3098 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3099 Chains[ChainI] = St;
3102 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3103 MVT::Other, &Chains[0], ChainI);
3105 AssignOrderingToNode(StoreNode.getNode());
3106 DAG.setRoot(StoreNode);
3109 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3111 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3112 unsigned Intrinsic) {
3113 bool HasChain = !I.doesNotAccessMemory();
3114 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3116 // Build the operand list.
3117 SmallVector<SDValue, 8> Ops;
3118 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3120 // We don't need to serialize loads against other loads.
3121 Ops.push_back(DAG.getRoot());
3123 Ops.push_back(getRoot());
3127 // Info is set by getTgtMemInstrinsic
3128 TargetLowering::IntrinsicInfo Info;
3129 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3131 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3132 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3133 Info.opc == ISD::INTRINSIC_W_CHAIN)
3134 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3136 // Add all operands of the call to the operand list.
3137 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3138 SDValue Op = getValue(I.getArgOperand(i));
3139 assert(TLI.isTypeLegal(Op.getValueType()) &&
3140 "Intrinsic uses a non-legal type?");
3144 SmallVector<EVT, 4> ValueVTs;
3145 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3147 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3148 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3149 "Intrinsic uses a non-legal type?");
3154 ValueVTs.push_back(MVT::Other);
3156 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3160 if (IsTgtIntrinsic) {
3161 // This is target intrinsic that touches memory
3162 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3163 VTs, &Ops[0], Ops.size(),
3165 MachinePointerInfo(Info.ptrVal, Info.offset),
3166 Info.align, Info.vol,
3167 Info.readMem, Info.writeMem);
3168 } else if (!HasChain) {
3169 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3170 VTs, &Ops[0], Ops.size());
3171 } else if (!I.getType()->isVoidTy()) {
3172 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3173 VTs, &Ops[0], Ops.size());
3175 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3176 VTs, &Ops[0], Ops.size());
3180 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3182 PendingLoads.push_back(Chain);
3187 if (!I.getType()->isVoidTy()) {
3188 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3189 EVT VT = TLI.getValueType(PTy);
3190 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
3193 setValue(&I, Result);
3197 /// GetSignificand - Get the significand and build it into a floating-point
3198 /// number with exponent of 1:
3200 /// Op = (Op & 0x007fffff) | 0x3f800000;
3202 /// where Op is the hexidecimal representation of floating point value.
3204 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3205 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3206 DAG.getConstant(0x007fffff, MVT::i32));
3207 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3208 DAG.getConstant(0x3f800000, MVT::i32));
3209 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3212 /// GetExponent - Get the exponent:
3214 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3216 /// where Op is the hexidecimal representation of floating point value.
3218 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3220 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3221 DAG.getConstant(0x7f800000, MVT::i32));
3222 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3223 DAG.getConstant(23, TLI.getPointerTy()));
3224 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3225 DAG.getConstant(127, MVT::i32));
3226 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3229 /// getF32Constant - Get 32-bit floating point constant.
3231 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3232 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3235 /// Inlined utility function to implement binary input atomic intrinsics for
3236 /// visitIntrinsicCall: I is a call instruction
3237 /// Op is the associated NodeType for I
3239 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
3241 SDValue Root = getRoot();
3243 DAG.getAtomic(Op, getCurDebugLoc(),
3244 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
3246 getValue(I.getArgOperand(0)),
3247 getValue(I.getArgOperand(1)),
3248 I.getArgOperand(0));
3250 DAG.setRoot(L.getValue(1));
3254 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3256 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
3257 SDValue Op1 = getValue(I.getArgOperand(0));
3258 SDValue Op2 = getValue(I.getArgOperand(1));
3260 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3261 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
3265 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3266 /// limited-precision mode.
3268 SelectionDAGBuilder::visitExp(const CallInst &I) {
3270 DebugLoc dl = getCurDebugLoc();
3272 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3273 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3274 SDValue Op = getValue(I.getArgOperand(0));
3276 // Put the exponent in the right bit position for later addition to the
3279 // #define LOG2OFe 1.4426950f
3280 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3281 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3282 getF32Constant(DAG, 0x3fb8aa3b));
3283 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3285 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3286 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3287 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3289 // IntegerPartOfX <<= 23;
3290 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3291 DAG.getConstant(23, TLI.getPointerTy()));
3293 if (LimitFloatPrecision <= 6) {
3294 // For floating-point precision of 6:
3296 // TwoToFractionalPartOfX =
3298 // (0.735607626f + 0.252464424f * x) * x;
3300 // error 0.0144103317, which is 6 bits
3301 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3302 getF32Constant(DAG, 0x3e814304));
3303 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3304 getF32Constant(DAG, 0x3f3c50c8));
3305 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3306 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3307 getF32Constant(DAG, 0x3f7f5e7e));
3308 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
3310 // Add the exponent into the result in integer domain.
3311 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3312 TwoToFracPartOfX, IntegerPartOfX);
3314 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
3315 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3316 // For floating-point precision of 12:
3318 // TwoToFractionalPartOfX =
3321 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3323 // 0.000107046256 error, which is 13 to 14 bits
3324 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3325 getF32Constant(DAG, 0x3da235e3));
3326 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3327 getF32Constant(DAG, 0x3e65b8f3));
3328 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3329 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3330 getF32Constant(DAG, 0x3f324b07));
3331 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3332 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3333 getF32Constant(DAG, 0x3f7ff8fd));
3334 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
3336 // Add the exponent into the result in integer domain.
3337 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3338 TwoToFracPartOfX, IntegerPartOfX);
3340 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
3341 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3342 // For floating-point precision of 18:
3344 // TwoToFractionalPartOfX =
3348 // (0.554906021e-1f +
3349 // (0.961591928e-2f +
3350 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3352 // error 2.47208000*10^(-7), which is better than 18 bits
3353 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3354 getF32Constant(DAG, 0x3924b03e));
3355 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3356 getF32Constant(DAG, 0x3ab24b87));
3357 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3358 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3359 getF32Constant(DAG, 0x3c1d8c17));
3360 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3361 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3362 getF32Constant(DAG, 0x3d634a1d));
3363 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3364 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3365 getF32Constant(DAG, 0x3e75fe14));
3366 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3367 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3368 getF32Constant(DAG, 0x3f317234));
3369 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3370 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3371 getF32Constant(DAG, 0x3f800000));
3372 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
3375 // Add the exponent into the result in integer domain.
3376 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3377 TwoToFracPartOfX, IntegerPartOfX);
3379 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
3382 // No special expansion.
3383 result = DAG.getNode(ISD::FEXP, dl,
3384 getValue(I.getArgOperand(0)).getValueType(),
3385 getValue(I.getArgOperand(0)));
3388 setValue(&I, result);
3391 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3392 /// limited-precision mode.
3394 SelectionDAGBuilder::visitLog(const CallInst &I) {
3396 DebugLoc dl = getCurDebugLoc();
3398 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3399 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3400 SDValue Op = getValue(I.getArgOperand(0));
3401 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3403 // Scale the exponent by log(2) [0.69314718f].
3404 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3405 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3406 getF32Constant(DAG, 0x3f317218));
3408 // Get the significand and build it into a floating-point number with
3410 SDValue X = GetSignificand(DAG, Op1, dl);
3412 if (LimitFloatPrecision <= 6) {
3413 // For floating-point precision of 6:
3417 // (1.4034025f - 0.23903021f * x) * x;
3419 // error 0.0034276066, which is better than 8 bits
3420 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3421 getF32Constant(DAG, 0xbe74c456));
3422 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3423 getF32Constant(DAG, 0x3fb3a2b1));
3424 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3425 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3426 getF32Constant(DAG, 0x3f949a29));
3428 result = DAG.getNode(ISD::FADD, dl,
3429 MVT::f32, LogOfExponent, LogOfMantissa);
3430 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3431 // For floating-point precision of 12:
3437 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3439 // error 0.000061011436, which is 14 bits
3440 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3441 getF32Constant(DAG, 0xbd67b6d6));
3442 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3443 getF32Constant(DAG, 0x3ee4f4b8));
3444 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3445 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3446 getF32Constant(DAG, 0x3fbc278b));
3447 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3448 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3449 getF32Constant(DAG, 0x40348e95));
3450 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3451 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3452 getF32Constant(DAG, 0x3fdef31a));
3454 result = DAG.getNode(ISD::FADD, dl,
3455 MVT::f32, LogOfExponent, LogOfMantissa);
3456 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3457 // For floating-point precision of 18:
3465 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3467 // error 0.0000023660568, which is better than 18 bits
3468 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3469 getF32Constant(DAG, 0xbc91e5ac));
3470 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3471 getF32Constant(DAG, 0x3e4350aa));
3472 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3473 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3474 getF32Constant(DAG, 0x3f60d3e3));
3475 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3476 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3477 getF32Constant(DAG, 0x4011cdf0));
3478 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3479 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3480 getF32Constant(DAG, 0x406cfd1c));
3481 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3482 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3483 getF32Constant(DAG, 0x408797cb));
3484 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3485 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3486 getF32Constant(DAG, 0x4006dcab));
3488 result = DAG.getNode(ISD::FADD, dl,
3489 MVT::f32, LogOfExponent, LogOfMantissa);
3492 // No special expansion.
3493 result = DAG.getNode(ISD::FLOG, dl,
3494 getValue(I.getArgOperand(0)).getValueType(),
3495 getValue(I.getArgOperand(0)));
3498 setValue(&I, result);
3501 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3502 /// limited-precision mode.
3504 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3506 DebugLoc dl = getCurDebugLoc();
3508 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3509 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3510 SDValue Op = getValue(I.getArgOperand(0));
3511 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3513 // Get the exponent.
3514 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3516 // Get the significand and build it into a floating-point number with
3518 SDValue X = GetSignificand(DAG, Op1, dl);
3520 // Different possible minimax approximations of significand in
3521 // floating-point for various degrees of accuracy over [1,2].
3522 if (LimitFloatPrecision <= 6) {
3523 // For floating-point precision of 6:
3525 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3527 // error 0.0049451742, which is more than 7 bits
3528 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3529 getF32Constant(DAG, 0xbeb08fe0));
3530 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3531 getF32Constant(DAG, 0x40019463));
3532 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3533 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3534 getF32Constant(DAG, 0x3fd6633d));
3536 result = DAG.getNode(ISD::FADD, dl,
3537 MVT::f32, LogOfExponent, Log2ofMantissa);
3538 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3539 // For floating-point precision of 12:
3545 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3547 // error 0.0000876136000, which is better than 13 bits
3548 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3549 getF32Constant(DAG, 0xbda7262e));
3550 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3551 getF32Constant(DAG, 0x3f25280b));
3552 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3553 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3554 getF32Constant(DAG, 0x4007b923));
3555 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3556 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3557 getF32Constant(DAG, 0x40823e2f));
3558 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3559 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3560 getF32Constant(DAG, 0x4020d29c));
3562 result = DAG.getNode(ISD::FADD, dl,
3563 MVT::f32, LogOfExponent, Log2ofMantissa);
3564 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3565 // For floating-point precision of 18:
3574 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3576 // error 0.0000018516, which is better than 18 bits
3577 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3578 getF32Constant(DAG, 0xbcd2769e));
3579 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3580 getF32Constant(DAG, 0x3e8ce0b9));
3581 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3582 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3583 getF32Constant(DAG, 0x3fa22ae7));
3584 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3585 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3586 getF32Constant(DAG, 0x40525723));
3587 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3588 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3589 getF32Constant(DAG, 0x40aaf200));
3590 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3591 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3592 getF32Constant(DAG, 0x40c39dad));
3593 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3594 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3595 getF32Constant(DAG, 0x4042902c));
3597 result = DAG.getNode(ISD::FADD, dl,
3598 MVT::f32, LogOfExponent, Log2ofMantissa);
3601 // No special expansion.
3602 result = DAG.getNode(ISD::FLOG2, dl,
3603 getValue(I.getArgOperand(0)).getValueType(),
3604 getValue(I.getArgOperand(0)));
3607 setValue(&I, result);
3610 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3611 /// limited-precision mode.
3613 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3615 DebugLoc dl = getCurDebugLoc();
3617 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3618 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3619 SDValue Op = getValue(I.getArgOperand(0));
3620 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3622 // Scale the exponent by log10(2) [0.30102999f].
3623 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3624 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3625 getF32Constant(DAG, 0x3e9a209a));
3627 // Get the significand and build it into a floating-point number with
3629 SDValue X = GetSignificand(DAG, Op1, dl);
3631 if (LimitFloatPrecision <= 6) {
3632 // For floating-point precision of 6:
3634 // Log10ofMantissa =
3636 // (0.60948995f - 0.10380950f * x) * x;
3638 // error 0.0014886165, which is 6 bits
3639 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3640 getF32Constant(DAG, 0xbdd49a13));
3641 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3642 getF32Constant(DAG, 0x3f1c0789));
3643 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3644 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3645 getF32Constant(DAG, 0x3f011300));
3647 result = DAG.getNode(ISD::FADD, dl,
3648 MVT::f32, LogOfExponent, Log10ofMantissa);
3649 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3650 // For floating-point precision of 12:
3652 // Log10ofMantissa =
3655 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3657 // error 0.00019228036, which is better than 12 bits
3658 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3659 getF32Constant(DAG, 0x3d431f31));
3660 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3661 getF32Constant(DAG, 0x3ea21fb2));
3662 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3663 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3664 getF32Constant(DAG, 0x3f6ae232));
3665 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3666 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3667 getF32Constant(DAG, 0x3f25f7c3));
3669 result = DAG.getNode(ISD::FADD, dl,
3670 MVT::f32, LogOfExponent, Log10ofMantissa);
3671 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3672 // For floating-point precision of 18:
3674 // Log10ofMantissa =
3679 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3681 // error 0.0000037995730, which is better than 18 bits
3682 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3683 getF32Constant(DAG, 0x3c5d51ce));
3684 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3685 getF32Constant(DAG, 0x3e00685a));
3686 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3687 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3688 getF32Constant(DAG, 0x3efb6798));
3689 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3690 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3691 getF32Constant(DAG, 0x3f88d192));
3692 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3693 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3694 getF32Constant(DAG, 0x3fc4316c));
3695 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3696 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3697 getF32Constant(DAG, 0x3f57ce70));
3699 result = DAG.getNode(ISD::FADD, dl,
3700 MVT::f32, LogOfExponent, Log10ofMantissa);
3703 // No special expansion.
3704 result = DAG.getNode(ISD::FLOG10, dl,
3705 getValue(I.getArgOperand(0)).getValueType(),
3706 getValue(I.getArgOperand(0)));
3709 setValue(&I, result);
3712 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3713 /// limited-precision mode.
3715 SelectionDAGBuilder::visitExp2(const CallInst &I) {
3717 DebugLoc dl = getCurDebugLoc();
3719 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3720 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3721 SDValue Op = getValue(I.getArgOperand(0));
3723 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3725 // FractionalPartOfX = x - (float)IntegerPartOfX;
3726 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3727 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3729 // IntegerPartOfX <<= 23;
3730 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3731 DAG.getConstant(23, TLI.getPointerTy()));
3733 if (LimitFloatPrecision <= 6) {
3734 // For floating-point precision of 6:
3736 // TwoToFractionalPartOfX =
3738 // (0.735607626f + 0.252464424f * x) * x;
3740 // error 0.0144103317, which is 6 bits
3741 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3742 getF32Constant(DAG, 0x3e814304));
3743 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3744 getF32Constant(DAG, 0x3f3c50c8));
3745 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3746 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3747 getF32Constant(DAG, 0x3f7f5e7e));
3748 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
3749 SDValue TwoToFractionalPartOfX =
3750 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3752 result = DAG.getNode(ISD::BITCAST, dl,
3753 MVT::f32, TwoToFractionalPartOfX);
3754 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3755 // For floating-point precision of 12:
3757 // TwoToFractionalPartOfX =
3760 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3762 // error 0.000107046256, which is 13 to 14 bits
3763 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3764 getF32Constant(DAG, 0x3da235e3));
3765 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3766 getF32Constant(DAG, 0x3e65b8f3));
3767 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3768 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3769 getF32Constant(DAG, 0x3f324b07));
3770 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3771 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3772 getF32Constant(DAG, 0x3f7ff8fd));
3773 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
3774 SDValue TwoToFractionalPartOfX =
3775 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3777 result = DAG.getNode(ISD::BITCAST, dl,
3778 MVT::f32, TwoToFractionalPartOfX);
3779 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3780 // For floating-point precision of 18:
3782 // TwoToFractionalPartOfX =
3786 // (0.554906021e-1f +
3787 // (0.961591928e-2f +
3788 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3789 // error 2.47208000*10^(-7), which is better than 18 bits
3790 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3791 getF32Constant(DAG, 0x3924b03e));
3792 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3793 getF32Constant(DAG, 0x3ab24b87));
3794 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3795 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3796 getF32Constant(DAG, 0x3c1d8c17));
3797 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3798 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3799 getF32Constant(DAG, 0x3d634a1d));
3800 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3801 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3802 getF32Constant(DAG, 0x3e75fe14));
3803 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3804 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3805 getF32Constant(DAG, 0x3f317234));
3806 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3807 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3808 getF32Constant(DAG, 0x3f800000));
3809 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
3810 SDValue TwoToFractionalPartOfX =
3811 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3813 result = DAG.getNode(ISD::BITCAST, dl,
3814 MVT::f32, TwoToFractionalPartOfX);
3817 // No special expansion.
3818 result = DAG.getNode(ISD::FEXP2, dl,
3819 getValue(I.getArgOperand(0)).getValueType(),
3820 getValue(I.getArgOperand(0)));
3823 setValue(&I, result);
3826 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3827 /// limited-precision mode with x == 10.0f.
3829 SelectionDAGBuilder::visitPow(const CallInst &I) {
3831 const Value *Val = I.getArgOperand(0);
3832 DebugLoc dl = getCurDebugLoc();
3833 bool IsExp10 = false;
3835 if (getValue(Val).getValueType() == MVT::f32 &&
3836 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
3837 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3838 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3839 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3841 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3846 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3847 SDValue Op = getValue(I.getArgOperand(1));
3849 // Put the exponent in the right bit position for later addition to the
3852 // #define LOG2OF10 3.3219281f
3853 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3854 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3855 getF32Constant(DAG, 0x40549a78));
3856 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3858 // FractionalPartOfX = x - (float)IntegerPartOfX;
3859 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3860 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3862 // IntegerPartOfX <<= 23;
3863 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3864 DAG.getConstant(23, TLI.getPointerTy()));
3866 if (LimitFloatPrecision <= 6) {
3867 // For floating-point precision of 6:
3869 // twoToFractionalPartOfX =
3871 // (0.735607626f + 0.252464424f * x) * x;
3873 // error 0.0144103317, which is 6 bits
3874 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3875 getF32Constant(DAG, 0x3e814304));
3876 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3877 getF32Constant(DAG, 0x3f3c50c8));
3878 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3879 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3880 getF32Constant(DAG, 0x3f7f5e7e));
3881 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
3882 SDValue TwoToFractionalPartOfX =
3883 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3885 result = DAG.getNode(ISD::BITCAST, dl,
3886 MVT::f32, TwoToFractionalPartOfX);
3887 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3888 // For floating-point precision of 12:
3890 // TwoToFractionalPartOfX =
3893 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3895 // error 0.000107046256, which is 13 to 14 bits
3896 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3897 getF32Constant(DAG, 0x3da235e3));
3898 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3899 getF32Constant(DAG, 0x3e65b8f3));
3900 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3901 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3902 getF32Constant(DAG, 0x3f324b07));
3903 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3904 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3905 getF32Constant(DAG, 0x3f7ff8fd));
3906 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
3907 SDValue TwoToFractionalPartOfX =
3908 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3910 result = DAG.getNode(ISD::BITCAST, dl,
3911 MVT::f32, TwoToFractionalPartOfX);
3912 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3913 // For floating-point precision of 18:
3915 // TwoToFractionalPartOfX =
3919 // (0.554906021e-1f +
3920 // (0.961591928e-2f +
3921 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3922 // error 2.47208000*10^(-7), which is better than 18 bits
3923 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3924 getF32Constant(DAG, 0x3924b03e));
3925 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3926 getF32Constant(DAG, 0x3ab24b87));
3927 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3928 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3929 getF32Constant(DAG, 0x3c1d8c17));
3930 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3931 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3932 getF32Constant(DAG, 0x3d634a1d));
3933 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3934 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3935 getF32Constant(DAG, 0x3e75fe14));
3936 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3937 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3938 getF32Constant(DAG, 0x3f317234));
3939 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3940 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3941 getF32Constant(DAG, 0x3f800000));
3942 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
3943 SDValue TwoToFractionalPartOfX =
3944 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3946 result = DAG.getNode(ISD::BITCAST, dl,
3947 MVT::f32, TwoToFractionalPartOfX);
3950 // No special expansion.
3951 result = DAG.getNode(ISD::FPOW, dl,
3952 getValue(I.getArgOperand(0)).getValueType(),
3953 getValue(I.getArgOperand(0)),
3954 getValue(I.getArgOperand(1)));
3957 setValue(&I, result);
3961 /// ExpandPowI - Expand a llvm.powi intrinsic.
3962 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3963 SelectionDAG &DAG) {
3964 // If RHS is a constant, we can expand this out to a multiplication tree,
3965 // otherwise we end up lowering to a call to __powidf2 (for example). When
3966 // optimizing for size, we only want to do this if the expansion would produce
3967 // a small number of multiplies, otherwise we do the full expansion.
3968 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3969 // Get the exponent as a positive value.
3970 unsigned Val = RHSC->getSExtValue();
3971 if ((int)Val < 0) Val = -Val;
3973 // powi(x, 0) -> 1.0
3975 return DAG.getConstantFP(1.0, LHS.getValueType());
3977 const Function *F = DAG.getMachineFunction().getFunction();
3978 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3979 // If optimizing for size, don't insert too many multiplies. This
3980 // inserts up to 5 multiplies.
3981 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3982 // We use the simple binary decomposition method to generate the multiply
3983 // sequence. There are more optimal ways to do this (for example,
3984 // powi(x,15) generates one more multiply than it should), but this has
3985 // the benefit of being both really simple and much better than a libcall.
3986 SDValue Res; // Logically starts equal to 1.0
3987 SDValue CurSquare = LHS;
3991 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3993 Res = CurSquare; // 1.0*CurSquare.
3996 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3997 CurSquare, CurSquare);
4001 // If the original was negative, invert the result, producing 1/(x*x*x).
4002 if (RHSC->getSExtValue() < 0)
4003 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4004 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4009 // Otherwise, expand to a libcall.
4010 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4013 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4014 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4015 /// At the end of instruction selection, they will be inserted to the entry BB.
4017 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4020 const Argument *Arg = dyn_cast<Argument>(V);
4024 MachineFunction &MF = DAG.getMachineFunction();
4025 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4026 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4028 // Ignore inlined function arguments here.
4029 DIVariable DV(Variable);
4030 if (DV.isInlinedFnArgument(MF.getFunction()))
4033 MachineBasicBlock *MBB = FuncInfo.MBB;
4034 if (MBB != &MF.front())
4038 if (Arg->hasByValAttr()) {
4039 // Byval arguments' frame index is recorded during argument lowering.
4040 // Use this info directly.
4041 Reg = TRI->getFrameRegister(MF);
4042 Offset = FuncInfo.getByValArgumentFrameIndex(Arg);
4043 // If byval argument ofset is not recorded then ignore this.
4048 if (N.getNode() && N.getOpcode() == ISD::CopyFromReg) {
4049 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4050 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
4051 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4052 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4059 // Check if ValueMap has reg number.
4060 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4061 if (VMI != FuncInfo.ValueMap.end())
4065 if (!Reg && N.getNode()) {
4066 // Check if frame index is available.
4067 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4068 if (FrameIndexSDNode *FINode =
4069 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4070 Reg = TRI->getFrameRegister(MF);
4071 Offset = FINode->getIndex();
4078 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4079 TII->get(TargetOpcode::DBG_VALUE))
4080 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
4081 FuncInfo.ArgDbgValues.push_back(&*MIB);
4085 // VisualStudio defines setjmp as _setjmp
4086 #if defined(_MSC_VER) && defined(setjmp) && \
4087 !defined(setjmp_undefined_for_msvc)
4088 # pragma push_macro("setjmp")
4090 # define setjmp_undefined_for_msvc
4093 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4094 /// we want to emit this as a call to a named external function, return the name
4095 /// otherwise lower it and return null.
4097 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4098 DebugLoc dl = getCurDebugLoc();
4101 switch (Intrinsic) {
4103 // By default, turn this into a target intrinsic node.
4104 visitTargetIntrinsic(I, Intrinsic);
4106 case Intrinsic::vastart: visitVAStart(I); return 0;
4107 case Intrinsic::vaend: visitVAEnd(I); return 0;
4108 case Intrinsic::vacopy: visitVACopy(I); return 0;
4109 case Intrinsic::returnaddress:
4110 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4111 getValue(I.getArgOperand(0))));
4113 case Intrinsic::frameaddress:
4114 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4115 getValue(I.getArgOperand(0))));
4117 case Intrinsic::setjmp:
4118 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4119 case Intrinsic::longjmp:
4120 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4121 case Intrinsic::memcpy: {
4122 // Assert for address < 256 since we support only user defined address
4124 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4126 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4128 "Unknown address space");
4129 SDValue Op1 = getValue(I.getArgOperand(0));
4130 SDValue Op2 = getValue(I.getArgOperand(1));
4131 SDValue Op3 = getValue(I.getArgOperand(2));
4132 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4133 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4134 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
4135 MachinePointerInfo(I.getArgOperand(0)),
4136 MachinePointerInfo(I.getArgOperand(1))));
4139 case Intrinsic::memset: {
4140 // Assert for address < 256 since we support only user defined address
4142 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4144 "Unknown address space");
4145 SDValue Op1 = getValue(I.getArgOperand(0));
4146 SDValue Op2 = getValue(I.getArgOperand(1));
4147 SDValue Op3 = getValue(I.getArgOperand(2));
4148 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4149 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4150 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4151 MachinePointerInfo(I.getArgOperand(0))));
4154 case Intrinsic::memmove: {
4155 // Assert for address < 256 since we support only user defined address
4157 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4159 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4161 "Unknown address space");
4162 SDValue Op1 = getValue(I.getArgOperand(0));
4163 SDValue Op2 = getValue(I.getArgOperand(1));
4164 SDValue Op3 = getValue(I.getArgOperand(2));
4165 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4166 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4167 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4168 MachinePointerInfo(I.getArgOperand(0)),
4169 MachinePointerInfo(I.getArgOperand(1))));
4172 case Intrinsic::dbg_declare: {
4173 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4174 MDNode *Variable = DI.getVariable();
4175 const Value *Address = DI.getAddress();
4176 if (!Address || !DIVariable(DI.getVariable()).Verify())
4179 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4180 // but do not always have a corresponding SDNode built. The SDNodeOrder
4181 // absolute, but not relative, values are different depending on whether
4182 // debug info exists.
4185 // Check if address has undef value.
4186 if (isa<UndefValue>(Address) ||
4187 (Address->use_empty() && !isa<Argument>(Address))) {
4188 DEBUG(dbgs() << "Dropping debug info for " << DI);
4192 SDValue &N = NodeMap[Address];
4193 if (!N.getNode() && isa<Argument>(Address))
4194 // Check unused arguments map.
4195 N = UnusedArgNodeMap[Address];
4198 // Parameters are handled specially.
4200 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
4201 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4202 Address = BCI->getOperand(0);
4203 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4205 if (isParameter && !AI) {
4206 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4208 // Byval parameter. We have a frame index at this point.
4209 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4210 0, dl, SDNodeOrder);
4212 // Can't do anything with other non-AI cases yet. This might be a
4213 // parameter of a callee function that got inlined, for example.
4214 DEBUG(dbgs() << "Dropping debug info for " << DI);
4218 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4219 0, dl, SDNodeOrder);
4221 // Can't do anything with other non-AI cases yet.
4222 DEBUG(dbgs() << "Dropping debug info for " << DI);
4225 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4227 // If Address is an argument then try to emit its dbg value using
4228 // virtual register info from the FuncInfo.ValueMap.
4229 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4230 // If variable is pinned by a alloca in dominating bb then
4231 // use StaticAllocaMap.
4232 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4233 if (AI->getParent() != DI.getParent()) {
4234 DenseMap<const AllocaInst*, int>::iterator SI =
4235 FuncInfo.StaticAllocaMap.find(AI);
4236 if (SI != FuncInfo.StaticAllocaMap.end()) {
4237 SDV = DAG.getDbgValue(Variable, SI->second,
4238 0, dl, SDNodeOrder);
4239 DAG.AddDbgValue(SDV, 0, false);
4244 DEBUG(dbgs() << "Dropping debug info for " << DI);
4249 case Intrinsic::dbg_value: {
4250 const DbgValueInst &DI = cast<DbgValueInst>(I);
4251 if (!DIVariable(DI.getVariable()).Verify())
4254 MDNode *Variable = DI.getVariable();
4255 uint64_t Offset = DI.getOffset();
4256 const Value *V = DI.getValue();
4260 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4261 // but do not always have a corresponding SDNode built. The SDNodeOrder
4262 // absolute, but not relative, values are different depending on whether
4263 // debug info exists.
4266 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
4267 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4268 DAG.AddDbgValue(SDV, 0, false);
4270 // Do not use getValue() in here; we don't want to generate code at
4271 // this point if it hasn't been done yet.
4272 SDValue N = NodeMap[V];
4273 if (!N.getNode() && isa<Argument>(V))
4274 // Check unused arguments map.
4275 N = UnusedArgNodeMap[V];
4277 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4278 SDV = DAG.getDbgValue(Variable, N.getNode(),
4279 N.getResNo(), Offset, dl, SDNodeOrder);
4280 DAG.AddDbgValue(SDV, N.getNode(), false);
4282 } else if (!V->use_empty() ) {
4283 // Do not call getValue(V) yet, as we don't want to generate code.
4284 // Remember it for later.
4285 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4286 DanglingDebugInfoMap[V] = DDI;
4288 // We may expand this to cover more cases. One case where we have no
4289 // data available is an unreferenced parameter.
4290 DEBUG(dbgs() << "Dropping debug info for " << DI);
4294 // Build a debug info table entry.
4295 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4296 V = BCI->getOperand(0);
4297 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4298 // Don't handle byval struct arguments or VLAs, for example.
4301 DenseMap<const AllocaInst*, int>::iterator SI =
4302 FuncInfo.StaticAllocaMap.find(AI);
4303 if (SI == FuncInfo.StaticAllocaMap.end())
4305 int FI = SI->second;
4307 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4308 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4309 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4312 case Intrinsic::eh_exception: {
4313 // Insert the EXCEPTIONADDR instruction.
4314 assert(FuncInfo.MBB->isLandingPad() &&
4315 "Call to eh.exception not in landing pad!");
4316 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4318 Ops[0] = DAG.getRoot();
4319 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4321 DAG.setRoot(Op.getValue(1));
4325 case Intrinsic::eh_selector: {
4326 MachineBasicBlock *CallMBB = FuncInfo.MBB;
4327 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4328 if (CallMBB->isLandingPad())
4329 AddCatchInfo(I, &MMI, CallMBB);
4332 FuncInfo.CatchInfoLost.insert(&I);
4334 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4335 unsigned Reg = TLI.getExceptionSelectorRegister();
4336 if (Reg) FuncInfo.MBB->addLiveIn(Reg);
4339 // Insert the EHSELECTION instruction.
4340 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4342 Ops[0] = getValue(I.getArgOperand(0));
4344 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4345 DAG.setRoot(Op.getValue(1));
4346 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4350 case Intrinsic::eh_typeid_for: {
4351 // Find the type id for the given typeinfo.
4352 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4353 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4354 Res = DAG.getConstant(TypeID, MVT::i32);
4359 case Intrinsic::eh_return_i32:
4360 case Intrinsic::eh_return_i64:
4361 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4362 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4365 getValue(I.getArgOperand(0)),
4366 getValue(I.getArgOperand(1))));
4368 case Intrinsic::eh_unwind_init:
4369 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4371 case Intrinsic::eh_dwarf_cfa: {
4372 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
4373 TLI.getPointerTy());
4374 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4376 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4377 TLI.getPointerTy()),
4379 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4381 DAG.getConstant(0, TLI.getPointerTy()));
4382 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4386 case Intrinsic::eh_sjlj_callsite: {
4387 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4388 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4389 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4390 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4392 MMI.setCurrentCallSite(CI->getZExtValue());
4395 case Intrinsic::eh_sjlj_setjmp: {
4396 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(),
4397 getValue(I.getArgOperand(0))));
4400 case Intrinsic::eh_sjlj_longjmp: {
4401 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
4402 getRoot(), getValue(I.getArgOperand(0))));
4405 case Intrinsic::eh_sjlj_dispatch_setup: {
4406 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
4407 getRoot(), getValue(I.getArgOperand(0))));
4411 case Intrinsic::x86_mmx_pslli_w:
4412 case Intrinsic::x86_mmx_pslli_d:
4413 case Intrinsic::x86_mmx_pslli_q:
4414 case Intrinsic::x86_mmx_psrli_w:
4415 case Intrinsic::x86_mmx_psrli_d:
4416 case Intrinsic::x86_mmx_psrli_q:
4417 case Intrinsic::x86_mmx_psrai_w:
4418 case Intrinsic::x86_mmx_psrai_d: {
4419 SDValue ShAmt = getValue(I.getArgOperand(1));
4420 if (isa<ConstantSDNode>(ShAmt)) {
4421 visitTargetIntrinsic(I, Intrinsic);
4424 unsigned NewIntrinsic = 0;
4425 EVT ShAmtVT = MVT::v2i32;
4426 switch (Intrinsic) {
4427 case Intrinsic::x86_mmx_pslli_w:
4428 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4430 case Intrinsic::x86_mmx_pslli_d:
4431 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4433 case Intrinsic::x86_mmx_pslli_q:
4434 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4436 case Intrinsic::x86_mmx_psrli_w:
4437 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4439 case Intrinsic::x86_mmx_psrli_d:
4440 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4442 case Intrinsic::x86_mmx_psrli_q:
4443 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4445 case Intrinsic::x86_mmx_psrai_w:
4446 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4448 case Intrinsic::x86_mmx_psrai_d:
4449 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4451 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4454 // The vector shift intrinsics with scalars uses 32b shift amounts but
4455 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4457 // We must do this early because v2i32 is not a legal type.
4458 DebugLoc dl = getCurDebugLoc();
4461 ShOps[1] = DAG.getConstant(0, MVT::i32);
4462 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4463 EVT DestVT = TLI.getValueType(I.getType());
4464 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
4465 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4466 DAG.getConstant(NewIntrinsic, MVT::i32),
4467 getValue(I.getArgOperand(0)), ShAmt);
4471 case Intrinsic::convertff:
4472 case Intrinsic::convertfsi:
4473 case Intrinsic::convertfui:
4474 case Intrinsic::convertsif:
4475 case Intrinsic::convertuif:
4476 case Intrinsic::convertss:
4477 case Intrinsic::convertsu:
4478 case Intrinsic::convertus:
4479 case Intrinsic::convertuu: {
4480 ISD::CvtCode Code = ISD::CVT_INVALID;
4481 switch (Intrinsic) {
4482 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4483 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4484 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4485 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4486 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4487 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4488 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4489 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4490 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4492 EVT DestVT = TLI.getValueType(I.getType());
4493 const Value *Op1 = I.getArgOperand(0);
4494 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4495 DAG.getValueType(DestVT),
4496 DAG.getValueType(getValue(Op1).getValueType()),
4497 getValue(I.getArgOperand(1)),
4498 getValue(I.getArgOperand(2)),
4503 case Intrinsic::sqrt:
4504 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4505 getValue(I.getArgOperand(0)).getValueType(),
4506 getValue(I.getArgOperand(0))));
4508 case Intrinsic::powi:
4509 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4510 getValue(I.getArgOperand(1)), DAG));
4512 case Intrinsic::sin:
4513 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4514 getValue(I.getArgOperand(0)).getValueType(),
4515 getValue(I.getArgOperand(0))));
4517 case Intrinsic::cos:
4518 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4519 getValue(I.getArgOperand(0)).getValueType(),
4520 getValue(I.getArgOperand(0))));
4522 case Intrinsic::log:
4525 case Intrinsic::log2:
4528 case Intrinsic::log10:
4531 case Intrinsic::exp:
4534 case Intrinsic::exp2:
4537 case Intrinsic::pow:
4540 case Intrinsic::convert_to_fp16:
4541 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4542 MVT::i16, getValue(I.getArgOperand(0))));
4544 case Intrinsic::convert_from_fp16:
4545 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4546 MVT::f32, getValue(I.getArgOperand(0))));
4548 case Intrinsic::pcmarker: {
4549 SDValue Tmp = getValue(I.getArgOperand(0));
4550 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4553 case Intrinsic::readcyclecounter: {
4554 SDValue Op = getRoot();
4555 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4556 DAG.getVTList(MVT::i64, MVT::Other),
4559 DAG.setRoot(Res.getValue(1));
4562 case Intrinsic::bswap:
4563 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4564 getValue(I.getArgOperand(0)).getValueType(),
4565 getValue(I.getArgOperand(0))));
4567 case Intrinsic::cttz: {
4568 SDValue Arg = getValue(I.getArgOperand(0));
4569 EVT Ty = Arg.getValueType();
4570 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4573 case Intrinsic::ctlz: {
4574 SDValue Arg = getValue(I.getArgOperand(0));
4575 EVT Ty = Arg.getValueType();
4576 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4579 case Intrinsic::ctpop: {
4580 SDValue Arg = getValue(I.getArgOperand(0));
4581 EVT Ty = Arg.getValueType();
4582 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4585 case Intrinsic::stacksave: {
4586 SDValue Op = getRoot();
4587 Res = DAG.getNode(ISD::STACKSAVE, dl,
4588 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4590 DAG.setRoot(Res.getValue(1));
4593 case Intrinsic::stackrestore: {
4594 Res = getValue(I.getArgOperand(0));
4595 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4598 case Intrinsic::stackprotector: {
4599 // Emit code into the DAG to store the stack guard onto the stack.
4600 MachineFunction &MF = DAG.getMachineFunction();
4601 MachineFrameInfo *MFI = MF.getFrameInfo();
4602 EVT PtrTy = TLI.getPointerTy();
4604 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4605 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4607 int FI = FuncInfo.StaticAllocaMap[Slot];
4608 MFI->setStackProtectorIndex(FI);
4610 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4612 // Store the stack protector onto the stack.
4613 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4614 MachinePointerInfo::getFixedStack(FI),
4620 case Intrinsic::objectsize: {
4621 // If we don't know by now, we're never going to know.
4622 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4624 assert(CI && "Non-constant type in __builtin_object_size?");
4626 SDValue Arg = getValue(I.getCalledValue());
4627 EVT Ty = Arg.getValueType();
4630 Res = DAG.getConstant(-1ULL, Ty);
4632 Res = DAG.getConstant(0, Ty);
4637 case Intrinsic::var_annotation:
4638 // Discard annotate attributes
4641 case Intrinsic::init_trampoline: {
4642 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4646 Ops[1] = getValue(I.getArgOperand(0));
4647 Ops[2] = getValue(I.getArgOperand(1));
4648 Ops[3] = getValue(I.getArgOperand(2));
4649 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4650 Ops[5] = DAG.getSrcValue(F);
4652 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4653 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4657 DAG.setRoot(Res.getValue(1));
4660 case Intrinsic::gcroot:
4662 const Value *Alloca = I.getArgOperand(0);
4663 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4665 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4666 GFI->addStackRoot(FI->getIndex(), TypeMap);
4669 case Intrinsic::gcread:
4670 case Intrinsic::gcwrite:
4671 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4673 case Intrinsic::flt_rounds:
4674 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4676 case Intrinsic::trap:
4677 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4679 case Intrinsic::uadd_with_overflow:
4680 return implVisitAluOverflow(I, ISD::UADDO);
4681 case Intrinsic::sadd_with_overflow:
4682 return implVisitAluOverflow(I, ISD::SADDO);
4683 case Intrinsic::usub_with_overflow:
4684 return implVisitAluOverflow(I, ISD::USUBO);
4685 case Intrinsic::ssub_with_overflow:
4686 return implVisitAluOverflow(I, ISD::SSUBO);
4687 case Intrinsic::umul_with_overflow:
4688 return implVisitAluOverflow(I, ISD::UMULO);
4689 case Intrinsic::smul_with_overflow:
4690 return implVisitAluOverflow(I, ISD::SMULO);
4692 case Intrinsic::prefetch: {
4694 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4696 Ops[1] = getValue(I.getArgOperand(0));
4697 Ops[2] = getValue(I.getArgOperand(1));
4698 Ops[3] = getValue(I.getArgOperand(2));
4699 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
4700 DAG.getVTList(MVT::Other),
4702 EVT::getIntegerVT(*Context, 8),
4703 MachinePointerInfo(I.getArgOperand(0)),
4705 false, /* volatile */
4707 rw==1)); /* write */
4710 case Intrinsic::memory_barrier: {
4713 for (int x = 1; x < 6; ++x)
4714 Ops[x] = getValue(I.getArgOperand(x - 1));
4716 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4719 case Intrinsic::atomic_cmp_swap: {
4720 SDValue Root = getRoot();
4722 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4723 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
4725 getValue(I.getArgOperand(0)),
4726 getValue(I.getArgOperand(1)),
4727 getValue(I.getArgOperand(2)),
4728 MachinePointerInfo(I.getArgOperand(0)));
4730 DAG.setRoot(L.getValue(1));
4733 case Intrinsic::atomic_load_add:
4734 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4735 case Intrinsic::atomic_load_sub:
4736 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4737 case Intrinsic::atomic_load_or:
4738 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4739 case Intrinsic::atomic_load_xor:
4740 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4741 case Intrinsic::atomic_load_and:
4742 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4743 case Intrinsic::atomic_load_nand:
4744 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4745 case Intrinsic::atomic_load_max:
4746 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4747 case Intrinsic::atomic_load_min:
4748 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4749 case Intrinsic::atomic_load_umin:
4750 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4751 case Intrinsic::atomic_load_umax:
4752 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4753 case Intrinsic::atomic_swap:
4754 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4756 case Intrinsic::invariant_start:
4757 case Intrinsic::lifetime_start:
4758 // Discard region information.
4759 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4761 case Intrinsic::invariant_end:
4762 case Intrinsic::lifetime_end:
4763 // Discard region information.
4768 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
4770 MachineBasicBlock *LandingPad) {
4771 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4772 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4773 const Type *RetTy = FTy->getReturnType();
4774 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4775 MCSymbol *BeginLabel = 0;
4777 TargetLowering::ArgListTy Args;
4778 TargetLowering::ArgListEntry Entry;
4779 Args.reserve(CS.arg_size());
4781 // Check whether the function can return without sret-demotion.
4782 SmallVector<ISD::OutputArg, 4> Outs;
4783 SmallVector<uint64_t, 4> Offsets;
4784 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4785 Outs, TLI, &Offsets);
4787 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4788 FTy->isVarArg(), Outs, FTy->getContext());
4790 SDValue DemoteStackSlot;
4791 int DemoteStackIdx = -100;
4793 if (!CanLowerReturn) {
4794 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4795 FTy->getReturnType());
4796 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4797 FTy->getReturnType());
4798 MachineFunction &MF = DAG.getMachineFunction();
4799 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4800 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4802 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
4803 Entry.Node = DemoteStackSlot;
4804 Entry.Ty = StackSlotPtrType;
4805 Entry.isSExt = false;
4806 Entry.isZExt = false;
4807 Entry.isInReg = false;
4808 Entry.isSRet = true;
4809 Entry.isNest = false;
4810 Entry.isByVal = false;
4811 Entry.Alignment = Align;
4812 Args.push_back(Entry);
4813 RetTy = Type::getVoidTy(FTy->getContext());
4816 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4818 SDValue ArgNode = getValue(*i);
4819 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4821 unsigned attrInd = i - CS.arg_begin() + 1;
4822 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4823 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4824 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4825 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4826 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4827 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4828 Entry.Alignment = CS.getParamAlignment(attrInd);
4829 Args.push_back(Entry);
4833 // Insert a label before the invoke call to mark the try range. This can be
4834 // used to detect deletion of the invoke via the MachineModuleInfo.
4835 BeginLabel = MMI.getContext().CreateTempSymbol();
4837 // For SjLj, keep track of which landing pads go with which invokes
4838 // so as to maintain the ordering of pads in the LSDA.
4839 unsigned CallSiteIndex = MMI.getCurrentCallSite();
4840 if (CallSiteIndex) {
4841 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4842 // Now that the call site is handled, stop tracking it.
4843 MMI.setCurrentCallSite(0);
4846 // Both PendingLoads and PendingExports must be flushed here;
4847 // this call might not return.
4849 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
4852 // Check if target-independent constraints permit a tail call here.
4853 // Target-dependent constraints are checked within TLI.LowerCallTo.
4855 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4858 // If there's a possibility that fast-isel has already selected some amount
4859 // of the current basic block, don't emit a tail call.
4860 if (isTailCall && EnableFastISel)
4863 std::pair<SDValue,SDValue> Result =
4864 TLI.LowerCallTo(getRoot(), RetTy,
4865 CS.paramHasAttr(0, Attribute::SExt),
4866 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4867 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4868 CS.getCallingConv(),
4870 !CS.getInstruction()->use_empty(),
4871 Callee, Args, DAG, getCurDebugLoc());
4872 assert((isTailCall || Result.second.getNode()) &&
4873 "Non-null chain expected with non-tail call!");
4874 assert((Result.second.getNode() || !Result.first.getNode()) &&
4875 "Null value expected with tail call!");
4876 if (Result.first.getNode()) {
4877 setValue(CS.getInstruction(), Result.first);
4878 } else if (!CanLowerReturn && Result.second.getNode()) {
4879 // The instruction result is the result of loading from the
4880 // hidden sret parameter.
4881 SmallVector<EVT, 1> PVTs;
4882 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4884 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4885 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4886 EVT PtrVT = PVTs[0];
4887 unsigned NumValues = Outs.size();
4888 SmallVector<SDValue, 4> Values(NumValues);
4889 SmallVector<SDValue, 4> Chains(NumValues);
4891 for (unsigned i = 0; i < NumValues; ++i) {
4892 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4894 DAG.getConstant(Offsets[i], PtrVT));
4895 SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second,
4897 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
4900 Chains[i] = L.getValue(1);
4903 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4904 MVT::Other, &Chains[0], NumValues);
4905 PendingLoads.push_back(Chain);
4907 // Collect the legal value parts into potentially illegal values
4908 // that correspond to the original function's return values.
4909 SmallVector<EVT, 4> RetTys;
4910 RetTy = FTy->getReturnType();
4911 ComputeValueVTs(TLI, RetTy, RetTys);
4912 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4913 SmallVector<SDValue, 4> ReturnValues;
4914 unsigned CurReg = 0;
4915 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4917 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4918 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4920 SDValue ReturnValue =
4921 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
4922 RegisterVT, VT, AssertOp);
4923 ReturnValues.push_back(ReturnValue);
4927 setValue(CS.getInstruction(),
4928 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4929 DAG.getVTList(&RetTys[0], RetTys.size()),
4930 &ReturnValues[0], ReturnValues.size()));
4934 // As a special case, a null chain means that a tail call has been emitted and
4935 // the DAG root is already updated.
4936 if (Result.second.getNode())
4937 DAG.setRoot(Result.second);
4942 // Insert a label at the end of the invoke call to mark the try range. This
4943 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4944 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
4945 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
4947 // Inform MachineModuleInfo of range.
4948 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
4952 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4953 /// value is equal or not-equal to zero.
4954 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
4955 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
4957 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4958 if (IC->isEquality())
4959 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4960 if (C->isNullValue())
4962 // Unknown instruction.
4968 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
4970 SelectionDAGBuilder &Builder) {
4972 // Check to see if this load can be trivially constant folded, e.g. if the
4973 // input is from a string literal.
4974 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4975 // Cast pointer to the type we really want to load.
4976 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
4977 PointerType::getUnqual(LoadTy));
4979 if (const Constant *LoadCst =
4980 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
4982 return Builder.getValue(LoadCst);
4985 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4986 // still constant memory, the input chain can be the entry node.
4988 bool ConstantMemory = false;
4990 // Do not serialize (non-volatile) loads of constant memory with anything.
4991 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4992 Root = Builder.DAG.getEntryNode();
4993 ConstantMemory = true;
4995 // Do not serialize non-volatile loads against each other.
4996 Root = Builder.DAG.getRoot();
4999 SDValue Ptr = Builder.getValue(PtrVal);
5000 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
5001 Ptr, MachinePointerInfo(PtrVal),
5003 false /*nontemporal*/, 1 /* align=1 */);
5005 if (!ConstantMemory)
5006 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5011 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5012 /// If so, return true and lower it, otherwise return false and it will be
5013 /// lowered like a normal call.
5014 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5015 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5016 if (I.getNumArgOperands() != 3)
5019 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5020 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5021 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5022 !I.getType()->isIntegerTy())
5025 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
5027 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5028 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5029 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5030 bool ActuallyDoIt = true;
5033 switch (Size->getZExtValue()) {
5035 LoadVT = MVT::Other;
5037 ActuallyDoIt = false;
5041 LoadTy = Type::getInt16Ty(Size->getContext());
5045 LoadTy = Type::getInt32Ty(Size->getContext());
5049 LoadTy = Type::getInt64Ty(Size->getContext());
5053 LoadVT = MVT::v4i32;
5054 LoadTy = Type::getInt32Ty(Size->getContext());
5055 LoadTy = VectorType::get(LoadTy, 4);
5060 // This turns into unaligned loads. We only do this if the target natively
5061 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5062 // we'll only produce a small number of byte loads.
5064 // Require that we can find a legal MVT, and only do this if the target
5065 // supports unaligned loads of that type. Expanding into byte loads would
5067 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5068 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5069 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5070 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5071 ActuallyDoIt = false;
5075 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5076 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5078 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5080 EVT CallVT = TLI.getValueType(I.getType(), true);
5081 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5091 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5092 // Handle inline assembly differently.
5093 if (isa<InlineAsm>(I.getCalledValue())) {
5098 // See if any floating point values are being passed to this function. This is
5099 // used to emit an undefined reference to fltused on Windows.
5100 const FunctionType *FT =
5101 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
5102 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5103 if (FT->isVarArg() &&
5104 !MMI.callsExternalVAFunctionWithFloatingPointArguments()) {
5105 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
5106 const Type* T = I.getArgOperand(i)->getType();
5107 for (po_iterator<const Type*> i = po_begin(T), e = po_end(T);
5109 if (!i->isFloatingPointTy()) continue;
5110 MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true);
5116 const char *RenameFn = 0;
5117 if (Function *F = I.getCalledFunction()) {
5118 if (F->isDeclaration()) {
5119 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5120 if (unsigned IID = II->getIntrinsicID(F)) {
5121 RenameFn = visitIntrinsicCall(I, IID);
5126 if (unsigned IID = F->getIntrinsicID()) {
5127 RenameFn = visitIntrinsicCall(I, IID);
5133 // Check for well-known libc/libm calls. If the function is internal, it
5134 // can't be a library call.
5135 if (!F->hasLocalLinkage() && F->hasName()) {
5136 StringRef Name = F->getName();
5137 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
5138 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5139 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5140 I.getType() == I.getArgOperand(0)->getType() &&
5141 I.getType() == I.getArgOperand(1)->getType()) {
5142 SDValue LHS = getValue(I.getArgOperand(0));
5143 SDValue RHS = getValue(I.getArgOperand(1));
5144 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5145 LHS.getValueType(), LHS, RHS));
5148 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5149 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5150 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5151 I.getType() == I.getArgOperand(0)->getType()) {
5152 SDValue Tmp = getValue(I.getArgOperand(0));
5153 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
5154 Tmp.getValueType(), Tmp));
5157 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5158 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5159 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5160 I.getType() == I.getArgOperand(0)->getType() &&
5161 I.onlyReadsMemory()) {
5162 SDValue Tmp = getValue(I.getArgOperand(0));
5163 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5164 Tmp.getValueType(), Tmp));
5167 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5168 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5169 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5170 I.getType() == I.getArgOperand(0)->getType() &&
5171 I.onlyReadsMemory()) {
5172 SDValue Tmp = getValue(I.getArgOperand(0));
5173 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5174 Tmp.getValueType(), Tmp));
5177 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5178 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5179 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5180 I.getType() == I.getArgOperand(0)->getType() &&
5181 I.onlyReadsMemory()) {
5182 SDValue Tmp = getValue(I.getArgOperand(0));
5183 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5184 Tmp.getValueType(), Tmp));
5187 } else if (Name == "memcmp") {
5188 if (visitMemCmpCall(I))
5196 Callee = getValue(I.getCalledValue());
5198 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5200 // Check if we can potentially perform a tail call. More detailed checking is
5201 // be done within LowerCallTo, after more information about the call is known.
5202 LowerCallTo(&I, Callee, I.isTailCall());
5207 /// AsmOperandInfo - This contains information for each constraint that we are
5209 class LLVM_LIBRARY_VISIBILITY SDISelAsmOperandInfo :
5210 public TargetLowering::AsmOperandInfo {
5212 /// CallOperand - If this is the result output operand or a clobber
5213 /// this is null, otherwise it is the incoming operand to the CallInst.
5214 /// This gets modified as the asm is processed.
5215 SDValue CallOperand;
5217 /// AssignedRegs - If this is a register or register class operand, this
5218 /// contains the set of register corresponding to the operand.
5219 RegsForValue AssignedRegs;
5221 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5222 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5225 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5226 /// busy in OutputRegs/InputRegs.
5227 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5228 std::set<unsigned> &OutputRegs,
5229 std::set<unsigned> &InputRegs,
5230 const TargetRegisterInfo &TRI) const {
5232 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5233 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5236 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5237 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5241 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5242 /// corresponds to. If there is no Value* for this operand, it returns
5244 EVT getCallOperandValEVT(LLVMContext &Context,
5245 const TargetLowering &TLI,
5246 const TargetData *TD) const {
5247 if (CallOperandVal == 0) return MVT::Other;
5249 if (isa<BasicBlock>(CallOperandVal))
5250 return TLI.getPointerTy();
5252 const llvm::Type *OpTy = CallOperandVal->getType();
5254 // If this is an indirect operand, the operand is a pointer to the
5257 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5259 report_fatal_error("Indirect operand for inline asm not a pointer!");
5260 OpTy = PtrTy->getElementType();
5263 // If OpTy is not a single value, it may be a struct/union that we
5264 // can tile with integers.
5265 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5266 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5275 OpTy = IntegerType::get(Context, BitSize);
5280 return TLI.getValueType(OpTy, true);
5284 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5286 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5287 const TargetRegisterInfo &TRI) {
5288 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5290 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5291 for (; *Aliases; ++Aliases)
5292 Regs.insert(*Aliases);
5296 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5298 } // end llvm namespace.
5300 /// isAllocatableRegister - If the specified register is safe to allocate,
5301 /// i.e. it isn't a stack pointer or some other special register, return the
5302 /// register class for the register. Otherwise, return null.
5303 static const TargetRegisterClass *
5304 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5305 const TargetLowering &TLI,
5306 const TargetRegisterInfo *TRI) {
5307 EVT FoundVT = MVT::Other;
5308 const TargetRegisterClass *FoundRC = 0;
5309 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5310 E = TRI->regclass_end(); RCI != E; ++RCI) {
5311 EVT ThisVT = MVT::Other;
5313 const TargetRegisterClass *RC = *RCI;
5314 // If none of the value types for this register class are valid, we
5315 // can't use it. For example, 64-bit reg classes on 32-bit targets.
5316 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5318 if (TLI.isTypeLegal(*I)) {
5319 // If we have already found this register in a different register class,
5320 // choose the one with the largest VT specified. For example, on
5321 // PowerPC, we favor f64 register classes over f32.
5322 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5329 if (ThisVT == MVT::Other) continue;
5331 // NOTE: This isn't ideal. In particular, this might allocate the
5332 // frame pointer in functions that need it (due to them not being taken
5333 // out of allocation, because a variable sized allocation hasn't been seen
5334 // yet). This is a slight code pessimization, but should still work.
5335 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5336 E = RC->allocation_order_end(MF); I != E; ++I)
5338 // We found a matching register class. Keep looking at others in case
5339 // we find one with larger registers that this physreg is also in.
5348 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5349 /// specified operand. We prefer to assign virtual registers, to allow the
5350 /// register allocator to handle the assignment process. However, if the asm
5351 /// uses features that we can't model on machineinstrs, we have SDISel do the
5352 /// allocation. This produces generally horrible, but correct, code.
5354 /// OpInfo describes the operand.
5355 /// Input and OutputRegs are the set of already allocated physical registers.
5357 void SelectionDAGBuilder::
5358 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5359 std::set<unsigned> &OutputRegs,
5360 std::set<unsigned> &InputRegs) {
5361 LLVMContext &Context = FuncInfo.Fn->getContext();
5363 // Compute whether this value requires an input register, an output register,
5365 bool isOutReg = false;
5366 bool isInReg = false;
5367 switch (OpInfo.Type) {
5368 case InlineAsm::isOutput:
5371 // If there is an input constraint that matches this, we need to reserve
5372 // the input register so no other inputs allocate to it.
5373 isInReg = OpInfo.hasMatchingInput();
5375 case InlineAsm::isInput:
5379 case InlineAsm::isClobber:
5386 MachineFunction &MF = DAG.getMachineFunction();
5387 SmallVector<unsigned, 4> Regs;
5389 // If this is a constraint for a single physreg, or a constraint for a
5390 // register class, find it.
5391 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5392 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5393 OpInfo.ConstraintVT);
5395 unsigned NumRegs = 1;
5396 if (OpInfo.ConstraintVT != MVT::Other) {
5397 // If this is a FP input in an integer register (or visa versa) insert a bit
5398 // cast of the input value. More generally, handle any case where the input
5399 // value disagrees with the register class we plan to stick this in.
5400 if (OpInfo.Type == InlineAsm::isInput &&
5401 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5402 // Try to convert to the first EVT that the reg class contains. If the
5403 // types are identical size, use a bitcast to convert (e.g. two differing
5405 EVT RegVT = *PhysReg.second->vt_begin();
5406 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5407 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
5408 RegVT, OpInfo.CallOperand);
5409 OpInfo.ConstraintVT = RegVT;
5410 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5411 // If the input is a FP value and we want it in FP registers, do a
5412 // bitcast to the corresponding integer type. This turns an f64 value
5413 // into i64, which can be passed with two i32 values on a 32-bit
5415 RegVT = EVT::getIntegerVT(Context,
5416 OpInfo.ConstraintVT.getSizeInBits());
5417 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
5418 RegVT, OpInfo.CallOperand);
5419 OpInfo.ConstraintVT = RegVT;
5423 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5427 EVT ValueVT = OpInfo.ConstraintVT;
5429 // If this is a constraint for a specific physical register, like {r17},
5431 if (unsigned AssignedReg = PhysReg.first) {
5432 const TargetRegisterClass *RC = PhysReg.second;
5433 if (OpInfo.ConstraintVT == MVT::Other)
5434 ValueVT = *RC->vt_begin();
5436 // Get the actual register value type. This is important, because the user
5437 // may have asked for (e.g.) the AX register in i32 type. We need to
5438 // remember that AX is actually i16 to get the right extension.
5439 RegVT = *RC->vt_begin();
5441 // This is a explicit reference to a physical register.
5442 Regs.push_back(AssignedReg);
5444 // If this is an expanded reference, add the rest of the regs to Regs.
5446 TargetRegisterClass::iterator I = RC->begin();
5447 for (; *I != AssignedReg; ++I)
5448 assert(I != RC->end() && "Didn't find reg!");
5450 // Already added the first reg.
5452 for (; NumRegs; --NumRegs, ++I) {
5453 assert(I != RC->end() && "Ran out of registers to allocate!");
5458 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5459 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5460 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5464 // Otherwise, if this was a reference to an LLVM register class, create vregs
5465 // for this reference.
5466 if (const TargetRegisterClass *RC = PhysReg.second) {
5467 RegVT = *RC->vt_begin();
5468 if (OpInfo.ConstraintVT == MVT::Other)
5471 // Create the appropriate number of virtual registers.
5472 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5473 for (; NumRegs; --NumRegs)
5474 Regs.push_back(RegInfo.createVirtualRegister(RC));
5476 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5480 // This is a reference to a register class that doesn't directly correspond
5481 // to an LLVM register class. Allocate NumRegs consecutive, available,
5482 // registers from the class.
5483 std::vector<unsigned> RegClassRegs
5484 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5485 OpInfo.ConstraintVT);
5487 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5488 unsigned NumAllocated = 0;
5489 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5490 unsigned Reg = RegClassRegs[i];
5491 // See if this register is available.
5492 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5493 (isInReg && InputRegs.count(Reg))) { // Already used.
5494 // Make sure we find consecutive registers.
5499 // Check to see if this register is allocatable (i.e. don't give out the
5501 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5502 if (!RC) { // Couldn't allocate this register.
5503 // Reset NumAllocated to make sure we return consecutive registers.
5508 // Okay, this register is good, we can use it.
5511 // If we allocated enough consecutive registers, succeed.
5512 if (NumAllocated == NumRegs) {
5513 unsigned RegStart = (i-NumAllocated)+1;
5514 unsigned RegEnd = i+1;
5515 // Mark all of the allocated registers used.
5516 for (unsigned i = RegStart; i != RegEnd; ++i)
5517 Regs.push_back(RegClassRegs[i]);
5519 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
5520 OpInfo.ConstraintVT);
5521 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5526 // Otherwise, we couldn't allocate enough registers for this.
5529 /// visitInlineAsm - Handle a call to an InlineAsm object.
5531 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5532 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5534 /// ConstraintOperands - Information about all of the constraints.
5535 SDISelAsmOperandInfoVector ConstraintOperands;
5537 std::set<unsigned> OutputRegs, InputRegs;
5539 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(CS);
5540 bool hasMemory = false;
5542 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5543 unsigned ResNo = 0; // ResNo - The result number of the next output.
5544 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5545 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
5546 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5548 EVT OpVT = MVT::Other;
5550 // Compute the value type for each operand.
5551 switch (OpInfo.Type) {
5552 case InlineAsm::isOutput:
5553 // Indirect outputs just consume an argument.
5554 if (OpInfo.isIndirect) {
5555 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5559 // The return value of the call is this value. As such, there is no
5560 // corresponding argument.
5561 assert(!CS.getType()->isVoidTy() &&
5563 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5564 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5566 assert(ResNo == 0 && "Asm only has one result!");
5567 OpVT = TLI.getValueType(CS.getType());
5571 case InlineAsm::isInput:
5572 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5574 case InlineAsm::isClobber:
5579 // If this is an input or an indirect output, process the call argument.
5580 // BasicBlocks are labels, currently appearing only in asm's.
5581 if (OpInfo.CallOperandVal) {
5582 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5583 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5585 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5588 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5591 OpInfo.ConstraintVT = OpVT;
5593 // Indirect operand accesses access memory.
5594 if (OpInfo.isIndirect)
5597 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
5598 TargetLowering::ConstraintType CType = TLI.getConstraintType(OpInfo.Codes[j]);
5599 if (CType == TargetLowering::C_Memory) {
5607 SDValue Chain, Flag;
5609 // We won't need to flush pending loads if this asm doesn't touch
5610 // memory and is nonvolatile.
5611 if (hasMemory || IA->hasSideEffects())
5614 Chain = DAG.getRoot();
5616 // Second pass over the constraints: compute which constraint option to use
5617 // and assign registers to constraints that want a specific physreg.
5618 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5619 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5621 // If this is an output operand with a matching input operand, look up the
5622 // matching input. If their types mismatch, e.g. one is an integer, the
5623 // other is floating point, or their sizes are different, flag it as an
5625 if (OpInfo.hasMatchingInput()) {
5626 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5628 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5629 if ((OpInfo.ConstraintVT.isInteger() !=
5630 Input.ConstraintVT.isInteger()) ||
5631 (OpInfo.ConstraintVT.getSizeInBits() !=
5632 Input.ConstraintVT.getSizeInBits())) {
5633 report_fatal_error("Unsupported asm: input constraint"
5634 " with a matching output constraint of"
5635 " incompatible type!");
5637 Input.ConstraintVT = OpInfo.ConstraintVT;
5641 // Compute the constraint code and ConstraintType to use.
5642 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5644 // If this is a memory input, and if the operand is not indirect, do what we
5645 // need to to provide an address for the memory input.
5646 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5647 !OpInfo.isIndirect) {
5648 assert((OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::isInput)) &&
5649 "Can only indirectify direct input operands!");
5651 // Memory operands really want the address of the value. If we don't have
5652 // an indirect input, put it in the constpool if we can, otherwise spill
5653 // it to a stack slot.
5655 // If the operand is a float, integer, or vector constant, spill to a
5656 // constant pool entry to get its address.
5657 const Value *OpVal = OpInfo.CallOperandVal;
5658 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5659 isa<ConstantVector>(OpVal)) {
5660 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5661 TLI.getPointerTy());
5663 // Otherwise, create a stack slot and emit a store to it before the
5665 const Type *Ty = OpVal->getType();
5666 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5667 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5668 MachineFunction &MF = DAG.getMachineFunction();
5669 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5670 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5671 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5672 OpInfo.CallOperand, StackSlot,
5673 MachinePointerInfo::getFixedStack(SSFI),
5675 OpInfo.CallOperand = StackSlot;
5678 // There is no longer a Value* corresponding to this operand.
5679 OpInfo.CallOperandVal = 0;
5681 // It is now an indirect operand.
5682 OpInfo.isIndirect = true;
5685 // If this constraint is for a specific register, allocate it before
5687 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5688 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5691 // Second pass - Loop over all of the operands, assigning virtual or physregs
5692 // to register class operands.
5693 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5694 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5696 // C_Register operands have already been allocated, Other/Memory don't need
5698 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5699 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5702 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5703 std::vector<SDValue> AsmNodeOperands;
5704 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5705 AsmNodeOperands.push_back(
5706 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5707 TLI.getPointerTy()));
5709 // If we have a !srcloc metadata node associated with it, we want to attach
5710 // this to the ultimately generated inline asm machineinstr. To do this, we
5711 // pass in the third operand as this (potentially null) inline asm MDNode.
5712 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
5713 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
5715 // Remember the HasSideEffect and AlignStack bits as operand 3.
5716 unsigned ExtraInfo = 0;
5717 if (IA->hasSideEffects())
5718 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
5719 if (IA->isAlignStack())
5720 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
5721 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
5722 TLI.getPointerTy()));
5724 // Loop over all of the inputs, copying the operand values into the
5725 // appropriate registers and processing the output regs.
5726 RegsForValue RetValRegs;
5728 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5729 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5731 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5732 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5734 switch (OpInfo.Type) {
5735 case InlineAsm::isOutput: {
5736 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5737 OpInfo.ConstraintType != TargetLowering::C_Register) {
5738 // Memory output, or 'other' output (e.g. 'X' constraint).
5739 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5741 // Add information to the INLINEASM node to know about this output.
5742 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5743 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
5744 TLI.getPointerTy()));
5745 AsmNodeOperands.push_back(OpInfo.CallOperand);
5749 // Otherwise, this is a register or register class output.
5751 // Copy the output from the appropriate register. Find a register that
5753 if (OpInfo.AssignedRegs.Regs.empty())
5754 report_fatal_error("Couldn't allocate output reg for constraint '" +
5755 Twine(OpInfo.ConstraintCode) + "'!");
5757 // If this is an indirect operand, store through the pointer after the
5759 if (OpInfo.isIndirect) {
5760 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5761 OpInfo.CallOperandVal));
5763 // This is the result value of the call.
5764 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5765 // Concatenate this output onto the outputs list.
5766 RetValRegs.append(OpInfo.AssignedRegs);
5769 // Add information to the INLINEASM node to know that this register is
5771 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5772 InlineAsm::Kind_RegDefEarlyClobber :
5773 InlineAsm::Kind_RegDef,
5780 case InlineAsm::isInput: {
5781 SDValue InOperandVal = OpInfo.CallOperand;
5783 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5784 // If this is required to match an output register we have already set,
5785 // just use its register.
5786 unsigned OperandNo = OpInfo.getMatchedOperand();
5788 // Scan until we find the definition we already emitted of this operand.
5789 // When we find it, create a RegsForValue operand.
5790 unsigned CurOp = InlineAsm::Op_FirstOperand;
5791 for (; OperandNo; --OperandNo) {
5792 // Advance to the next operand.
5794 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5795 assert((InlineAsm::isRegDefKind(OpFlag) ||
5796 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
5797 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
5798 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5802 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5803 if (InlineAsm::isRegDefKind(OpFlag) ||
5804 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
5805 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5806 if (OpInfo.isIndirect) {
5807 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
5808 LLVMContext &Ctx = *DAG.getContext();
5809 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
5810 " don't know how to handle tied "
5811 "indirect register inputs");
5814 RegsForValue MatchedRegs;
5815 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5816 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5817 MatchedRegs.RegVTs.push_back(RegVT);
5818 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5819 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5821 MatchedRegs.Regs.push_back
5822 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5824 // Use the produced MatchedRegs object to
5825 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5827 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
5828 true, OpInfo.getMatchedOperand(),
5829 DAG, AsmNodeOperands);
5833 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
5834 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
5835 "Unexpected number of operands");
5836 // Add information to the INLINEASM node to know about this input.
5837 // See InlineAsm.h isUseOperandTiedToDef.
5838 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
5839 OpInfo.getMatchedOperand());
5840 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5841 TLI.getPointerTy()));
5842 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5846 // Treat indirect 'X' constraint as memory.
5847 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
5849 OpInfo.ConstraintType = TargetLowering::C_Memory;
5851 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5852 std::vector<SDValue> Ops;
5853 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5856 report_fatal_error("Invalid operand for inline asm constraint '" +
5857 Twine(OpInfo.ConstraintCode) + "'!");
5859 // Add information to the INLINEASM node to know about this input.
5860 unsigned ResOpType =
5861 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
5862 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5863 TLI.getPointerTy()));
5864 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5868 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5869 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5870 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5871 "Memory operands expect pointer values");
5873 // Add information to the INLINEASM node to know about this input.
5874 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5875 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5876 TLI.getPointerTy()));
5877 AsmNodeOperands.push_back(InOperandVal);
5881 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5882 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5883 "Unknown constraint type!");
5884 assert(!OpInfo.isIndirect &&
5885 "Don't know how to handle indirect register inputs yet!");
5887 // Copy the input into the appropriate registers.
5888 if (OpInfo.AssignedRegs.Regs.empty() ||
5889 !OpInfo.AssignedRegs.areValueTypesLegal(TLI))
5890 report_fatal_error("Couldn't allocate input reg for constraint '" +
5891 Twine(OpInfo.ConstraintCode) + "'!");
5893 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5896 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
5897 DAG, AsmNodeOperands);
5900 case InlineAsm::isClobber: {
5901 // Add the clobbered value to the operand list, so that the register
5902 // allocator is aware that the physreg got clobbered.
5903 if (!OpInfo.AssignedRegs.Regs.empty())
5904 OpInfo.AssignedRegs.AddInlineAsmOperands(
5905 InlineAsm::Kind_RegDefEarlyClobber,
5913 // Finish up input operands. Set the input chain and add the flag last.
5914 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
5915 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5917 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5918 DAG.getVTList(MVT::Other, MVT::Glue),
5919 &AsmNodeOperands[0], AsmNodeOperands.size());
5920 Flag = Chain.getValue(1);
5922 // If this asm returns a register value, copy the result from that register
5923 // and set it as the value of the call.
5924 if (!RetValRegs.Regs.empty()) {
5925 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
5928 // FIXME: Why don't we do this for inline asms with MRVs?
5929 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5930 EVT ResultType = TLI.getValueType(CS.getType());
5932 // If any of the results of the inline asm is a vector, it may have the
5933 // wrong width/num elts. This can happen for register classes that can
5934 // contain multiple different value types. The preg or vreg allocated may
5935 // not have the same VT as was expected. Convert it to the right type
5936 // with bit_convert.
5937 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5938 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
5941 } else if (ResultType != Val.getValueType() &&
5942 ResultType.isInteger() && Val.getValueType().isInteger()) {
5943 // If a result value was tied to an input value, the computed result may
5944 // have a wider width than the expected result. Extract the relevant
5946 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5949 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5952 setValue(CS.getInstruction(), Val);
5953 // Don't need to use this as a chain in this case.
5954 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5958 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
5960 // Process indirect outputs, first output all of the flagged copies out of
5962 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5963 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5964 const Value *Ptr = IndirectStoresToEmit[i].second;
5965 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
5967 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5970 // Emit the non-flagged stores from the physregs.
5971 SmallVector<SDValue, 8> OutChains;
5972 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5973 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5974 StoresToEmit[i].first,
5975 getValue(StoresToEmit[i].second),
5976 MachinePointerInfo(StoresToEmit[i].second),
5978 OutChains.push_back(Val);
5981 if (!OutChains.empty())
5982 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5983 &OutChains[0], OutChains.size());
5988 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
5989 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5990 MVT::Other, getRoot(),
5991 getValue(I.getArgOperand(0)),
5992 DAG.getSrcValue(I.getArgOperand(0))));
5995 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
5996 const TargetData &TD = *TLI.getTargetData();
5997 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5998 getRoot(), getValue(I.getOperand(0)),
5999 DAG.getSrcValue(I.getOperand(0)),
6000 TD.getABITypeAlignment(I.getType()));
6002 DAG.setRoot(V.getValue(1));
6005 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6006 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6007 MVT::Other, getRoot(),
6008 getValue(I.getArgOperand(0)),
6009 DAG.getSrcValue(I.getArgOperand(0))));
6012 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6013 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6014 MVT::Other, getRoot(),
6015 getValue(I.getArgOperand(0)),
6016 getValue(I.getArgOperand(1)),
6017 DAG.getSrcValue(I.getArgOperand(0)),
6018 DAG.getSrcValue(I.getArgOperand(1))));
6021 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6022 /// implementation, which just calls LowerCall.
6023 /// FIXME: When all targets are
6024 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6025 std::pair<SDValue, SDValue>
6026 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
6027 bool RetSExt, bool RetZExt, bool isVarArg,
6028 bool isInreg, unsigned NumFixedArgs,
6029 CallingConv::ID CallConv, bool isTailCall,
6030 bool isReturnValueUsed,
6032 ArgListTy &Args, SelectionDAG &DAG,
6033 DebugLoc dl) const {
6034 // Handle all of the outgoing arguments.
6035 SmallVector<ISD::OutputArg, 32> Outs;
6036 SmallVector<SDValue, 32> OutVals;
6037 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6038 SmallVector<EVT, 4> ValueVTs;
6039 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6040 for (unsigned Value = 0, NumValues = ValueVTs.size();
6041 Value != NumValues; ++Value) {
6042 EVT VT = ValueVTs[Value];
6043 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6044 SDValue Op = SDValue(Args[i].Node.getNode(),
6045 Args[i].Node.getResNo() + Value);
6046 ISD::ArgFlagsTy Flags;
6047 unsigned OriginalAlignment =
6048 getTargetData()->getABITypeAlignment(ArgTy);
6054 if (Args[i].isInReg)
6058 if (Args[i].isByVal) {
6060 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
6061 const Type *ElementTy = Ty->getElementType();
6062 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
6063 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
6064 // For ByVal, alignment should come from FE. BE will guess if this
6065 // info is not there but there are cases it cannot get right.
6066 if (Args[i].Alignment)
6067 FrameAlign = Args[i].Alignment;
6068 Flags.setByValAlign(FrameAlign);
6069 Flags.setByValSize(FrameSize);
6073 Flags.setOrigAlign(OriginalAlignment);
6075 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6076 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6077 SmallVector<SDValue, 4> Parts(NumParts);
6078 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6081 ExtendKind = ISD::SIGN_EXTEND;
6082 else if (Args[i].isZExt)
6083 ExtendKind = ISD::ZERO_EXTEND;
6085 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
6086 PartVT, ExtendKind);
6088 for (unsigned j = 0; j != NumParts; ++j) {
6089 // if it isn't first piece, alignment must be 1
6090 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
6092 if (NumParts > 1 && j == 0)
6093 MyFlags.Flags.setSplit();
6095 MyFlags.Flags.setOrigAlign(1);
6097 Outs.push_back(MyFlags);
6098 OutVals.push_back(Parts[j]);
6103 // Handle the incoming return values from the call.
6104 SmallVector<ISD::InputArg, 32> Ins;
6105 SmallVector<EVT, 4> RetTys;
6106 ComputeValueVTs(*this, RetTy, RetTys);
6107 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6109 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6110 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6111 for (unsigned i = 0; i != NumRegs; ++i) {
6112 ISD::InputArg MyFlags;
6113 MyFlags.VT = RegisterVT.getSimpleVT();
6114 MyFlags.Used = isReturnValueUsed;
6116 MyFlags.Flags.setSExt();
6118 MyFlags.Flags.setZExt();
6120 MyFlags.Flags.setInReg();
6121 Ins.push_back(MyFlags);
6125 SmallVector<SDValue, 4> InVals;
6126 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6127 Outs, OutVals, Ins, dl, DAG, InVals);
6129 // Verify that the target's LowerCall behaved as expected.
6130 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6131 "LowerCall didn't return a valid chain!");
6132 assert((!isTailCall || InVals.empty()) &&
6133 "LowerCall emitted a return value for a tail call!");
6134 assert((isTailCall || InVals.size() == Ins.size()) &&
6135 "LowerCall didn't emit the correct number of values!");
6137 // For a tail call, the return value is merely live-out and there aren't
6138 // any nodes in the DAG representing it. Return a special value to
6139 // indicate that a tail call has been emitted and no more Instructions
6140 // should be processed in the current block.
6143 return std::make_pair(SDValue(), SDValue());
6146 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6147 assert(InVals[i].getNode() &&
6148 "LowerCall emitted a null value!");
6149 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6150 "LowerCall emitted a value with the wrong type!");
6153 // Collect the legal value parts into potentially illegal values
6154 // that correspond to the original function's return values.
6155 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6157 AssertOp = ISD::AssertSext;
6159 AssertOp = ISD::AssertZext;
6160 SmallVector<SDValue, 4> ReturnValues;
6161 unsigned CurReg = 0;
6162 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6164 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6165 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6167 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
6168 NumRegs, RegisterVT, VT,
6173 // For a function returning void, there is no return value. We can't create
6174 // such a node, so we just return a null return value in that case. In
6175 // that case, nothing will actualy look at the value.
6176 if (ReturnValues.empty())
6177 return std::make_pair(SDValue(), Chain);
6179 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6180 DAG.getVTList(&RetTys[0], RetTys.size()),
6181 &ReturnValues[0], ReturnValues.size());
6182 return std::make_pair(Res, Chain);
6185 void TargetLowering::LowerOperationWrapper(SDNode *N,
6186 SmallVectorImpl<SDValue> &Results,
6187 SelectionDAG &DAG) const {
6188 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6190 Results.push_back(Res);
6193 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6194 llvm_unreachable("LowerOperation not implemented for this target!");
6199 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
6200 SDValue Op = getNonRegisterValue(V);
6201 assert((Op.getOpcode() != ISD::CopyFromReg ||
6202 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6203 "Copy from a reg to the same reg!");
6204 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6206 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6207 SDValue Chain = DAG.getEntryNode();
6208 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
6209 PendingExports.push_back(Chain);
6212 #include "llvm/CodeGen/SelectionDAGISel.h"
6214 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
6215 // If this is the entry block, emit arguments.
6216 const Function &F = *LLVMBB->getParent();
6217 SelectionDAG &DAG = SDB->DAG;
6218 DebugLoc dl = SDB->getCurDebugLoc();
6219 const TargetData *TD = TLI.getTargetData();
6220 SmallVector<ISD::InputArg, 16> Ins;
6222 // Check whether the function can return without sret-demotion.
6223 SmallVector<ISD::OutputArg, 4> Outs;
6224 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6227 if (!FuncInfo->CanLowerReturn) {
6228 // Put in an sret pointer parameter before all the other parameters.
6229 SmallVector<EVT, 1> ValueVTs;
6230 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6232 // NOTE: Assuming that a pointer will never break down to more than one VT
6234 ISD::ArgFlagsTy Flags;
6236 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
6237 ISD::InputArg RetArg(Flags, RegisterVT, true);
6238 Ins.push_back(RetArg);
6241 // Set up the incoming argument description vector.
6243 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
6244 I != E; ++I, ++Idx) {
6245 SmallVector<EVT, 4> ValueVTs;
6246 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6247 bool isArgValueUsed = !I->use_empty();
6248 for (unsigned Value = 0, NumValues = ValueVTs.size();
6249 Value != NumValues; ++Value) {
6250 EVT VT = ValueVTs[Value];
6251 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6252 ISD::ArgFlagsTy Flags;
6253 unsigned OriginalAlignment =
6254 TD->getABITypeAlignment(ArgTy);
6256 if (F.paramHasAttr(Idx, Attribute::ZExt))
6258 if (F.paramHasAttr(Idx, Attribute::SExt))
6260 if (F.paramHasAttr(Idx, Attribute::InReg))
6262 if (F.paramHasAttr(Idx, Attribute::StructRet))
6264 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6266 const PointerType *Ty = cast<PointerType>(I->getType());
6267 const Type *ElementTy = Ty->getElementType();
6268 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6269 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
6270 // For ByVal, alignment should be passed from FE. BE will guess if
6271 // this info is not there but there are cases it cannot get right.
6272 if (F.getParamAlignment(Idx))
6273 FrameAlign = F.getParamAlignment(Idx);
6274 Flags.setByValAlign(FrameAlign);
6275 Flags.setByValSize(FrameSize);
6277 if (F.paramHasAttr(Idx, Attribute::Nest))
6279 Flags.setOrigAlign(OriginalAlignment);
6281 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6282 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6283 for (unsigned i = 0; i != NumRegs; ++i) {
6284 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6285 if (NumRegs > 1 && i == 0)
6286 MyFlags.Flags.setSplit();
6287 // if it isn't first piece, alignment must be 1
6289 MyFlags.Flags.setOrigAlign(1);
6290 Ins.push_back(MyFlags);
6295 // Call the target to set up the argument values.
6296 SmallVector<SDValue, 8> InVals;
6297 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6301 // Verify that the target's LowerFormalArguments behaved as expected.
6302 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6303 "LowerFormalArguments didn't return a valid chain!");
6304 assert(InVals.size() == Ins.size() &&
6305 "LowerFormalArguments didn't emit the correct number of values!");
6307 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6308 assert(InVals[i].getNode() &&
6309 "LowerFormalArguments emitted a null value!");
6310 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6311 "LowerFormalArguments emitted a value with the wrong type!");
6315 // Update the DAG with the new chain value resulting from argument lowering.
6316 DAG.setRoot(NewRoot);
6318 // Set up the argument values.
6321 if (!FuncInfo->CanLowerReturn) {
6322 // Create a virtual register for the sret pointer, and put in a copy
6323 // from the sret argument into it.
6324 SmallVector<EVT, 1> ValueVTs;
6325 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6326 EVT VT = ValueVTs[0];
6327 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6328 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6329 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6330 RegVT, VT, AssertOp);
6332 MachineFunction& MF = SDB->DAG.getMachineFunction();
6333 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6334 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6335 FuncInfo->DemoteRegister = SRetReg;
6336 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6338 DAG.setRoot(NewRoot);
6340 // i indexes lowered arguments. Bump it past the hidden sret argument.
6341 // Idx indexes LLVM arguments. Don't touch it.
6345 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6347 SmallVector<SDValue, 4> ArgValues;
6348 SmallVector<EVT, 4> ValueVTs;
6349 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6350 unsigned NumValues = ValueVTs.size();
6352 // If this argument is unused then remember its value. It is used to generate
6353 // debugging information.
6354 if (I->use_empty() && NumValues)
6355 SDB->setUnusedArgValue(I, InVals[i]);
6357 for (unsigned Value = 0; Value != NumValues; ++Value) {
6358 EVT VT = ValueVTs[Value];
6359 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6360 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6362 if (!I->use_empty()) {
6363 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6364 if (F.paramHasAttr(Idx, Attribute::SExt))
6365 AssertOp = ISD::AssertSext;
6366 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6367 AssertOp = ISD::AssertZext;
6369 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6370 NumParts, PartVT, VT,
6377 // Note down frame index for byval arguments.
6378 if (I->hasByValAttr() && !ArgValues.empty())
6379 if (FrameIndexSDNode *FI =
6380 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
6381 FuncInfo->setByValArgumentFrameIndex(I, FI->getIndex());
6383 if (!I->use_empty()) {
6385 if (!ArgValues.empty())
6386 Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6387 SDB->getCurDebugLoc());
6388 SDB->setValue(I, Res);
6390 // If this argument is live outside of the entry block, insert a copy from
6391 // whereever we got it to the vreg that other BB's will reference it as.
6392 SDB->CopyToExportRegsIfNeeded(I);
6396 assert(i == InVals.size() && "Argument register count mismatch!");
6398 // Finally, if the target has anything special to do, allow it to do so.
6399 // FIXME: this should insert code into the DAG!
6400 EmitFunctionEntryCode();
6403 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6404 /// ensure constants are generated when needed. Remember the virtual registers
6405 /// that need to be added to the Machine PHI nodes as input. We cannot just
6406 /// directly add them, because expansion might result in multiple MBB's for one
6407 /// BB. As such, the start of the BB might correspond to a different MBB than
6411 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6412 const TerminatorInst *TI = LLVMBB->getTerminator();
6414 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6416 // Check successor nodes' PHI nodes that expect a constant to be available
6418 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6419 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6420 if (!isa<PHINode>(SuccBB->begin())) continue;
6421 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
6423 // If this terminator has multiple identical successors (common for
6424 // switches), only handle each succ once.
6425 if (!SuccsHandled.insert(SuccMBB)) continue;
6427 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6429 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6430 // nodes and Machine PHI nodes, but the incoming operands have not been
6432 for (BasicBlock::const_iterator I = SuccBB->begin();
6433 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6434 // Ignore dead phi's.
6435 if (PN->use_empty()) continue;
6438 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6440 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6441 unsigned &RegOut = ConstantsOut[C];
6443 RegOut = FuncInfo.CreateRegs(C->getType());
6444 CopyValueToVirtualRegister(C, RegOut);
6448 DenseMap<const Value *, unsigned>::iterator I =
6449 FuncInfo.ValueMap.find(PHIOp);
6450 if (I != FuncInfo.ValueMap.end())
6453 assert(isa<AllocaInst>(PHIOp) &&
6454 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6455 "Didn't codegen value into a register!??");
6456 Reg = FuncInfo.CreateRegs(PHIOp->getType());
6457 CopyValueToVirtualRegister(PHIOp, Reg);
6461 // Remember that this register needs to added to the machine PHI node as
6462 // the input for this MBB.
6463 SmallVector<EVT, 4> ValueVTs;
6464 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6465 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6466 EVT VT = ValueVTs[vti];
6467 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6468 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6469 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6470 Reg += NumRegisters;
6474 ConstantsOut.clear();