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 "SelectionDAGBuilder.h"
16 #include "FunctionLoweringInfo.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Constants.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/Module.h"
31 #include "llvm/CodeGen/FastISel.h"
32 #include "llvm/CodeGen/GCStrategy.h"
33 #include "llvm/CodeGen/GCMetadata.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineJumpTableInfo.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/PseudoSourceValue.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/DwarfWriter.h"
43 #include "llvm/Analysis/DebugInfo.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetFrameInfo.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetIntrinsicInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
60 /// LimitFloatPrecision - Generate low-precision inline sequences for
61 /// some float libcalls (6, 8 or 12 bits).
62 static unsigned LimitFloatPrecision;
64 static cl::opt<unsigned, true>
65 LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
72 /// RegsForValue - This struct represents the registers (physical or virtual)
73 /// that a particular set of values is assigned, and the type information about
74 /// the value. The most common situation is to represent one value at a time,
75 /// but struct or array values are handled element-wise as multiple values.
76 /// The splitting of aggregates is performed recursively, so that we never
77 /// have aggregate-typed registers. The values at this point do not necessarily
78 /// have legal types, so each value may require one or more registers of some
82 /// TLI - The TargetLowering object.
84 const TargetLowering *TLI;
86 /// ValueVTs - The value types of the values, which may not be legal, and
87 /// may need be promoted or synthesized from one or more registers.
89 SmallVector<EVT, 4> ValueVTs;
91 /// RegVTs - The value types of the registers. This is the same size as
92 /// ValueVTs and it records, for each value, what the type of the assigned
93 /// register or registers are. (Individual values are never synthesized
94 /// from more than one type of register.)
96 /// With virtual registers, the contents of RegVTs is redundant with TLI's
97 /// getRegisterType member function, however when with physical registers
98 /// it is necessary to have a separate record of the types.
100 SmallVector<EVT, 4> RegVTs;
102 /// Regs - This list holds the registers assigned to the values.
103 /// Each legal or promoted value requires one register, and each
104 /// expanded value requires multiple registers.
106 SmallVector<unsigned, 4> Regs;
108 RegsForValue() : TLI(0) {}
110 RegsForValue(const TargetLowering &tli,
111 const SmallVector<unsigned, 4> ®s,
112 EVT regvt, EVT valuevt)
113 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
114 RegsForValue(const TargetLowering &tli,
115 const SmallVector<unsigned, 4> ®s,
116 const SmallVector<EVT, 4> ®vts,
117 const SmallVector<EVT, 4> &valuevts)
118 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
119 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
120 unsigned Reg, const Type *Ty) : TLI(&tli) {
121 ComputeValueVTs(tli, Ty, ValueVTs);
123 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
124 EVT ValueVT = ValueVTs[Value];
125 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
126 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
127 for (unsigned i = 0; i != NumRegs; ++i)
128 Regs.push_back(Reg + i);
129 RegVTs.push_back(RegisterVT);
134 /// append - Add the specified values to this one.
135 void append(const RegsForValue &RHS) {
137 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
138 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
139 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
143 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
144 /// this value and returns the result as a ValueVTs value. This uses
145 /// Chain/Flag as the input and updates them for the output Chain/Flag.
146 /// If the Flag pointer is NULL, no flag is used.
147 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
148 SDValue &Chain, SDValue *Flag) const;
150 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
151 /// specified value into the registers specified by this object. This uses
152 /// Chain/Flag as the input and updates them for the output Chain/Flag.
153 /// If the Flag pointer is NULL, no flag is used.
154 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
155 unsigned Order, SDValue &Chain, SDValue *Flag) const;
157 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
158 /// operand list. This adds the code marker, matching input operand index
159 /// (if applicable), and includes the number of values added into it.
160 void AddInlineAsmOperands(unsigned Code,
161 bool HasMatching, unsigned MatchingIdx,
162 SelectionDAG &DAG, unsigned Order,
163 std::vector<SDValue> &Ops) const;
167 /// getCopyFromParts - Create a value that contains the specified legal parts
168 /// combined into the value they represent. If the parts combine to a type
169 /// larger then ValueVT then AssertOp can be used to specify whether the extra
170 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
171 /// (ISD::AssertSext).
172 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
173 const SDValue *Parts,
174 unsigned NumParts, EVT PartVT, EVT ValueVT,
175 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
176 assert(NumParts > 0 && "No parts to assemble!");
177 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
178 SDValue Val = Parts[0];
179 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
182 // Assemble the value from multiple parts.
183 if (!ValueVT.isVector() && ValueVT.isInteger()) {
184 unsigned PartBits = PartVT.getSizeInBits();
185 unsigned ValueBits = ValueVT.getSizeInBits();
187 // Assemble the power of 2 part.
188 unsigned RoundParts = NumParts & (NumParts - 1) ?
189 1 << Log2_32(NumParts) : NumParts;
190 unsigned RoundBits = PartBits * RoundParts;
191 EVT RoundVT = RoundBits == ValueBits ?
192 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
197 if (RoundParts > 2) {
198 Lo = getCopyFromParts(DAG, dl, Order, Parts, RoundParts / 2,
200 Hi = getCopyFromParts(DAG, dl, Order, Parts + RoundParts / 2,
201 RoundParts / 2, PartVT, HalfVT);
203 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
204 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
207 if (TLI.isBigEndian())
210 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
212 if (DisableScheduling) {
213 DAG.AssignOrdering(Lo.getNode(), Order);
214 DAG.AssignOrdering(Hi.getNode(), Order);
215 DAG.AssignOrdering(Val.getNode(), Order);
218 if (RoundParts < NumParts) {
219 // Assemble the trailing non-power-of-2 part.
220 unsigned OddParts = NumParts - RoundParts;
221 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
222 Hi = getCopyFromParts(DAG, dl, Order,
223 Parts + RoundParts, OddParts, PartVT, OddVT);
225 // Combine the round and odd parts.
227 if (TLI.isBigEndian())
229 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
230 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
231 if (DisableScheduling) DAG.AssignOrdering(Hi.getNode(), Order);
232 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
233 DAG.getConstant(Lo.getValueType().getSizeInBits(),
234 TLI.getPointerTy()));
235 if (DisableScheduling) DAG.AssignOrdering(Hi.getNode(), Order);
236 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
237 if (DisableScheduling) DAG.AssignOrdering(Lo.getNode(), Order);
238 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
239 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
241 } else if (ValueVT.isVector()) {
242 // Handle a multi-element vector.
243 EVT IntermediateVT, RegisterVT;
244 unsigned NumIntermediates;
246 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
247 NumIntermediates, RegisterVT);
248 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
249 NumParts = NumRegs; // Silence a compiler warning.
250 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
251 assert(RegisterVT == Parts[0].getValueType() &&
252 "Part type doesn't match part!");
254 // Assemble the parts into intermediate operands.
255 SmallVector<SDValue, 8> Ops(NumIntermediates);
256 if (NumIntermediates == NumParts) {
257 // If the register was not expanded, truncate or copy the value,
259 for (unsigned i = 0; i != NumParts; ++i)
260 Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i], 1,
261 PartVT, IntermediateVT);
262 } else if (NumParts > 0) {
263 // If the intermediate type was expanded, build the intermediate operands
265 assert(NumParts % NumIntermediates == 0 &&
266 "Must expand into a divisible number of parts!");
267 unsigned Factor = NumParts / NumIntermediates;
268 for (unsigned i = 0; i != NumIntermediates; ++i)
269 Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i * Factor], Factor,
270 PartVT, IntermediateVT);
273 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
275 Val = DAG.getNode(IntermediateVT.isVector() ?
276 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
277 ValueVT, &Ops[0], NumIntermediates);
278 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
279 } else if (PartVT.isFloatingPoint()) {
280 // FP split into multiple FP parts (for ppcf128)
281 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
284 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
285 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
286 if (TLI.isBigEndian())
288 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
290 if (DisableScheduling) {
291 DAG.AssignOrdering(Hi.getNode(), Order);
292 DAG.AssignOrdering(Lo.getNode(), Order);
293 DAG.AssignOrdering(Val.getNode(), Order);
296 // FP split into integer parts (soft fp)
297 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
298 !PartVT.isVector() && "Unexpected split");
299 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
300 Val = getCopyFromParts(DAG, dl, Order, Parts, NumParts, PartVT, IntVT);
304 // There is now one part, held in Val. Correct it to match ValueVT.
305 PartVT = Val.getValueType();
307 if (PartVT == ValueVT)
310 if (PartVT.isVector()) {
311 assert(ValueVT.isVector() && "Unknown vector conversion!");
312 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
313 if (DisableScheduling)
314 DAG.AssignOrdering(Res.getNode(), Order);
318 if (ValueVT.isVector()) {
319 assert(ValueVT.getVectorElementType() == PartVT &&
320 ValueVT.getVectorNumElements() == 1 &&
321 "Only trivial scalar-to-vector conversions should get here!");
322 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
323 if (DisableScheduling)
324 DAG.AssignOrdering(Res.getNode(), Order);
328 if (PartVT.isInteger() &&
329 ValueVT.isInteger()) {
330 if (ValueVT.bitsLT(PartVT)) {
331 // For a truncate, see if we have any information to
332 // indicate whether the truncated bits will always be
333 // zero or sign-extension.
334 if (AssertOp != ISD::DELETED_NODE)
335 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
336 DAG.getValueType(ValueVT));
337 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
338 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
339 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
342 Val = DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
343 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
348 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
349 if (ValueVT.bitsLT(Val.getValueType())) {
350 // FP_ROUND's are always exact here.
351 Val = DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
352 DAG.getIntPtrConstant(1));
353 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
357 Val = DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
358 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
362 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
363 Val = DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
364 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
368 llvm_unreachable("Unknown mismatch!");
372 /// getCopyToParts - Create a series of nodes that contain the specified value
373 /// split into legal parts. If the parts contain more bits than Val, then, for
374 /// integers, ExtendKind can be used to specify how to generate the extra bits.
375 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
376 SDValue Val, SDValue *Parts, unsigned NumParts,
378 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
379 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
380 EVT PtrVT = TLI.getPointerTy();
381 EVT ValueVT = Val.getValueType();
382 unsigned PartBits = PartVT.getSizeInBits();
383 unsigned OrigNumParts = NumParts;
384 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
389 if (!ValueVT.isVector()) {
390 if (PartVT == ValueVT) {
391 assert(NumParts == 1 && "No-op copy with multiple parts!");
396 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
397 // If the parts cover more bits than the value has, promote the value.
398 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
399 assert(NumParts == 1 && "Do not know what to promote to!");
400 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
401 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
402 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
403 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
405 llvm_unreachable("Unknown mismatch!");
407 } else if (PartBits == ValueVT.getSizeInBits()) {
408 // Different types of the same size.
409 assert(NumParts == 1 && PartVT != ValueVT);
410 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
411 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
412 // If the parts cover less bits than value has, truncate the value.
413 if (PartVT.isInteger() && ValueVT.isInteger()) {
414 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
415 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
417 llvm_unreachable("Unknown mismatch!");
421 if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
423 // The value may have changed - recompute ValueVT.
424 ValueVT = Val.getValueType();
425 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
426 "Failed to tile the value with PartVT!");
429 assert(PartVT == ValueVT && "Type conversion failed!");
434 // Expand the value into multiple parts.
435 if (NumParts & (NumParts - 1)) {
436 // The number of parts is not a power of 2. Split off and copy the tail.
437 assert(PartVT.isInteger() && ValueVT.isInteger() &&
438 "Do not know what to expand to!");
439 unsigned RoundParts = 1 << Log2_32(NumParts);
440 unsigned RoundBits = RoundParts * PartBits;
441 unsigned OddParts = NumParts - RoundParts;
442 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
443 DAG.getConstant(RoundBits,
444 TLI.getPointerTy()));
445 getCopyToParts(DAG, dl, Order, OddVal, Parts + RoundParts,
448 if (TLI.isBigEndian())
449 // The odd parts were reversed by getCopyToParts - unreverse them.
450 std::reverse(Parts + RoundParts, Parts + NumParts);
452 NumParts = RoundParts;
453 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
454 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
456 if (DisableScheduling) {
457 DAG.AssignOrdering(OddVal.getNode(), Order);
458 DAG.AssignOrdering(Val.getNode(), Order);
462 // The number of parts is a power of 2. Repeatedly bisect the value using
464 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
465 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
468 if (DisableScheduling)
469 DAG.AssignOrdering(Parts[0].getNode(), Order);
471 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
472 for (unsigned i = 0; i < NumParts; i += StepSize) {
473 unsigned ThisBits = StepSize * PartBits / 2;
474 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
475 SDValue &Part0 = Parts[i];
476 SDValue &Part1 = Parts[i+StepSize/2];
478 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
480 DAG.getConstant(1, PtrVT));
481 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
483 DAG.getConstant(0, PtrVT));
485 if (DisableScheduling) {
486 DAG.AssignOrdering(Part0.getNode(), Order);
487 DAG.AssignOrdering(Part1.getNode(), Order);
490 if (ThisBits == PartBits && ThisVT != PartVT) {
491 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
493 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
495 if (DisableScheduling) {
496 DAG.AssignOrdering(Part0.getNode(), Order);
497 DAG.AssignOrdering(Part1.getNode(), Order);
503 if (TLI.isBigEndian())
504 std::reverse(Parts, Parts + OrigNumParts);
511 if (PartVT != ValueVT) {
512 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
513 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
515 assert(ValueVT.getVectorElementType() == PartVT &&
516 ValueVT.getVectorNumElements() == 1 &&
517 "Only trivial vector-to-scalar conversions should get here!");
518 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
520 DAG.getConstant(0, PtrVT));
524 if (DisableScheduling)
525 DAG.AssignOrdering(Val.getNode(), Order);
531 // Handle a multi-element vector.
532 EVT IntermediateVT, RegisterVT;
533 unsigned NumIntermediates;
534 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
535 IntermediateVT, NumIntermediates, RegisterVT);
536 unsigned NumElements = ValueVT.getVectorNumElements();
538 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
539 NumParts = NumRegs; // Silence a compiler warning.
540 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
542 // Split the vector into intermediate operands.
543 SmallVector<SDValue, 8> Ops(NumIntermediates);
544 for (unsigned i = 0; i != NumIntermediates; ++i) {
545 if (IntermediateVT.isVector())
546 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
548 DAG.getConstant(i * (NumElements / NumIntermediates),
551 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
553 DAG.getConstant(i, PtrVT));
555 if (DisableScheduling)
556 DAG.AssignOrdering(Ops[i].getNode(), Order);
559 // Split the intermediate operands into legal parts.
560 if (NumParts == NumIntermediates) {
561 // If the register was not expanded, promote or copy the value,
563 for (unsigned i = 0; i != NumParts; ++i)
564 getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i], 1, PartVT);
565 } else if (NumParts > 0) {
566 // If the intermediate type was expanded, split each the value into
568 assert(NumParts % NumIntermediates == 0 &&
569 "Must expand into a divisible number of parts!");
570 unsigned Factor = NumParts / NumIntermediates;
571 for (unsigned i = 0; i != NumIntermediates; ++i)
572 getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i*Factor], Factor, PartVT);
577 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
580 TD = DAG.getTarget().getTargetData();
583 /// clear - Clear out the curret SelectionDAG and the associated
584 /// state and prepare this SelectionDAGBuilder object to be used
585 /// for a new block. This doesn't clear out information about
586 /// additional blocks that are needed to complete switch lowering
587 /// or PHI node updating; that information is cleared out as it is
589 void SelectionDAGBuilder::clear() {
591 PendingLoads.clear();
592 PendingExports.clear();
595 CurDebugLoc = DebugLoc::getUnknownLoc();
599 /// getRoot - Return the current virtual root of the Selection DAG,
600 /// flushing any PendingLoad items. This must be done before emitting
601 /// a store or any other node that may need to be ordered after any
602 /// prior load instructions.
604 SDValue SelectionDAGBuilder::getRoot() {
605 if (PendingLoads.empty())
606 return DAG.getRoot();
608 if (PendingLoads.size() == 1) {
609 SDValue Root = PendingLoads[0];
611 PendingLoads.clear();
615 // Otherwise, we have to make a token factor node.
616 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
617 &PendingLoads[0], PendingLoads.size());
618 PendingLoads.clear();
623 /// getControlRoot - Similar to getRoot, but instead of flushing all the
624 /// PendingLoad items, flush all the PendingExports items. It is necessary
625 /// to do this before emitting a terminator instruction.
627 SDValue SelectionDAGBuilder::getControlRoot() {
628 SDValue Root = DAG.getRoot();
630 if (PendingExports.empty())
633 // Turn all of the CopyToReg chains into one factored node.
634 if (Root.getOpcode() != ISD::EntryToken) {
635 unsigned i = 0, e = PendingExports.size();
636 for (; i != e; ++i) {
637 assert(PendingExports[i].getNode()->getNumOperands() > 1);
638 if (PendingExports[i].getNode()->getOperand(0) == Root)
639 break; // Don't add the root if we already indirectly depend on it.
643 PendingExports.push_back(Root);
646 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
648 PendingExports.size());
649 PendingExports.clear();
654 void SelectionDAGBuilder::visit(Instruction &I) {
655 visit(I.getOpcode(), I);
658 void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
659 // We're processing a new instruction.
662 // Note: this doesn't use InstVisitor, because it has to work with
663 // ConstantExpr's in addition to instructions.
665 default: llvm_unreachable("Unknown instruction type encountered!");
666 // Build the switch statement using the Instruction.def file.
667 #define HANDLE_INST(NUM, OPCODE, CLASS) \
668 case Instruction::OPCODE: return visit##OPCODE((CLASS&)I);
669 #include "llvm/Instruction.def"
673 SDValue SelectionDAGBuilder::getValue(const Value *V) {
674 SDValue &N = NodeMap[V];
675 if (N.getNode()) return N;
677 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
678 EVT VT = TLI.getValueType(V->getType(), true);
680 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
681 return N = DAG.getConstant(*CI, VT);
683 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
684 return N = DAG.getGlobalAddress(GV, VT);
686 if (isa<ConstantPointerNull>(C))
687 return N = DAG.getConstant(0, TLI.getPointerTy());
689 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
690 return N = DAG.getConstantFP(*CFP, VT);
692 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
693 return N = DAG.getUNDEF(VT);
695 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
696 visit(CE->getOpcode(), *CE);
697 SDValue N1 = NodeMap[V];
698 assert(N1.getNode() && "visit didn't populate the ValueMap!");
702 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
703 SmallVector<SDValue, 4> Constants;
704 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
706 SDNode *Val = getValue(*OI).getNode();
707 // If the operand is an empty aggregate, there are no values.
709 // Add each leaf value from the operand to the Constants list
710 // to form a flattened list of all the values.
711 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
712 Constants.push_back(SDValue(Val, i));
715 SDValue Res = DAG.getMergeValues(&Constants[0], Constants.size(),
717 if (DisableScheduling)
718 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
722 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
723 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
724 "Unknown struct or array constant!");
726 SmallVector<EVT, 4> ValueVTs;
727 ComputeValueVTs(TLI, C->getType(), ValueVTs);
728 unsigned NumElts = ValueVTs.size();
730 return SDValue(); // empty struct
731 SmallVector<SDValue, 4> Constants(NumElts);
732 for (unsigned i = 0; i != NumElts; ++i) {
733 EVT EltVT = ValueVTs[i];
734 if (isa<UndefValue>(C))
735 Constants[i] = DAG.getUNDEF(EltVT);
736 else if (EltVT.isFloatingPoint())
737 Constants[i] = DAG.getConstantFP(0, EltVT);
739 Constants[i] = DAG.getConstant(0, EltVT);
742 SDValue Res = DAG.getMergeValues(&Constants[0], NumElts,
744 if (DisableScheduling)
745 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
749 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
750 return DAG.getBlockAddress(BA, VT);
752 const VectorType *VecTy = cast<VectorType>(V->getType());
753 unsigned NumElements = VecTy->getNumElements();
755 // Now that we know the number and type of the elements, get that number of
756 // elements into the Ops array based on what kind of constant it is.
757 SmallVector<SDValue, 16> Ops;
758 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
759 for (unsigned i = 0; i != NumElements; ++i)
760 Ops.push_back(getValue(CP->getOperand(i)));
762 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
763 EVT EltVT = TLI.getValueType(VecTy->getElementType());
766 if (EltVT.isFloatingPoint())
767 Op = DAG.getConstantFP(0, EltVT);
769 Op = DAG.getConstant(0, EltVT);
770 Ops.assign(NumElements, Op);
773 // Create a BUILD_VECTOR node.
774 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
775 VT, &Ops[0], Ops.size());
776 if (DisableScheduling)
777 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
779 return NodeMap[V] = Res;
782 // If this is a static alloca, generate it as the frameindex instead of
784 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
785 DenseMap<const AllocaInst*, int>::iterator SI =
786 FuncInfo.StaticAllocaMap.find(AI);
787 if (SI != FuncInfo.StaticAllocaMap.end())
788 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
791 unsigned InReg = FuncInfo.ValueMap[V];
792 assert(InReg && "Value not in map!");
794 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
795 SDValue Chain = DAG.getEntryNode();
796 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(),
797 SDNodeOrder, Chain, NULL);
800 /// Get the EVTs and ArgFlags collections that represent the return type
801 /// of the given function. This does not require a DAG or a return value, and
802 /// is suitable for use before any DAGs for the function are constructed.
803 static void getReturnInfo(const Type* ReturnType,
804 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
805 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
807 SmallVectorImpl<uint64_t> *Offsets = 0) {
808 SmallVector<EVT, 4> ValueVTs;
809 ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets);
810 unsigned NumValues = ValueVTs.size();
811 if ( NumValues == 0 ) return;
813 for (unsigned j = 0, f = NumValues; j != f; ++j) {
814 EVT VT = ValueVTs[j];
815 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
817 if (attr & Attribute::SExt)
818 ExtendKind = ISD::SIGN_EXTEND;
819 else if (attr & Attribute::ZExt)
820 ExtendKind = ISD::ZERO_EXTEND;
822 // FIXME: C calling convention requires the return type to be promoted to
823 // at least 32-bit. But this is not necessary for non-C calling
824 // conventions. The frontend should mark functions whose return values
825 // require promoting with signext or zeroext attributes.
826 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
827 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
828 if (VT.bitsLT(MinVT))
832 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
833 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
834 // 'inreg' on function refers to return value
835 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
836 if (attr & Attribute::InReg)
839 // Propagate extension type if any
840 if (attr & Attribute::SExt)
842 else if (attr & Attribute::ZExt)
845 for (unsigned i = 0; i < NumParts; ++i) {
846 OutVTs.push_back(PartVT);
847 OutFlags.push_back(Flags);
852 void SelectionDAGBuilder::visitRet(ReturnInst &I) {
853 SDValue Chain = getControlRoot();
854 SmallVector<ISD::OutputArg, 8> Outs;
855 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
857 if (!FLI.CanLowerReturn) {
858 unsigned DemoteReg = FLI.DemoteRegister;
859 const Function *F = I.getParent()->getParent();
861 // Emit a store of the return value through the virtual register.
862 // Leave Outs empty so that LowerReturn won't try to load return
863 // registers the usual way.
864 SmallVector<EVT, 1> PtrValueVTs;
865 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
868 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
869 SDValue RetOp = getValue(I.getOperand(0));
871 SmallVector<EVT, 4> ValueVTs;
872 SmallVector<uint64_t, 4> Offsets;
873 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
874 unsigned NumValues = ValueVTs.size();
876 SmallVector<SDValue, 4> Chains(NumValues);
877 EVT PtrVT = PtrValueVTs[0];
878 for (unsigned i = 0; i != NumValues; ++i) {
879 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
880 DAG.getConstant(Offsets[i], PtrVT));
882 DAG.getStore(Chain, getCurDebugLoc(),
883 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
884 Add, NULL, Offsets[i], false, 0);
886 if (DisableScheduling) {
887 DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
888 DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder);
892 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
893 MVT::Other, &Chains[0], NumValues);
895 if (DisableScheduling)
896 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
898 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
899 SmallVector<EVT, 4> ValueVTs;
900 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
901 unsigned NumValues = ValueVTs.size();
902 if (NumValues == 0) continue;
904 SDValue RetOp = getValue(I.getOperand(i));
905 for (unsigned j = 0, f = NumValues; j != f; ++j) {
906 EVT VT = ValueVTs[j];
908 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
910 const Function *F = I.getParent()->getParent();
911 if (F->paramHasAttr(0, Attribute::SExt))
912 ExtendKind = ISD::SIGN_EXTEND;
913 else if (F->paramHasAttr(0, Attribute::ZExt))
914 ExtendKind = ISD::ZERO_EXTEND;
916 // FIXME: C calling convention requires the return type to be promoted to
917 // at least 32-bit. But this is not necessary for non-C calling
918 // conventions. The frontend should mark functions whose return values
919 // require promoting with signext or zeroext attributes.
920 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
921 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
922 if (VT.bitsLT(MinVT))
926 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
927 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
928 SmallVector<SDValue, 4> Parts(NumParts);
929 getCopyToParts(DAG, getCurDebugLoc(), SDNodeOrder,
930 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
931 &Parts[0], NumParts, PartVT, ExtendKind);
933 // 'inreg' on function refers to return value
934 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
935 if (F->paramHasAttr(0, Attribute::InReg))
938 // Propagate extension type if any
939 if (F->paramHasAttr(0, Attribute::SExt))
941 else if (F->paramHasAttr(0, Attribute::ZExt))
944 for (unsigned i = 0; i < NumParts; ++i)
945 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
950 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
951 CallingConv::ID CallConv =
952 DAG.getMachineFunction().getFunction()->getCallingConv();
953 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
954 Outs, getCurDebugLoc(), DAG);
956 // Verify that the target's LowerReturn behaved as expected.
957 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
958 "LowerReturn didn't return a valid chain!");
960 // Update the DAG with the new chain value resulting from return lowering.
963 if (DisableScheduling)
964 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
967 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
968 /// created for it, emit nodes to copy the value into the virtual
970 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
971 if (!V->use_empty()) {
972 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
973 if (VMI != FuncInfo.ValueMap.end())
974 CopyValueToVirtualRegister(V, VMI->second);
978 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
979 /// the current basic block, add it to ValueMap now so that we'll get a
981 void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
982 // No need to export constants.
983 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
986 if (FuncInfo.isExportedInst(V)) return;
988 unsigned Reg = FuncInfo.InitializeRegForValue(V);
989 CopyValueToVirtualRegister(V, Reg);
992 bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
993 const BasicBlock *FromBB) {
994 // The operands of the setcc have to be in this block. We don't know
995 // how to export them from some other block.
996 if (Instruction *VI = dyn_cast<Instruction>(V)) {
997 // Can export from current BB.
998 if (VI->getParent() == FromBB)
1001 // Is already exported, noop.
1002 return FuncInfo.isExportedInst(V);
1005 // If this is an argument, we can export it if the BB is the entry block or
1006 // if it is already exported.
1007 if (isa<Argument>(V)) {
1008 if (FromBB == &FromBB->getParent()->getEntryBlock())
1011 // Otherwise, can only export this if it is already exported.
1012 return FuncInfo.isExportedInst(V);
1015 // Otherwise, constants can always be exported.
1019 static bool InBlock(const Value *V, const BasicBlock *BB) {
1020 if (const Instruction *I = dyn_cast<Instruction>(V))
1021 return I->getParent() == BB;
1025 /// getFCmpCondCode - Return the ISD condition code corresponding to
1026 /// the given LLVM IR floating-point condition code. This includes
1027 /// consideration of global floating-point math flags.
1029 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1030 ISD::CondCode FPC, FOC;
1032 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1033 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1034 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1035 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1036 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1037 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1038 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1039 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1040 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1041 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1042 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1043 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1044 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1045 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1046 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1047 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1049 llvm_unreachable("Invalid FCmp predicate opcode!");
1050 FOC = FPC = ISD::SETFALSE;
1053 if (FiniteOnlyFPMath())
1059 /// getICmpCondCode - Return the ISD condition code corresponding to
1060 /// the given LLVM IR integer condition code.
1062 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1064 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1065 case ICmpInst::ICMP_NE: return ISD::SETNE;
1066 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1067 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1068 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1069 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1070 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1071 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1072 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1073 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1075 llvm_unreachable("Invalid ICmp predicate opcode!");
1080 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1081 /// This function emits a branch and is used at the leaves of an OR or an
1082 /// AND operator tree.
1085 SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1086 MachineBasicBlock *TBB,
1087 MachineBasicBlock *FBB,
1088 MachineBasicBlock *CurBB) {
1089 const BasicBlock *BB = CurBB->getBasicBlock();
1091 // If the leaf of the tree is a comparison, merge the condition into
1093 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1094 // The operands of the cmp have to be in this block. We don't know
1095 // how to export them from some other block. If this is the first block
1096 // of the sequence, no exporting is needed.
1097 if (CurBB == CurMBB ||
1098 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1099 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1100 ISD::CondCode Condition;
1101 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1102 Condition = getICmpCondCode(IC->getPredicate());
1103 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1104 Condition = getFCmpCondCode(FC->getPredicate());
1106 Condition = ISD::SETEQ; // silence warning.
1107 llvm_unreachable("Unknown compare instruction");
1110 CaseBlock CB(Condition, BOp->getOperand(0),
1111 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1112 SwitchCases.push_back(CB);
1117 // Create a CaseBlock record representing this branch.
1118 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1119 NULL, TBB, FBB, CurBB);
1120 SwitchCases.push_back(CB);
1123 /// FindMergedConditions - If Cond is an expression like
1124 void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1125 MachineBasicBlock *TBB,
1126 MachineBasicBlock *FBB,
1127 MachineBasicBlock *CurBB,
1129 // If this node is not part of the or/and tree, emit it as a branch.
1130 Instruction *BOp = dyn_cast<Instruction>(Cond);
1131 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1132 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1133 BOp->getParent() != CurBB->getBasicBlock() ||
1134 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1135 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1136 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1140 // Create TmpBB after CurBB.
1141 MachineFunction::iterator BBI = CurBB;
1142 MachineFunction &MF = DAG.getMachineFunction();
1143 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1144 CurBB->getParent()->insert(++BBI, TmpBB);
1146 if (Opc == Instruction::Or) {
1147 // Codegen X | Y as:
1155 // Emit the LHS condition.
1156 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1158 // Emit the RHS condition into TmpBB.
1159 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1161 assert(Opc == Instruction::And && "Unknown merge op!");
1162 // Codegen X & Y as:
1169 // This requires creation of TmpBB after CurBB.
1171 // Emit the LHS condition.
1172 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1174 // Emit the RHS condition into TmpBB.
1175 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1179 /// If the set of cases should be emitted as a series of branches, return true.
1180 /// If we should emit this as a bunch of and/or'd together conditions, return
1183 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1184 if (Cases.size() != 2) return true;
1186 // If this is two comparisons of the same values or'd or and'd together, they
1187 // will get folded into a single comparison, so don't emit two blocks.
1188 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1189 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1190 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1191 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1198 void SelectionDAGBuilder::visitBr(BranchInst &I) {
1199 // Update machine-CFG edges.
1200 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1202 // Figure out which block is immediately after the current one.
1203 MachineBasicBlock *NextBlock = 0;
1204 MachineFunction::iterator BBI = CurMBB;
1205 if (++BBI != FuncInfo.MF->end())
1208 if (I.isUnconditional()) {
1209 // Update machine-CFG edges.
1210 CurMBB->addSuccessor(Succ0MBB);
1212 // If this is not a fall-through branch, emit the branch.
1213 if (Succ0MBB != NextBlock) {
1214 SDValue V = DAG.getNode(ISD::BR, getCurDebugLoc(),
1215 MVT::Other, getControlRoot(),
1216 DAG.getBasicBlock(Succ0MBB));
1219 if (DisableScheduling)
1220 DAG.AssignOrdering(V.getNode(), SDNodeOrder);
1226 // If this condition is one of the special cases we handle, do special stuff
1228 Value *CondVal = I.getCondition();
1229 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1231 // If this is a series of conditions that are or'd or and'd together, emit
1232 // this as a sequence of branches instead of setcc's with and/or operations.
1233 // For example, instead of something like:
1246 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1247 if (BOp->hasOneUse() &&
1248 (BOp->getOpcode() == Instruction::And ||
1249 BOp->getOpcode() == Instruction::Or)) {
1250 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1251 // If the compares in later blocks need to use values not currently
1252 // exported from this block, export them now. This block should always
1253 // be the first entry.
1254 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1256 // Allow some cases to be rejected.
1257 if (ShouldEmitAsBranches(SwitchCases)) {
1258 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1259 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1260 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1263 // Emit the branch for this block.
1264 visitSwitchCase(SwitchCases[0]);
1265 SwitchCases.erase(SwitchCases.begin());
1269 // Okay, we decided not to do this, remove any inserted MBB's and clear
1271 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1272 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1274 SwitchCases.clear();
1278 // Create a CaseBlock record representing this branch.
1279 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1280 NULL, Succ0MBB, Succ1MBB, CurMBB);
1282 // Use visitSwitchCase to actually insert the fast branch sequence for this
1284 visitSwitchCase(CB);
1287 /// visitSwitchCase - Emits the necessary code to represent a single node in
1288 /// the binary search tree resulting from lowering a switch instruction.
1289 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
1291 SDValue CondLHS = getValue(CB.CmpLHS);
1292 DebugLoc dl = getCurDebugLoc();
1294 // Build the setcc now.
1295 if (CB.CmpMHS == NULL) {
1296 // Fold "(X == true)" to X and "(X == false)" to !X to
1297 // handle common cases produced by branch lowering.
1298 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1299 CB.CC == ISD::SETEQ)
1301 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1302 CB.CC == ISD::SETEQ) {
1303 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1304 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1306 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1308 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1310 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1311 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1313 SDValue CmpOp = getValue(CB.CmpMHS);
1314 EVT VT = CmpOp.getValueType();
1316 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1317 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1320 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1321 VT, CmpOp, DAG.getConstant(Low, VT));
1322 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1323 DAG.getConstant(High-Low, VT), ISD::SETULE);
1327 if (DisableScheduling)
1328 DAG.AssignOrdering(Cond.getNode(), SDNodeOrder);
1330 // Update successor info
1331 CurMBB->addSuccessor(CB.TrueBB);
1332 CurMBB->addSuccessor(CB.FalseBB);
1334 // Set NextBlock to be the MBB immediately after the current one, if any.
1335 // This is used to avoid emitting unnecessary branches to the next block.
1336 MachineBasicBlock *NextBlock = 0;
1337 MachineFunction::iterator BBI = CurMBB;
1338 if (++BBI != FuncInfo.MF->end())
1341 // If the lhs block is the next block, invert the condition so that we can
1342 // fall through to the lhs instead of the rhs block.
1343 if (CB.TrueBB == NextBlock) {
1344 std::swap(CB.TrueBB, CB.FalseBB);
1345 SDValue True = DAG.getConstant(1, Cond.getValueType());
1346 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1348 if (DisableScheduling)
1349 DAG.AssignOrdering(Cond.getNode(), SDNodeOrder);
1352 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1353 MVT::Other, getControlRoot(), Cond,
1354 DAG.getBasicBlock(CB.TrueBB));
1356 if (DisableScheduling)
1357 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1359 // If the branch was constant folded, fix up the CFG.
1360 if (BrCond.getOpcode() == ISD::BR) {
1361 CurMBB->removeSuccessor(CB.FalseBB);
1363 // Otherwise, go ahead and insert the false branch.
1364 if (BrCond == getControlRoot())
1365 CurMBB->removeSuccessor(CB.TrueBB);
1367 if (CB.FalseBB != NextBlock) {
1368 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1369 DAG.getBasicBlock(CB.FalseBB));
1371 if (DisableScheduling)
1372 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1376 DAG.setRoot(BrCond);
1379 /// visitJumpTable - Emit JumpTable node in the current MBB
1380 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1381 // Emit the code for the jump table
1382 assert(JT.Reg != -1U && "Should lower JT Header first!");
1383 EVT PTy = TLI.getPointerTy();
1384 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1386 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1387 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1388 MVT::Other, Index.getValue(1),
1390 DAG.setRoot(BrJumpTable);
1392 if (DisableScheduling) {
1393 DAG.AssignOrdering(Index.getNode(), SDNodeOrder);
1394 DAG.AssignOrdering(Table.getNode(), SDNodeOrder);
1395 DAG.AssignOrdering(BrJumpTable.getNode(), SDNodeOrder);
1399 /// visitJumpTableHeader - This function emits necessary code to produce index
1400 /// in the JumpTable from switch case.
1401 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1402 JumpTableHeader &JTH) {
1403 // Subtract the lowest switch case value from the value being switched on and
1404 // conditional branch to default mbb if the result is greater than the
1405 // difference between smallest and largest cases.
1406 SDValue SwitchOp = getValue(JTH.SValue);
1407 EVT VT = SwitchOp.getValueType();
1408 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1409 DAG.getConstant(JTH.First, VT));
1411 // The SDNode we just created, which holds the value being switched on minus
1412 // the the smallest case value, needs to be copied to a virtual register so it
1413 // can be used as an index into the jump table in a subsequent basic block.
1414 // This value may be smaller or larger than the target's pointer type, and
1415 // therefore require extension or truncating.
1416 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1418 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1419 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1420 JumpTableReg, SwitchOp);
1421 JT.Reg = JumpTableReg;
1423 // Emit the range check for the jump table, and branch to the default block
1424 // for the switch statement if the value being switched on exceeds the largest
1425 // case in the switch.
1426 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1427 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1428 DAG.getConstant(JTH.Last-JTH.First,VT),
1431 if (DisableScheduling) {
1432 DAG.AssignOrdering(Sub.getNode(), SDNodeOrder);
1433 DAG.AssignOrdering(SwitchOp.getNode(), SDNodeOrder);
1434 DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder);
1435 DAG.AssignOrdering(CMP.getNode(), SDNodeOrder);
1438 // Set NextBlock to be the MBB immediately after the current one, if any.
1439 // This is used to avoid emitting unnecessary branches to the next block.
1440 MachineBasicBlock *NextBlock = 0;
1441 MachineFunction::iterator BBI = CurMBB;
1443 if (++BBI != FuncInfo.MF->end())
1446 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1447 MVT::Other, CopyTo, CMP,
1448 DAG.getBasicBlock(JT.Default));
1450 if (DisableScheduling)
1451 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1453 if (JT.MBB != NextBlock) {
1454 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1455 DAG.getBasicBlock(JT.MBB));
1457 if (DisableScheduling)
1458 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1461 DAG.setRoot(BrCond);
1464 /// visitBitTestHeader - This function emits necessary code to produce value
1465 /// suitable for "bit tests"
1466 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
1467 // Subtract the minimum value
1468 SDValue SwitchOp = getValue(B.SValue);
1469 EVT VT = SwitchOp.getValueType();
1470 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1471 DAG.getConstant(B.First, VT));
1474 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1475 TLI.getSetCCResultType(Sub.getValueType()),
1476 Sub, DAG.getConstant(B.Range, VT),
1479 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1480 TLI.getPointerTy());
1482 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1483 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1486 if (DisableScheduling) {
1487 DAG.AssignOrdering(Sub.getNode(), SDNodeOrder);
1488 DAG.AssignOrdering(RangeCmp.getNode(), SDNodeOrder);
1489 DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder);
1490 DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder);
1493 // Set NextBlock to be the MBB immediately after the current one, if any.
1494 // This is used to avoid emitting unnecessary branches to the next block.
1495 MachineBasicBlock *NextBlock = 0;
1496 MachineFunction::iterator BBI = CurMBB;
1497 if (++BBI != FuncInfo.MF->end())
1500 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1502 CurMBB->addSuccessor(B.Default);
1503 CurMBB->addSuccessor(MBB);
1505 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1506 MVT::Other, CopyTo, RangeCmp,
1507 DAG.getBasicBlock(B.Default));
1509 if (DisableScheduling)
1510 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1512 if (MBB != NextBlock) {
1513 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1514 DAG.getBasicBlock(MBB));
1516 if (DisableScheduling)
1517 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1520 DAG.setRoot(BrRange);
1523 /// visitBitTestCase - this function produces one "bit test"
1524 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1527 // Make desired shift
1528 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1529 TLI.getPointerTy());
1530 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1532 DAG.getConstant(1, TLI.getPointerTy()),
1535 // Emit bit tests and jumps
1536 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1537 TLI.getPointerTy(), SwitchVal,
1538 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1539 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1540 TLI.getSetCCResultType(AndOp.getValueType()),
1541 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1544 if (DisableScheduling) {
1545 DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder);
1546 DAG.AssignOrdering(SwitchVal.getNode(), SDNodeOrder);
1547 DAG.AssignOrdering(AndOp.getNode(), SDNodeOrder);
1548 DAG.AssignOrdering(AndCmp.getNode(), SDNodeOrder);
1551 CurMBB->addSuccessor(B.TargetBB);
1552 CurMBB->addSuccessor(NextMBB);
1554 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1555 MVT::Other, getControlRoot(),
1556 AndCmp, DAG.getBasicBlock(B.TargetBB));
1558 if (DisableScheduling)
1559 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1561 // Set NextBlock to be the MBB immediately after the current one, if any.
1562 // This is used to avoid emitting unnecessary branches to the next block.
1563 MachineBasicBlock *NextBlock = 0;
1564 MachineFunction::iterator BBI = CurMBB;
1565 if (++BBI != FuncInfo.MF->end())
1568 if (NextMBB != NextBlock) {
1569 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1570 DAG.getBasicBlock(NextMBB));
1572 if (DisableScheduling)
1573 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1579 void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
1580 // Retrieve successors.
1581 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1582 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1584 const Value *Callee(I.getCalledValue());
1585 if (isa<InlineAsm>(Callee))
1588 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1590 // If the value of the invoke is used outside of its defining block, make it
1591 // available as a virtual register.
1592 CopyToExportRegsIfNeeded(&I);
1594 // Update successor info
1595 CurMBB->addSuccessor(Return);
1596 CurMBB->addSuccessor(LandingPad);
1598 // Drop into normal successor.
1599 SDValue Branch = DAG.getNode(ISD::BR, getCurDebugLoc(),
1600 MVT::Other, getControlRoot(),
1601 DAG.getBasicBlock(Return));
1602 DAG.setRoot(Branch);
1604 if (DisableScheduling)
1605 DAG.AssignOrdering(Branch.getNode(), SDNodeOrder);
1608 void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
1611 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1612 /// small case ranges).
1613 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1614 CaseRecVector& WorkList,
1616 MachineBasicBlock* Default) {
1617 Case& BackCase = *(CR.Range.second-1);
1619 // Size is the number of Cases represented by this range.
1620 size_t Size = CR.Range.second - CR.Range.first;
1624 // Get the MachineFunction which holds the current MBB. This is used when
1625 // inserting any additional MBBs necessary to represent the switch.
1626 MachineFunction *CurMF = FuncInfo.MF;
1628 // Figure out which block is immediately after the current one.
1629 MachineBasicBlock *NextBlock = 0;
1630 MachineFunction::iterator BBI = CR.CaseBB;
1632 if (++BBI != FuncInfo.MF->end())
1635 // TODO: If any two of the cases has the same destination, and if one value
1636 // is the same as the other, but has one bit unset that the other has set,
1637 // use bit manipulation to do two compares at once. For example:
1638 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1640 // Rearrange the case blocks so that the last one falls through if possible.
1641 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1642 // The last case block won't fall through into 'NextBlock' if we emit the
1643 // branches in this order. See if rearranging a case value would help.
1644 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1645 if (I->BB == NextBlock) {
1646 std::swap(*I, BackCase);
1652 // Create a CaseBlock record representing a conditional branch to
1653 // the Case's target mbb if the value being switched on SV is equal
1655 MachineBasicBlock *CurBlock = CR.CaseBB;
1656 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1657 MachineBasicBlock *FallThrough;
1659 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1660 CurMF->insert(BBI, FallThrough);
1662 // Put SV in a virtual register to make it available from the new blocks.
1663 ExportFromCurrentBlock(SV);
1665 // If the last case doesn't match, go to the default block.
1666 FallThrough = Default;
1669 Value *RHS, *LHS, *MHS;
1671 if (I->High == I->Low) {
1672 // This is just small small case range :) containing exactly 1 case
1674 LHS = SV; RHS = I->High; MHS = NULL;
1677 LHS = I->Low; MHS = SV; RHS = I->High;
1679 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1681 // If emitting the first comparison, just call visitSwitchCase to emit the
1682 // code into the current block. Otherwise, push the CaseBlock onto the
1683 // vector to be later processed by SDISel, and insert the node's MBB
1684 // before the next MBB.
1685 if (CurBlock == CurMBB)
1686 visitSwitchCase(CB);
1688 SwitchCases.push_back(CB);
1690 CurBlock = FallThrough;
1696 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1697 return !DisableJumpTables &&
1698 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1699 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1702 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1703 APInt LastExt(Last), FirstExt(First);
1704 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1705 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1706 return (LastExt - FirstExt + 1ULL);
1709 /// handleJTSwitchCase - Emit jumptable for current switch case range
1710 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1711 CaseRecVector& WorkList,
1713 MachineBasicBlock* Default) {
1714 Case& FrontCase = *CR.Range.first;
1715 Case& BackCase = *(CR.Range.second-1);
1717 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1718 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1720 APInt TSize(First.getBitWidth(), 0);
1721 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1725 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
1728 APInt Range = ComputeRange(First, Last);
1729 double Density = TSize.roundToDouble() / Range.roundToDouble();
1733 DEBUG(errs() << "Lowering jump table\n"
1734 << "First entry: " << First << ". Last entry: " << Last << '\n'
1735 << "Range: " << Range
1736 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1738 // Get the MachineFunction which holds the current MBB. This is used when
1739 // inserting any additional MBBs necessary to represent the switch.
1740 MachineFunction *CurMF = FuncInfo.MF;
1742 // Figure out which block is immediately after the current one.
1743 MachineFunction::iterator BBI = CR.CaseBB;
1746 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1748 // Create a new basic block to hold the code for loading the address
1749 // of the jump table, and jumping to it. Update successor information;
1750 // we will either branch to the default case for the switch, or the jump
1752 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1753 CurMF->insert(BBI, JumpTableBB);
1754 CR.CaseBB->addSuccessor(Default);
1755 CR.CaseBB->addSuccessor(JumpTableBB);
1757 // Build a vector of destination BBs, corresponding to each target
1758 // of the jump table. If the value of the jump table slot corresponds to
1759 // a case statement, push the case's BB onto the vector, otherwise, push
1761 std::vector<MachineBasicBlock*> DestBBs;
1763 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1764 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1765 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1767 if (Low.sle(TEI) && TEI.sle(High)) {
1768 DestBBs.push_back(I->BB);
1772 DestBBs.push_back(Default);
1776 // Update successor info. Add one edge to each unique successor.
1777 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1778 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1779 E = DestBBs.end(); I != E; ++I) {
1780 if (!SuccsHandled[(*I)->getNumber()]) {
1781 SuccsHandled[(*I)->getNumber()] = true;
1782 JumpTableBB->addSuccessor(*I);
1786 // Create a jump table index for this jump table, or return an existing
1788 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1790 // Set the jump table information so that we can codegen it as a second
1791 // MachineBasicBlock
1792 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1793 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1794 if (CR.CaseBB == CurMBB)
1795 visitJumpTableHeader(JT, JTH);
1797 JTCases.push_back(JumpTableBlock(JTH, JT));
1802 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1804 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1805 CaseRecVector& WorkList,
1807 MachineBasicBlock* Default) {
1808 // Get the MachineFunction which holds the current MBB. This is used when
1809 // inserting any additional MBBs necessary to represent the switch.
1810 MachineFunction *CurMF = FuncInfo.MF;
1812 // Figure out which block is immediately after the current one.
1813 MachineFunction::iterator BBI = CR.CaseBB;
1816 Case& FrontCase = *CR.Range.first;
1817 Case& BackCase = *(CR.Range.second-1);
1818 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1820 // Size is the number of Cases represented by this range.
1821 unsigned Size = CR.Range.second - CR.Range.first;
1823 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1824 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1826 CaseItr Pivot = CR.Range.first + Size/2;
1828 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1829 // (heuristically) allow us to emit JumpTable's later.
1830 APInt TSize(First.getBitWidth(), 0);
1831 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1835 APInt LSize = FrontCase.size();
1836 APInt RSize = TSize-LSize;
1837 DEBUG(errs() << "Selecting best pivot: \n"
1838 << "First: " << First << ", Last: " << Last <<'\n'
1839 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1840 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1842 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1843 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1844 APInt Range = ComputeRange(LEnd, RBegin);
1845 assert((Range - 2ULL).isNonNegative() &&
1846 "Invalid case distance");
1847 double LDensity = (double)LSize.roundToDouble() /
1848 (LEnd - First + 1ULL).roundToDouble();
1849 double RDensity = (double)RSize.roundToDouble() /
1850 (Last - RBegin + 1ULL).roundToDouble();
1851 double Metric = Range.logBase2()*(LDensity+RDensity);
1852 // Should always split in some non-trivial place
1853 DEBUG(errs() <<"=>Step\n"
1854 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1855 << "LDensity: " << LDensity
1856 << ", RDensity: " << RDensity << '\n'
1857 << "Metric: " << Metric << '\n');
1858 if (FMetric < Metric) {
1861 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1867 if (areJTsAllowed(TLI)) {
1868 // If our case is dense we *really* should handle it earlier!
1869 assert((FMetric > 0) && "Should handle dense range earlier!");
1871 Pivot = CR.Range.first + Size/2;
1874 CaseRange LHSR(CR.Range.first, Pivot);
1875 CaseRange RHSR(Pivot, CR.Range.second);
1876 Constant *C = Pivot->Low;
1877 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1879 // We know that we branch to the LHS if the Value being switched on is
1880 // less than the Pivot value, C. We use this to optimize our binary
1881 // tree a bit, by recognizing that if SV is greater than or equal to the
1882 // LHS's Case Value, and that Case Value is exactly one less than the
1883 // Pivot's Value, then we can branch directly to the LHS's Target,
1884 // rather than creating a leaf node for it.
1885 if ((LHSR.second - LHSR.first) == 1 &&
1886 LHSR.first->High == CR.GE &&
1887 cast<ConstantInt>(C)->getValue() ==
1888 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1889 TrueBB = LHSR.first->BB;
1891 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1892 CurMF->insert(BBI, TrueBB);
1893 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1895 // Put SV in a virtual register to make it available from the new blocks.
1896 ExportFromCurrentBlock(SV);
1899 // Similar to the optimization above, if the Value being switched on is
1900 // known to be less than the Constant CR.LT, and the current Case Value
1901 // is CR.LT - 1, then we can branch directly to the target block for
1902 // the current Case Value, rather than emitting a RHS leaf node for it.
1903 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1904 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1905 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1906 FalseBB = RHSR.first->BB;
1908 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1909 CurMF->insert(BBI, FalseBB);
1910 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1912 // Put SV in a virtual register to make it available from the new blocks.
1913 ExportFromCurrentBlock(SV);
1916 // Create a CaseBlock record representing a conditional branch to
1917 // the LHS node if the value being switched on SV is less than C.
1918 // Otherwise, branch to LHS.
1919 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1921 if (CR.CaseBB == CurMBB)
1922 visitSwitchCase(CB);
1924 SwitchCases.push_back(CB);
1929 /// handleBitTestsSwitchCase - if current case range has few destination and
1930 /// range span less, than machine word bitwidth, encode case range into series
1931 /// of masks and emit bit tests with these masks.
1932 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1933 CaseRecVector& WorkList,
1935 MachineBasicBlock* Default){
1936 EVT PTy = TLI.getPointerTy();
1937 unsigned IntPtrBits = PTy.getSizeInBits();
1939 Case& FrontCase = *CR.Range.first;
1940 Case& BackCase = *(CR.Range.second-1);
1942 // Get the MachineFunction which holds the current MBB. This is used when
1943 // inserting any additional MBBs necessary to represent the switch.
1944 MachineFunction *CurMF = FuncInfo.MF;
1946 // If target does not have legal shift left, do not emit bit tests at all.
1947 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1951 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1953 // Single case counts one, case range - two.
1954 numCmps += (I->Low == I->High ? 1 : 2);
1957 // Count unique destinations
1958 SmallSet<MachineBasicBlock*, 4> Dests;
1959 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1960 Dests.insert(I->BB);
1961 if (Dests.size() > 3)
1962 // Don't bother the code below, if there are too much unique destinations
1965 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1966 << "Total number of comparisons: " << numCmps << '\n');
1968 // Compute span of values.
1969 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1970 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1971 APInt cmpRange = maxValue - minValue;
1973 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1974 << "Low bound: " << minValue << '\n'
1975 << "High bound: " << maxValue << '\n');
1977 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1978 (!(Dests.size() == 1 && numCmps >= 3) &&
1979 !(Dests.size() == 2 && numCmps >= 5) &&
1980 !(Dests.size() >= 3 && numCmps >= 6)))
1983 DEBUG(errs() << "Emitting bit tests\n");
1984 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1986 // Optimize the case where all the case values fit in a
1987 // word without having to subtract minValue. In this case,
1988 // we can optimize away the subtraction.
1989 if (minValue.isNonNegative() &&
1990 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1991 cmpRange = maxValue;
1993 lowBound = minValue;
1996 CaseBitsVector CasesBits;
1997 unsigned i, count = 0;
1999 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2000 MachineBasicBlock* Dest = I->BB;
2001 for (i = 0; i < count; ++i)
2002 if (Dest == CasesBits[i].BB)
2006 assert((count < 3) && "Too much destinations to test!");
2007 CasesBits.push_back(CaseBits(0, Dest, 0));
2011 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2012 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2014 uint64_t lo = (lowValue - lowBound).getZExtValue();
2015 uint64_t hi = (highValue - lowBound).getZExtValue();
2017 for (uint64_t j = lo; j <= hi; j++) {
2018 CasesBits[i].Mask |= 1ULL << j;
2019 CasesBits[i].Bits++;
2023 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2027 // Figure out which block is immediately after the current one.
2028 MachineFunction::iterator BBI = CR.CaseBB;
2031 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2033 DEBUG(errs() << "Cases:\n");
2034 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2035 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2036 << ", Bits: " << CasesBits[i].Bits
2037 << ", BB: " << CasesBits[i].BB << '\n');
2039 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2040 CurMF->insert(BBI, CaseBB);
2041 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2045 // Put SV in a virtual register to make it available from the new blocks.
2046 ExportFromCurrentBlock(SV);
2049 BitTestBlock BTB(lowBound, cmpRange, SV,
2050 -1U, (CR.CaseBB == CurMBB),
2051 CR.CaseBB, Default, BTC);
2053 if (CR.CaseBB == CurMBB)
2054 visitBitTestHeader(BTB);
2056 BitTestCases.push_back(BTB);
2061 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2062 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2063 const SwitchInst& SI) {
2066 // Start with "simple" cases
2067 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2068 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2069 Cases.push_back(Case(SI.getSuccessorValue(i),
2070 SI.getSuccessorValue(i),
2073 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2075 // Merge case into clusters
2076 if (Cases.size() >= 2)
2077 // Must recompute end() each iteration because it may be
2078 // invalidated by erase if we hold on to it
2079 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2080 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2081 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2082 MachineBasicBlock* nextBB = J->BB;
2083 MachineBasicBlock* currentBB = I->BB;
2085 // If the two neighboring cases go to the same destination, merge them
2086 // into a single case.
2087 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2095 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2096 if (I->Low != I->High)
2097 // A range counts double, since it requires two compares.
2104 void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
2105 // Figure out which block is immediately after the current one.
2106 MachineBasicBlock *NextBlock = 0;
2107 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2109 // If there is only the default destination, branch to it if it is not the
2110 // next basic block. Otherwise, just fall through.
2111 if (SI.getNumOperands() == 2) {
2112 // Update machine-CFG edges.
2114 // If this is not a fall-through branch, emit the branch.
2115 CurMBB->addSuccessor(Default);
2116 if (Default != NextBlock) {
2117 SDValue Res = DAG.getNode(ISD::BR, getCurDebugLoc(),
2118 MVT::Other, getControlRoot(),
2119 DAG.getBasicBlock(Default));
2122 if (DisableScheduling)
2123 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2129 // If there are any non-default case statements, create a vector of Cases
2130 // representing each one, and sort the vector so that we can efficiently
2131 // create a binary search tree from them.
2133 size_t numCmps = Clusterify(Cases, SI);
2134 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2135 << ". Total compares: " << numCmps << '\n');
2138 // Get the Value to be switched on and default basic blocks, which will be
2139 // inserted into CaseBlock records, representing basic blocks in the binary
2141 Value *SV = SI.getOperand(0);
2143 // Push the initial CaseRec onto the worklist
2144 CaseRecVector WorkList;
2145 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2147 while (!WorkList.empty()) {
2148 // Grab a record representing a case range to process off the worklist
2149 CaseRec CR = WorkList.back();
2150 WorkList.pop_back();
2152 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2155 // If the range has few cases (two or less) emit a series of specific
2157 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2160 // If the switch has more than 5 blocks, and at least 40% dense, and the
2161 // target supports indirect branches, then emit a jump table rather than
2162 // lowering the switch to a binary tree of conditional branches.
2163 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2166 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2167 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2168 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2172 void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
2173 // Update machine-CFG edges.
2174 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2175 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2177 SDValue Res = DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2178 MVT::Other, getControlRoot(),
2179 getValue(I.getAddress()));
2182 if (DisableScheduling)
2183 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2186 void SelectionDAGBuilder::visitFSub(User &I) {
2187 // -0.0 - X --> fneg
2188 const Type *Ty = I.getType();
2189 if (isa<VectorType>(Ty)) {
2190 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2191 const VectorType *DestTy = cast<VectorType>(I.getType());
2192 const Type *ElTy = DestTy->getElementType();
2193 unsigned VL = DestTy->getNumElements();
2194 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2195 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2197 SDValue Op2 = getValue(I.getOperand(1));
2198 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2199 Op2.getValueType(), Op2);
2202 if (DisableScheduling)
2203 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2210 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2211 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2212 SDValue Op2 = getValue(I.getOperand(1));
2213 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2214 Op2.getValueType(), Op2);
2217 if (DisableScheduling)
2218 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2223 visitBinary(I, ISD::FSUB);
2226 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
2227 SDValue Op1 = getValue(I.getOperand(0));
2228 SDValue Op2 = getValue(I.getOperand(1));
2229 SDValue Res = DAG.getNode(OpCode, getCurDebugLoc(),
2230 Op1.getValueType(), Op1, Op2);
2233 if (DisableScheduling)
2234 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2237 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
2238 SDValue Op1 = getValue(I.getOperand(0));
2239 SDValue Op2 = getValue(I.getOperand(1));
2240 if (!isa<VectorType>(I.getType()) &&
2241 Op2.getValueType() != TLI.getShiftAmountTy()) {
2242 // If the operand is smaller than the shift count type, promote it.
2243 EVT PTy = TLI.getPointerTy();
2244 EVT STy = TLI.getShiftAmountTy();
2245 if (STy.bitsGT(Op2.getValueType()))
2246 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2247 TLI.getShiftAmountTy(), Op2);
2248 // If the operand is larger than the shift count type but the shift
2249 // count type has enough bits to represent any shift value, truncate
2250 // it now. This is a common case and it exposes the truncate to
2251 // optimization early.
2252 else if (STy.getSizeInBits() >=
2253 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2254 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2255 TLI.getShiftAmountTy(), Op2);
2256 // Otherwise we'll need to temporarily settle for some other
2257 // convenient type; type legalization will make adjustments as
2259 else if (PTy.bitsLT(Op2.getValueType()))
2260 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2261 TLI.getPointerTy(), Op2);
2262 else if (PTy.bitsGT(Op2.getValueType()))
2263 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2264 TLI.getPointerTy(), Op2);
2267 SDValue Res = DAG.getNode(Opcode, getCurDebugLoc(),
2268 Op1.getValueType(), Op1, Op2);
2271 if (DisableScheduling) {
2272 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
2273 DAG.AssignOrdering(Op2.getNode(), SDNodeOrder);
2274 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2278 void SelectionDAGBuilder::visitICmp(User &I) {
2279 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2280 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2281 predicate = IC->getPredicate();
2282 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2283 predicate = ICmpInst::Predicate(IC->getPredicate());
2284 SDValue Op1 = getValue(I.getOperand(0));
2285 SDValue Op2 = getValue(I.getOperand(1));
2286 ISD::CondCode Opcode = getICmpCondCode(predicate);
2288 EVT DestVT = TLI.getValueType(I.getType());
2289 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode);
2292 if (DisableScheduling)
2293 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2296 void SelectionDAGBuilder::visitFCmp(User &I) {
2297 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2298 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2299 predicate = FC->getPredicate();
2300 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2301 predicate = FCmpInst::Predicate(FC->getPredicate());
2302 SDValue Op1 = getValue(I.getOperand(0));
2303 SDValue Op2 = getValue(I.getOperand(1));
2304 ISD::CondCode Condition = getFCmpCondCode(predicate);
2305 EVT DestVT = TLI.getValueType(I.getType());
2306 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition);
2309 if (DisableScheduling)
2310 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2313 void SelectionDAGBuilder::visitSelect(User &I) {
2314 SmallVector<EVT, 4> ValueVTs;
2315 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2316 unsigned NumValues = ValueVTs.size();
2317 if (NumValues == 0) return;
2319 SmallVector<SDValue, 4> Values(NumValues);
2320 SDValue Cond = getValue(I.getOperand(0));
2321 SDValue TrueVal = getValue(I.getOperand(1));
2322 SDValue FalseVal = getValue(I.getOperand(2));
2324 for (unsigned i = 0; i != NumValues; ++i) {
2325 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2326 TrueVal.getNode()->getValueType(i), Cond,
2327 SDValue(TrueVal.getNode(),
2328 TrueVal.getResNo() + i),
2329 SDValue(FalseVal.getNode(),
2330 FalseVal.getResNo() + i));
2332 if (DisableScheduling)
2333 DAG.AssignOrdering(Values[i].getNode(), SDNodeOrder);
2336 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2337 DAG.getVTList(&ValueVTs[0], NumValues),
2338 &Values[0], NumValues);
2341 if (DisableScheduling)
2342 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2345 void SelectionDAGBuilder::visitTrunc(User &I) {
2346 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2347 SDValue N = getValue(I.getOperand(0));
2348 EVT DestVT = TLI.getValueType(I.getType());
2349 SDValue Res = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2352 if (DisableScheduling)
2353 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2356 void SelectionDAGBuilder::visitZExt(User &I) {
2357 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2358 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2359 SDValue N = getValue(I.getOperand(0));
2360 EVT DestVT = TLI.getValueType(I.getType());
2361 SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2364 if (DisableScheduling)
2365 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2368 void SelectionDAGBuilder::visitSExt(User &I) {
2369 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2370 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2371 SDValue N = getValue(I.getOperand(0));
2372 EVT DestVT = TLI.getValueType(I.getType());
2373 SDValue Res = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N);
2376 if (DisableScheduling)
2377 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2380 void SelectionDAGBuilder::visitFPTrunc(User &I) {
2381 // FPTrunc is never a no-op cast, no need to check
2382 SDValue N = getValue(I.getOperand(0));
2383 EVT DestVT = TLI.getValueType(I.getType());
2384 SDValue Res = DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2385 DestVT, N, DAG.getIntPtrConstant(0));
2388 if (DisableScheduling)
2389 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2392 void SelectionDAGBuilder::visitFPExt(User &I){
2393 // FPTrunc is never a no-op cast, no need to check
2394 SDValue N = getValue(I.getOperand(0));
2395 EVT DestVT = TLI.getValueType(I.getType());
2396 SDValue Res = DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N);
2399 if (DisableScheduling)
2400 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2403 void SelectionDAGBuilder::visitFPToUI(User &I) {
2404 // FPToUI is never a no-op cast, no need to check
2405 SDValue N = getValue(I.getOperand(0));
2406 EVT DestVT = TLI.getValueType(I.getType());
2407 SDValue Res = DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N);
2410 if (DisableScheduling)
2411 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2414 void SelectionDAGBuilder::visitFPToSI(User &I) {
2415 // FPToSI is never a no-op cast, no need to check
2416 SDValue N = getValue(I.getOperand(0));
2417 EVT DestVT = TLI.getValueType(I.getType());
2418 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N);
2421 if (DisableScheduling)
2422 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2425 void SelectionDAGBuilder::visitUIToFP(User &I) {
2426 // UIToFP is never a no-op cast, no need to check
2427 SDValue N = getValue(I.getOperand(0));
2428 EVT DestVT = TLI.getValueType(I.getType());
2429 SDValue Res = DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N);
2432 if (DisableScheduling)
2433 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2436 void SelectionDAGBuilder::visitSIToFP(User &I){
2437 // SIToFP is never a no-op cast, no need to check
2438 SDValue N = getValue(I.getOperand(0));
2439 EVT DestVT = TLI.getValueType(I.getType());
2440 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N);
2443 if (DisableScheduling)
2444 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2447 void SelectionDAGBuilder::visitPtrToInt(User &I) {
2448 // What to do depends on the size of the integer and the size of the pointer.
2449 // We can either truncate, zero extend, or no-op, accordingly.
2450 SDValue N = getValue(I.getOperand(0));
2451 EVT SrcVT = N.getValueType();
2452 EVT DestVT = TLI.getValueType(I.getType());
2453 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2456 if (DisableScheduling)
2457 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2460 void SelectionDAGBuilder::visitIntToPtr(User &I) {
2461 // What to do depends on the size of the integer and the size of the pointer.
2462 // We can either truncate, zero extend, or no-op, accordingly.
2463 SDValue N = getValue(I.getOperand(0));
2464 EVT SrcVT = N.getValueType();
2465 EVT DestVT = TLI.getValueType(I.getType());
2466 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2469 if (DisableScheduling)
2470 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2473 void SelectionDAGBuilder::visitBitCast(User &I) {
2474 SDValue N = getValue(I.getOperand(0));
2475 EVT DestVT = TLI.getValueType(I.getType());
2477 // BitCast assures us that source and destination are the same size so this is
2478 // either a BIT_CONVERT or a no-op.
2479 if (DestVT != N.getValueType()) {
2480 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2481 DestVT, N); // convert types.
2484 if (DisableScheduling)
2485 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2487 setValue(&I, N); // noop cast.
2491 void SelectionDAGBuilder::visitInsertElement(User &I) {
2492 SDValue InVec = getValue(I.getOperand(0));
2493 SDValue InVal = getValue(I.getOperand(1));
2494 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2496 getValue(I.getOperand(2)));
2497 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2498 TLI.getValueType(I.getType()),
2499 InVec, InVal, InIdx);
2502 if (DisableScheduling) {
2503 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder);
2504 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2508 void SelectionDAGBuilder::visitExtractElement(User &I) {
2509 SDValue InVec = getValue(I.getOperand(0));
2510 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2512 getValue(I.getOperand(1)));
2513 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2514 TLI.getValueType(I.getType()), InVec, InIdx);
2517 if (DisableScheduling) {
2518 DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder);
2519 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2524 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2525 // from SIndx and increasing to the element length (undefs are allowed).
2526 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2527 unsigned MaskNumElts = Mask.size();
2528 for (unsigned i = 0; i != MaskNumElts; ++i)
2529 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2534 void SelectionDAGBuilder::visitShuffleVector(User &I) {
2535 SmallVector<int, 8> Mask;
2536 SDValue Src1 = getValue(I.getOperand(0));
2537 SDValue Src2 = getValue(I.getOperand(1));
2539 // Convert the ConstantVector mask operand into an array of ints, with -1
2540 // representing undef values.
2541 SmallVector<Constant*, 8> MaskElts;
2542 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2544 unsigned MaskNumElts = MaskElts.size();
2545 for (unsigned i = 0; i != MaskNumElts; ++i) {
2546 if (isa<UndefValue>(MaskElts[i]))
2549 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2552 EVT VT = TLI.getValueType(I.getType());
2553 EVT SrcVT = Src1.getValueType();
2554 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2556 if (SrcNumElts == MaskNumElts) {
2557 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2561 if (DisableScheduling)
2562 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2567 // Normalize the shuffle vector since mask and vector length don't match.
2568 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2569 // Mask is longer than the source vectors and is a multiple of the source
2570 // vectors. We can use concatenate vector to make the mask and vectors
2572 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2573 // The shuffle is concatenating two vectors together.
2574 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2578 if (DisableScheduling)
2579 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2584 // Pad both vectors with undefs to make them the same length as the mask.
2585 unsigned NumConcat = MaskNumElts / SrcNumElts;
2586 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2587 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2588 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2590 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2591 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2595 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2596 getCurDebugLoc(), VT,
2597 &MOps1[0], NumConcat);
2598 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2599 getCurDebugLoc(), VT,
2600 &MOps2[0], NumConcat);
2602 // Readjust mask for new input vector length.
2603 SmallVector<int, 8> MappedOps;
2604 for (unsigned i = 0; i != MaskNumElts; ++i) {
2606 if (Idx < (int)SrcNumElts)
2607 MappedOps.push_back(Idx);
2609 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2612 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2616 if (DisableScheduling) {
2617 DAG.AssignOrdering(Src1.getNode(), SDNodeOrder);
2618 DAG.AssignOrdering(Src2.getNode(), SDNodeOrder);
2619 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2625 if (SrcNumElts > MaskNumElts) {
2626 // Analyze the access pattern of the vector to see if we can extract
2627 // two subvectors and do the shuffle. The analysis is done by calculating
2628 // the range of elements the mask access on both vectors.
2629 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2630 int MaxRange[2] = {-1, -1};
2632 for (unsigned i = 0; i != MaskNumElts; ++i) {
2638 if (Idx >= (int)SrcNumElts) {
2642 if (Idx > MaxRange[Input])
2643 MaxRange[Input] = Idx;
2644 if (Idx < MinRange[Input])
2645 MinRange[Input] = Idx;
2648 // Check if the access is smaller than the vector size and can we find
2649 // a reasonable extract index.
2650 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2651 int StartIdx[2]; // StartIdx to extract from
2652 for (int Input=0; Input < 2; ++Input) {
2653 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2654 RangeUse[Input] = 0; // Unused
2655 StartIdx[Input] = 0;
2656 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2657 // Fits within range but we should see if we can find a good
2658 // start index that is a multiple of the mask length.
2659 if (MaxRange[Input] < (int)MaskNumElts) {
2660 RangeUse[Input] = 1; // Extract from beginning of the vector
2661 StartIdx[Input] = 0;
2663 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2664 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2665 StartIdx[Input] + MaskNumElts < SrcNumElts)
2666 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2671 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2672 SDValue Res = DAG.getUNDEF(VT);
2673 setValue(&I, Res); // Vectors are not used.
2675 if (DisableScheduling)
2676 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2680 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2681 // Extract appropriate subvector and generate a vector shuffle
2682 for (int Input=0; Input < 2; ++Input) {
2683 SDValue &Src = Input == 0 ? Src1 : Src2;
2684 if (RangeUse[Input] == 0)
2685 Src = DAG.getUNDEF(VT);
2687 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2688 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2690 if (DisableScheduling)
2691 DAG.AssignOrdering(Src.getNode(), SDNodeOrder);
2694 // Calculate new mask.
2695 SmallVector<int, 8> MappedOps;
2696 for (unsigned i = 0; i != MaskNumElts; ++i) {
2699 MappedOps.push_back(Idx);
2700 else if (Idx < (int)SrcNumElts)
2701 MappedOps.push_back(Idx - StartIdx[0]);
2703 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2706 SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2710 if (DisableScheduling)
2711 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2717 // We can't use either concat vectors or extract subvectors so fall back to
2718 // replacing the shuffle with extract and build vector.
2719 // to insert and build vector.
2720 EVT EltVT = VT.getVectorElementType();
2721 EVT PtrVT = TLI.getPointerTy();
2722 SmallVector<SDValue,8> Ops;
2723 for (unsigned i = 0; i != MaskNumElts; ++i) {
2725 Ops.push_back(DAG.getUNDEF(EltVT));
2730 if (Idx < (int)SrcNumElts)
2731 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2732 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2734 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2736 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2740 if (DisableScheduling)
2741 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2745 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2746 VT, &Ops[0], Ops.size());
2749 if (DisableScheduling)
2750 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2753 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
2754 const Value *Op0 = I.getOperand(0);
2755 const Value *Op1 = I.getOperand(1);
2756 const Type *AggTy = I.getType();
2757 const Type *ValTy = Op1->getType();
2758 bool IntoUndef = isa<UndefValue>(Op0);
2759 bool FromUndef = isa<UndefValue>(Op1);
2761 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2762 I.idx_begin(), I.idx_end());
2764 SmallVector<EVT, 4> AggValueVTs;
2765 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2766 SmallVector<EVT, 4> ValValueVTs;
2767 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2769 unsigned NumAggValues = AggValueVTs.size();
2770 unsigned NumValValues = ValValueVTs.size();
2771 SmallVector<SDValue, 4> Values(NumAggValues);
2773 SDValue Agg = getValue(Op0);
2774 SDValue Val = getValue(Op1);
2776 // Copy the beginning value(s) from the original aggregate.
2777 for (; i != LinearIndex; ++i)
2778 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2779 SDValue(Agg.getNode(), Agg.getResNo() + i);
2780 // Copy values from the inserted value(s).
2781 for (; i != LinearIndex + NumValValues; ++i)
2782 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2783 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2784 // Copy remaining value(s) from the original aggregate.
2785 for (; i != NumAggValues; ++i)
2786 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2787 SDValue(Agg.getNode(), Agg.getResNo() + i);
2789 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2790 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2791 &Values[0], NumAggValues);
2794 if (DisableScheduling)
2795 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2798 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
2799 const Value *Op0 = I.getOperand(0);
2800 const Type *AggTy = Op0->getType();
2801 const Type *ValTy = I.getType();
2802 bool OutOfUndef = isa<UndefValue>(Op0);
2804 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2805 I.idx_begin(), I.idx_end());
2807 SmallVector<EVT, 4> ValValueVTs;
2808 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2810 unsigned NumValValues = ValValueVTs.size();
2811 SmallVector<SDValue, 4> Values(NumValValues);
2813 SDValue Agg = getValue(Op0);
2814 // Copy out the selected value(s).
2815 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2816 Values[i - LinearIndex] =
2818 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2819 SDValue(Agg.getNode(), Agg.getResNo() + i);
2821 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2822 DAG.getVTList(&ValValueVTs[0], NumValValues),
2823 &Values[0], NumValValues);
2826 if (DisableScheduling)
2827 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2830 void SelectionDAGBuilder::visitGetElementPtr(User &I) {
2831 SDValue N = getValue(I.getOperand(0));
2832 const Type *Ty = I.getOperand(0)->getType();
2834 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2837 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2838 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2841 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2842 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2843 DAG.getIntPtrConstant(Offset));
2845 if (DisableScheduling)
2846 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2849 Ty = StTy->getElementType(Field);
2851 Ty = cast<SequentialType>(Ty)->getElementType();
2853 // If this is a constant subscript, handle it quickly.
2854 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2855 if (CI->getZExtValue() == 0) continue;
2857 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2859 EVT PTy = TLI.getPointerTy();
2860 unsigned PtrBits = PTy.getSizeInBits();
2862 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2864 DAG.getConstant(Offs, MVT::i64));
2866 OffsVal = DAG.getIntPtrConstant(Offs);
2868 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2871 if (DisableScheduling) {
2872 DAG.AssignOrdering(OffsVal.getNode(), SDNodeOrder);
2873 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2879 // N = N + Idx * ElementSize;
2880 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2881 TD->getTypeAllocSize(Ty));
2882 SDValue IdxN = getValue(Idx);
2884 // If the index is smaller or larger than intptr_t, truncate or extend
2886 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2888 // If this is a multiply by a power of two, turn it into a shl
2889 // immediately. This is a very common case.
2890 if (ElementSize != 1) {
2891 if (ElementSize.isPowerOf2()) {
2892 unsigned Amt = ElementSize.logBase2();
2893 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2894 N.getValueType(), IdxN,
2895 DAG.getConstant(Amt, TLI.getPointerTy()));
2897 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2898 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2899 N.getValueType(), IdxN, Scale);
2902 if (DisableScheduling)
2903 DAG.AssignOrdering(IdxN.getNode(), SDNodeOrder);
2906 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2907 N.getValueType(), N, IdxN);
2909 if (DisableScheduling)
2910 DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2917 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
2918 // If this is a fixed sized alloca in the entry block of the function,
2919 // allocate it statically on the stack.
2920 if (FuncInfo.StaticAllocaMap.count(&I))
2921 return; // getValue will auto-populate this.
2923 const Type *Ty = I.getAllocatedType();
2924 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2926 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2929 SDValue AllocSize = getValue(I.getArraySize());
2931 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2933 DAG.getConstant(TySize, AllocSize.getValueType()));
2935 if (DisableScheduling)
2936 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2938 EVT IntPtr = TLI.getPointerTy();
2939 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2941 if (DisableScheduling)
2942 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2944 // Handle alignment. If the requested alignment is less than or equal to
2945 // the stack alignment, ignore it. If the size is greater than or equal to
2946 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2947 unsigned StackAlign =
2948 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2949 if (Align <= StackAlign)
2952 // Round the size of the allocation up to the stack alignment size
2953 // by add SA-1 to the size.
2954 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2955 AllocSize.getValueType(), AllocSize,
2956 DAG.getIntPtrConstant(StackAlign-1));
2957 if (DisableScheduling)
2958 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2960 // Mask out the low bits for alignment purposes.
2961 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2962 AllocSize.getValueType(), AllocSize,
2963 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2964 if (DisableScheduling)
2965 DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2967 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2968 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2969 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2972 DAG.setRoot(DSA.getValue(1));
2974 if (DisableScheduling)
2975 DAG.AssignOrdering(DSA.getNode(), SDNodeOrder);
2977 // Inform the Frame Information that we have just allocated a variable-sized
2979 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2982 void SelectionDAGBuilder::visitLoad(LoadInst &I) {
2983 const Value *SV = I.getOperand(0);
2984 SDValue Ptr = getValue(SV);
2986 const Type *Ty = I.getType();
2987 bool isVolatile = I.isVolatile();
2988 unsigned Alignment = I.getAlignment();
2990 SmallVector<EVT, 4> ValueVTs;
2991 SmallVector<uint64_t, 4> Offsets;
2992 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2993 unsigned NumValues = ValueVTs.size();
2998 bool ConstantMemory = false;
3000 // Serialize volatile loads with other side effects.
3002 else if (AA->pointsToConstantMemory(SV)) {
3003 // Do not serialize (non-volatile) loads of constant memory with anything.
3004 Root = DAG.getEntryNode();
3005 ConstantMemory = true;
3007 // Do not serialize non-volatile loads against each other.
3008 Root = DAG.getRoot();
3011 SmallVector<SDValue, 4> Values(NumValues);
3012 SmallVector<SDValue, 4> Chains(NumValues);
3013 EVT PtrVT = Ptr.getValueType();
3014 for (unsigned i = 0; i != NumValues; ++i) {
3015 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3017 DAG.getConstant(Offsets[i], PtrVT));
3018 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
3019 A, SV, Offsets[i], isVolatile, Alignment);
3022 Chains[i] = L.getValue(1);
3024 if (DisableScheduling) {
3025 DAG.AssignOrdering(A.getNode(), SDNodeOrder);
3026 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
3030 if (!ConstantMemory) {
3031 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3032 MVT::Other, &Chains[0], NumValues);
3036 PendingLoads.push_back(Chain);
3038 if (DisableScheduling)
3039 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
3042 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3043 DAG.getVTList(&ValueVTs[0], NumValues),
3044 &Values[0], NumValues);
3047 if (DisableScheduling)
3048 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
3051 void SelectionDAGBuilder::visitStore(StoreInst &I) {
3052 Value *SrcV = I.getOperand(0);
3053 Value *PtrV = I.getOperand(1);
3055 SmallVector<EVT, 4> ValueVTs;
3056 SmallVector<uint64_t, 4> Offsets;
3057 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3058 unsigned NumValues = ValueVTs.size();
3062 // Get the lowered operands. Note that we do this after
3063 // checking if NumResults is zero, because with zero results
3064 // the operands won't have values in the map.
3065 SDValue Src = getValue(SrcV);
3066 SDValue Ptr = getValue(PtrV);
3068 SDValue Root = getRoot();
3069 SmallVector<SDValue, 4> Chains(NumValues);
3070 EVT PtrVT = Ptr.getValueType();
3071 bool isVolatile = I.isVolatile();
3072 unsigned Alignment = I.getAlignment();
3074 for (unsigned i = 0; i != NumValues; ++i) {
3075 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3076 DAG.getConstant(Offsets[i], PtrVT));
3077 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
3078 SDValue(Src.getNode(), Src.getResNo() + i),
3079 Add, PtrV, Offsets[i], isVolatile, Alignment);
3081 if (DisableScheduling) {
3082 DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
3083 DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder);
3087 SDValue Res = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3088 MVT::Other, &Chains[0], NumValues);
3091 if (DisableScheduling)
3092 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
3095 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3097 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
3098 unsigned Intrinsic) {
3099 bool HasChain = !I.doesNotAccessMemory();
3100 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3102 // Build the operand list.
3103 SmallVector<SDValue, 8> Ops;
3104 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3106 // We don't need to serialize loads against other loads.
3107 Ops.push_back(DAG.getRoot());
3109 Ops.push_back(getRoot());
3113 // Info is set by getTgtMemInstrinsic
3114 TargetLowering::IntrinsicInfo Info;
3115 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3117 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3118 if (!IsTgtIntrinsic)
3119 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3121 // Add all operands of the call to the operand list.
3122 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3123 SDValue Op = getValue(I.getOperand(i));
3124 assert(TLI.isTypeLegal(Op.getValueType()) &&
3125 "Intrinsic uses a non-legal type?");
3129 SmallVector<EVT, 4> ValueVTs;
3130 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3132 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3133 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3134 "Intrinsic uses a non-legal type?");
3139 ValueVTs.push_back(MVT::Other);
3141 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3145 if (IsTgtIntrinsic) {
3146 // This is target intrinsic that touches memory
3147 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3148 VTs, &Ops[0], Ops.size(),
3149 Info.memVT, Info.ptrVal, Info.offset,
3150 Info.align, Info.vol,
3151 Info.readMem, Info.writeMem);
3152 } else if (!HasChain) {
3153 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3154 VTs, &Ops[0], Ops.size());
3155 } else if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
3156 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3157 VTs, &Ops[0], Ops.size());
3159 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3160 VTs, &Ops[0], Ops.size());
3163 if (DisableScheduling)
3164 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3167 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3169 PendingLoads.push_back(Chain);
3174 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
3175 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3176 EVT VT = TLI.getValueType(PTy);
3177 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
3179 if (DisableScheduling)
3180 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3183 setValue(&I, Result);
3187 /// GetSignificand - Get the significand and build it into a floating-point
3188 /// number with exponent of 1:
3190 /// Op = (Op & 0x007fffff) | 0x3f800000;
3192 /// where Op is the hexidecimal representation of floating point value.
3194 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
3195 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3196 DAG.getConstant(0x007fffff, MVT::i32));
3197 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3198 DAG.getConstant(0x3f800000, MVT::i32));
3199 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3201 if (DisableScheduling) {
3202 DAG.AssignOrdering(t1.getNode(), Order);
3203 DAG.AssignOrdering(t2.getNode(), Order);
3204 DAG.AssignOrdering(Res.getNode(), Order);
3210 /// GetExponent - Get the exponent:
3212 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3214 /// where Op is the hexidecimal representation of floating point value.
3216 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3217 DebugLoc dl, unsigned Order) {
3218 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3219 DAG.getConstant(0x7f800000, MVT::i32));
3220 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3221 DAG.getConstant(23, TLI.getPointerTy()));
3222 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3223 DAG.getConstant(127, MVT::i32));
3224 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3226 if (DisableScheduling) {
3227 DAG.AssignOrdering(t0.getNode(), Order);
3228 DAG.AssignOrdering(t1.getNode(), Order);
3229 DAG.AssignOrdering(t2.getNode(), Order);
3230 DAG.AssignOrdering(Res.getNode(), Order);
3236 /// getF32Constant - Get 32-bit floating point constant.
3238 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3239 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3242 /// Inlined utility function to implement binary input atomic intrinsics for
3243 /// visitIntrinsicCall: I is a call instruction
3244 /// Op is the associated NodeType for I
3246 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3247 SDValue Root = getRoot();
3249 DAG.getAtomic(Op, getCurDebugLoc(),
3250 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3252 getValue(I.getOperand(1)),
3253 getValue(I.getOperand(2)),
3256 DAG.setRoot(L.getValue(1));
3258 if (DisableScheduling)
3259 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
3264 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3266 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3267 SDValue Op1 = getValue(I.getOperand(1));
3268 SDValue Op2 = getValue(I.getOperand(2));
3270 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3271 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
3273 setValue(&I, Result);
3275 if (DisableScheduling)
3276 DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3281 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3282 /// limited-precision mode.
3284 SelectionDAGBuilder::visitExp(CallInst &I) {
3286 DebugLoc dl = getCurDebugLoc();
3288 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3289 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3290 SDValue Op = getValue(I.getOperand(1));
3292 // Put the exponent in the right bit position for later addition to the
3295 // #define LOG2OFe 1.4426950f
3296 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3297 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3298 getF32Constant(DAG, 0x3fb8aa3b));
3299 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3301 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3302 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3303 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3305 if (DisableScheduling) {
3306 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3307 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3308 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3309 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
3312 // IntegerPartOfX <<= 23;
3313 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3314 DAG.getConstant(23, TLI.getPointerTy()));
3316 if (DisableScheduling)
3317 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3319 if (LimitFloatPrecision <= 6) {
3320 // For floating-point precision of 6:
3322 // TwoToFractionalPartOfX =
3324 // (0.735607626f + 0.252464424f * x) * x;
3326 // error 0.0144103317, which is 6 bits
3327 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3328 getF32Constant(DAG, 0x3e814304));
3329 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3330 getF32Constant(DAG, 0x3f3c50c8));
3331 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3332 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3333 getF32Constant(DAG, 0x3f7f5e7e));
3334 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3336 // Add the exponent into the result in integer domain.
3337 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3338 TwoToFracPartOfX, IntegerPartOfX);
3340 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3342 if (DisableScheduling) {
3343 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3344 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3345 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3346 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3347 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3348 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3349 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3351 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3352 // For floating-point precision of 12:
3354 // TwoToFractionalPartOfX =
3357 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3359 // 0.000107046256 error, which is 13 to 14 bits
3360 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3361 getF32Constant(DAG, 0x3da235e3));
3362 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3363 getF32Constant(DAG, 0x3e65b8f3));
3364 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3365 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3366 getF32Constant(DAG, 0x3f324b07));
3367 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3368 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3369 getF32Constant(DAG, 0x3f7ff8fd));
3370 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3372 // Add the exponent into the result in integer domain.
3373 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3374 TwoToFracPartOfX, IntegerPartOfX);
3376 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3378 if (DisableScheduling) {
3379 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3380 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3381 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3382 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3383 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3384 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3385 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3386 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3387 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3389 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3390 // For floating-point precision of 18:
3392 // TwoToFractionalPartOfX =
3396 // (0.554906021e-1f +
3397 // (0.961591928e-2f +
3398 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3400 // error 2.47208000*10^(-7), which is better than 18 bits
3401 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3402 getF32Constant(DAG, 0x3924b03e));
3403 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3404 getF32Constant(DAG, 0x3ab24b87));
3405 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3406 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3407 getF32Constant(DAG, 0x3c1d8c17));
3408 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3409 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3410 getF32Constant(DAG, 0x3d634a1d));
3411 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3412 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3413 getF32Constant(DAG, 0x3e75fe14));
3414 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3415 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3416 getF32Constant(DAG, 0x3f317234));
3417 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3418 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3419 getF32Constant(DAG, 0x3f800000));
3420 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3423 // Add the exponent into the result in integer domain.
3424 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3425 TwoToFracPartOfX, IntegerPartOfX);
3427 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3429 if (DisableScheduling) {
3430 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3431 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3432 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3433 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3434 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3435 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3436 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3437 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3438 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3439 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
3440 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
3441 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
3442 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
3443 DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3444 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3448 // No special expansion.
3449 result = DAG.getNode(ISD::FEXP, dl,
3450 getValue(I.getOperand(1)).getValueType(),
3451 getValue(I.getOperand(1)));
3452 if (DisableScheduling)
3453 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3456 setValue(&I, result);
3459 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3460 /// limited-precision mode.
3462 SelectionDAGBuilder::visitLog(CallInst &I) {
3464 DebugLoc dl = getCurDebugLoc();
3466 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3467 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3468 SDValue Op = getValue(I.getOperand(1));
3469 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3471 if (DisableScheduling)
3472 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3474 // Scale the exponent by log(2) [0.69314718f].
3475 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3476 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3477 getF32Constant(DAG, 0x3f317218));
3479 if (DisableScheduling)
3480 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3482 // Get the significand and build it into a floating-point number with
3484 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3486 if (LimitFloatPrecision <= 6) {
3487 // For floating-point precision of 6:
3491 // (1.4034025f - 0.23903021f * x) * x;
3493 // error 0.0034276066, which is better than 8 bits
3494 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3495 getF32Constant(DAG, 0xbe74c456));
3496 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3497 getF32Constant(DAG, 0x3fb3a2b1));
3498 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3499 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3500 getF32Constant(DAG, 0x3f949a29));
3502 result = DAG.getNode(ISD::FADD, dl,
3503 MVT::f32, LogOfExponent, LogOfMantissa);
3505 if (DisableScheduling) {
3506 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3507 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3508 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3509 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3510 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3512 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3513 // For floating-point precision of 12:
3519 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3521 // error 0.000061011436, which is 14 bits
3522 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3523 getF32Constant(DAG, 0xbd67b6d6));
3524 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3525 getF32Constant(DAG, 0x3ee4f4b8));
3526 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3527 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3528 getF32Constant(DAG, 0x3fbc278b));
3529 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3530 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3531 getF32Constant(DAG, 0x40348e95));
3532 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3533 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3534 getF32Constant(DAG, 0x3fdef31a));
3536 result = DAG.getNode(ISD::FADD, dl,
3537 MVT::f32, LogOfExponent, LogOfMantissa);
3539 if (DisableScheduling) {
3540 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3541 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3542 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3543 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3544 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3545 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3546 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3547 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3548 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3550 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3551 // For floating-point precision of 18:
3559 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3561 // error 0.0000023660568, which is better than 18 bits
3562 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3563 getF32Constant(DAG, 0xbc91e5ac));
3564 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3565 getF32Constant(DAG, 0x3e4350aa));
3566 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3567 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3568 getF32Constant(DAG, 0x3f60d3e3));
3569 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3570 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3571 getF32Constant(DAG, 0x4011cdf0));
3572 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3573 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3574 getF32Constant(DAG, 0x406cfd1c));
3575 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3576 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3577 getF32Constant(DAG, 0x408797cb));
3578 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3579 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3580 getF32Constant(DAG, 0x4006dcab));
3582 result = DAG.getNode(ISD::FADD, dl,
3583 MVT::f32, LogOfExponent, LogOfMantissa);
3585 if (DisableScheduling) {
3586 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3587 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3588 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3589 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3590 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3591 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3592 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3593 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3594 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3595 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3596 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3597 DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3598 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3602 // No special expansion.
3603 result = DAG.getNode(ISD::FLOG, dl,
3604 getValue(I.getOperand(1)).getValueType(),
3605 getValue(I.getOperand(1)));
3607 if (DisableScheduling)
3608 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3611 setValue(&I, result);
3614 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3615 /// limited-precision mode.
3617 SelectionDAGBuilder::visitLog2(CallInst &I) {
3619 DebugLoc dl = getCurDebugLoc();
3621 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3622 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3623 SDValue Op = getValue(I.getOperand(1));
3624 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3626 if (DisableScheduling)
3627 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3629 // Get the exponent.
3630 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3632 if (DisableScheduling)
3633 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3635 // Get the significand and build it into a floating-point number with
3637 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3639 // Different possible minimax approximations of significand in
3640 // floating-point for various degrees of accuracy over [1,2].
3641 if (LimitFloatPrecision <= 6) {
3642 // For floating-point precision of 6:
3644 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3646 // error 0.0049451742, which is more than 7 bits
3647 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3648 getF32Constant(DAG, 0xbeb08fe0));
3649 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3650 getF32Constant(DAG, 0x40019463));
3651 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3652 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3653 getF32Constant(DAG, 0x3fd6633d));
3655 result = DAG.getNode(ISD::FADD, dl,
3656 MVT::f32, LogOfExponent, Log2ofMantissa);
3658 if (DisableScheduling) {
3659 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3660 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3661 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3662 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3663 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3665 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3666 // For floating-point precision of 12:
3672 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3674 // error 0.0000876136000, which is better than 13 bits
3675 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3676 getF32Constant(DAG, 0xbda7262e));
3677 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3678 getF32Constant(DAG, 0x3f25280b));
3679 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3680 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3681 getF32Constant(DAG, 0x4007b923));
3682 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3683 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3684 getF32Constant(DAG, 0x40823e2f));
3685 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3686 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3687 getF32Constant(DAG, 0x4020d29c));
3689 result = DAG.getNode(ISD::FADD, dl,
3690 MVT::f32, LogOfExponent, Log2ofMantissa);
3692 if (DisableScheduling) {
3693 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3694 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3695 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3696 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3697 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3698 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3699 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3700 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3701 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3703 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3704 // For floating-point precision of 18:
3713 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3715 // error 0.0000018516, which is better than 18 bits
3716 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3717 getF32Constant(DAG, 0xbcd2769e));
3718 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3719 getF32Constant(DAG, 0x3e8ce0b9));
3720 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3721 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3722 getF32Constant(DAG, 0x3fa22ae7));
3723 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3724 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3725 getF32Constant(DAG, 0x40525723));
3726 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3727 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3728 getF32Constant(DAG, 0x40aaf200));
3729 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3730 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3731 getF32Constant(DAG, 0x40c39dad));
3732 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3733 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3734 getF32Constant(DAG, 0x4042902c));
3736 result = DAG.getNode(ISD::FADD, dl,
3737 MVT::f32, LogOfExponent, Log2ofMantissa);
3739 if (DisableScheduling) {
3740 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3741 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3742 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3743 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3744 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3745 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3746 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3747 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3748 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3749 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3750 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3751 DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3752 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3756 // No special expansion.
3757 result = DAG.getNode(ISD::FLOG2, dl,
3758 getValue(I.getOperand(1)).getValueType(),
3759 getValue(I.getOperand(1)));
3761 if (DisableScheduling)
3762 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3765 setValue(&I, result);
3768 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3769 /// limited-precision mode.
3771 SelectionDAGBuilder::visitLog10(CallInst &I) {
3773 DebugLoc dl = getCurDebugLoc();
3775 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3776 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3777 SDValue Op = getValue(I.getOperand(1));
3778 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3780 if (DisableScheduling)
3781 DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3783 // Scale the exponent by log10(2) [0.30102999f].
3784 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3785 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3786 getF32Constant(DAG, 0x3e9a209a));
3788 if (DisableScheduling)
3789 DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3791 // Get the significand and build it into a floating-point number with
3793 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3795 if (LimitFloatPrecision <= 6) {
3796 // For floating-point precision of 6:
3798 // Log10ofMantissa =
3800 // (0.60948995f - 0.10380950f * x) * x;
3802 // error 0.0014886165, which is 6 bits
3803 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3804 getF32Constant(DAG, 0xbdd49a13));
3805 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3806 getF32Constant(DAG, 0x3f1c0789));
3807 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3808 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3809 getF32Constant(DAG, 0x3f011300));
3811 result = DAG.getNode(ISD::FADD, dl,
3812 MVT::f32, LogOfExponent, Log10ofMantissa);
3814 if (DisableScheduling) {
3815 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3816 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3817 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3818 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3819 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3821 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3822 // For floating-point precision of 12:
3824 // Log10ofMantissa =
3827 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3829 // error 0.00019228036, which is better than 12 bits
3830 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3831 getF32Constant(DAG, 0x3d431f31));
3832 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3833 getF32Constant(DAG, 0x3ea21fb2));
3834 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3835 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3836 getF32Constant(DAG, 0x3f6ae232));
3837 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3838 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3839 getF32Constant(DAG, 0x3f25f7c3));
3841 result = DAG.getNode(ISD::FADD, dl,
3842 MVT::f32, LogOfExponent, Log10ofMantissa);
3844 if (DisableScheduling) {
3845 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3846 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3847 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3848 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3849 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3850 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3851 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3853 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3854 // For floating-point precision of 18:
3856 // Log10ofMantissa =
3861 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3863 // error 0.0000037995730, which is better than 18 bits
3864 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3865 getF32Constant(DAG, 0x3c5d51ce));
3866 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3867 getF32Constant(DAG, 0x3e00685a));
3868 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3869 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3870 getF32Constant(DAG, 0x3efb6798));
3871 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3872 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3873 getF32Constant(DAG, 0x3f88d192));
3874 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3875 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3876 getF32Constant(DAG, 0x3fc4316c));
3877 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3878 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3879 getF32Constant(DAG, 0x3f57ce70));
3881 result = DAG.getNode(ISD::FADD, dl,
3882 MVT::f32, LogOfExponent, Log10ofMantissa);
3884 if (DisableScheduling) {
3885 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3886 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3887 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3888 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3889 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3890 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3891 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3892 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3893 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3894 DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3895 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3899 // No special expansion.
3900 result = DAG.getNode(ISD::FLOG10, dl,
3901 getValue(I.getOperand(1)).getValueType(),
3902 getValue(I.getOperand(1)));
3904 if (DisableScheduling)
3905 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3908 setValue(&I, result);
3911 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3912 /// limited-precision mode.
3914 SelectionDAGBuilder::visitExp2(CallInst &I) {
3916 DebugLoc dl = getCurDebugLoc();
3918 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3919 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3920 SDValue Op = getValue(I.getOperand(1));
3922 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3924 if (DisableScheduling)
3925 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3927 // FractionalPartOfX = x - (float)IntegerPartOfX;
3928 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3929 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3931 // IntegerPartOfX <<= 23;
3932 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3933 DAG.getConstant(23, TLI.getPointerTy()));
3935 if (DisableScheduling) {
3936 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3937 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
3938 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3941 if (LimitFloatPrecision <= 6) {
3942 // For floating-point precision of 6:
3944 // TwoToFractionalPartOfX =
3946 // (0.735607626f + 0.252464424f * x) * x;
3948 // error 0.0144103317, which is 6 bits
3949 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3950 getF32Constant(DAG, 0x3e814304));
3951 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3952 getF32Constant(DAG, 0x3f3c50c8));
3953 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3954 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3955 getF32Constant(DAG, 0x3f7f5e7e));
3956 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3957 SDValue TwoToFractionalPartOfX =
3958 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3960 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3961 MVT::f32, TwoToFractionalPartOfX);
3963 if (DisableScheduling) {
3964 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3965 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3966 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3967 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3968 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3969 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
3970 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3972 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3973 // For floating-point precision of 12:
3975 // TwoToFractionalPartOfX =
3978 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3980 // error 0.000107046256, which is 13 to 14 bits
3981 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3982 getF32Constant(DAG, 0x3da235e3));
3983 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3984 getF32Constant(DAG, 0x3e65b8f3));
3985 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3986 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3987 getF32Constant(DAG, 0x3f324b07));
3988 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3989 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3990 getF32Constant(DAG, 0x3f7ff8fd));
3991 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3992 SDValue TwoToFractionalPartOfX =
3993 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3995 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3996 MVT::f32, TwoToFractionalPartOfX);
3998 if (DisableScheduling) {
3999 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4000 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4001 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4002 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4003 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4004 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4005 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4006 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4007 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4009 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4010 // For floating-point precision of 18:
4012 // TwoToFractionalPartOfX =
4016 // (0.554906021e-1f +
4017 // (0.961591928e-2f +
4018 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4019 // error 2.47208000*10^(-7), which is better than 18 bits
4020 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4021 getF32Constant(DAG, 0x3924b03e));
4022 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4023 getF32Constant(DAG, 0x3ab24b87));
4024 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4025 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4026 getF32Constant(DAG, 0x3c1d8c17));
4027 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4028 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4029 getF32Constant(DAG, 0x3d634a1d));
4030 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4031 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4032 getF32Constant(DAG, 0x3e75fe14));
4033 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4034 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4035 getF32Constant(DAG, 0x3f317234));
4036 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4037 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4038 getF32Constant(DAG, 0x3f800000));
4039 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
4040 SDValue TwoToFractionalPartOfX =
4041 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4043 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4044 MVT::f32, TwoToFractionalPartOfX);
4046 if (DisableScheduling) {
4047 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4048 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4049 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4050 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4051 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4052 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4053 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4054 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
4055 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
4056 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
4057 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
4058 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
4059 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
4060 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4061 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4065 // No special expansion.
4066 result = DAG.getNode(ISD::FEXP2, dl,
4067 getValue(I.getOperand(1)).getValueType(),
4068 getValue(I.getOperand(1)));
4070 if (DisableScheduling)
4071 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4074 setValue(&I, result);
4077 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4078 /// limited-precision mode with x == 10.0f.
4080 SelectionDAGBuilder::visitPow(CallInst &I) {
4082 Value *Val = I.getOperand(1);
4083 DebugLoc dl = getCurDebugLoc();
4084 bool IsExp10 = false;
4086 if (getValue(Val).getValueType() == MVT::f32 &&
4087 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
4088 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4089 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
4090 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
4092 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
4097 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4098 SDValue Op = getValue(I.getOperand(2));
4100 // Put the exponent in the right bit position for later addition to the
4103 // #define LOG2OF10 3.3219281f
4104 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4105 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4106 getF32Constant(DAG, 0x40549a78));
4107 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4109 // FractionalPartOfX = x - (float)IntegerPartOfX;
4110 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4111 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4113 if (DisableScheduling) {
4114 DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
4115 DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
4116 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
4117 DAG.AssignOrdering(X.getNode(), SDNodeOrder);
4120 // IntegerPartOfX <<= 23;
4121 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4122 DAG.getConstant(23, TLI.getPointerTy()));
4124 if (DisableScheduling)
4125 DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
4127 if (LimitFloatPrecision <= 6) {
4128 // For floating-point precision of 6:
4130 // twoToFractionalPartOfX =
4132 // (0.735607626f + 0.252464424f * x) * x;
4134 // error 0.0144103317, which is 6 bits
4135 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4136 getF32Constant(DAG, 0x3e814304));
4137 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4138 getF32Constant(DAG, 0x3f3c50c8));
4139 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4140 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4141 getF32Constant(DAG, 0x3f7f5e7e));
4142 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
4143 SDValue TwoToFractionalPartOfX =
4144 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4146 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4147 MVT::f32, TwoToFractionalPartOfX);
4149 if (DisableScheduling) {
4150 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4151 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4152 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4153 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4154 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4155 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4156 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4158 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4159 // For floating-point precision of 12:
4161 // TwoToFractionalPartOfX =
4164 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4166 // error 0.000107046256, which is 13 to 14 bits
4167 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4168 getF32Constant(DAG, 0x3da235e3));
4169 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4170 getF32Constant(DAG, 0x3e65b8f3));
4171 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4172 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4173 getF32Constant(DAG, 0x3f324b07));
4174 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4175 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4176 getF32Constant(DAG, 0x3f7ff8fd));
4177 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
4178 SDValue TwoToFractionalPartOfX =
4179 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4181 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4182 MVT::f32, TwoToFractionalPartOfX);
4184 if (DisableScheduling) {
4185 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4186 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4187 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4188 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4189 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4190 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4191 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4192 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4193 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4195 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4196 // For floating-point precision of 18:
4198 // TwoToFractionalPartOfX =
4202 // (0.554906021e-1f +
4203 // (0.961591928e-2f +
4204 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4205 // error 2.47208000*10^(-7), which is better than 18 bits
4206 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4207 getF32Constant(DAG, 0x3924b03e));
4208 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4209 getF32Constant(DAG, 0x3ab24b87));
4210 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4211 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4212 getF32Constant(DAG, 0x3c1d8c17));
4213 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4214 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4215 getF32Constant(DAG, 0x3d634a1d));
4216 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4217 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4218 getF32Constant(DAG, 0x3e75fe14));
4219 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4220 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4221 getF32Constant(DAG, 0x3f317234));
4222 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4223 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4224 getF32Constant(DAG, 0x3f800000));
4225 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
4226 SDValue TwoToFractionalPartOfX =
4227 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4229 result = DAG.getNode(ISD::BIT_CONVERT, dl,
4230 MVT::f32, TwoToFractionalPartOfX);
4232 if (DisableScheduling) {
4233 DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4234 DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4235 DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4236 DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4237 DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4238 DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4239 DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4240 DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
4241 DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
4242 DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
4243 DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
4244 DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
4245 DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
4246 DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4247 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4251 // No special expansion.
4252 result = DAG.getNode(ISD::FPOW, dl,
4253 getValue(I.getOperand(1)).getValueType(),
4254 getValue(I.getOperand(1)),
4255 getValue(I.getOperand(2)));
4257 if (DisableScheduling)
4258 DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4261 setValue(&I, result);
4264 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4265 /// we want to emit this as a call to a named external function, return the name
4266 /// otherwise lower it and return null.
4268 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
4269 DebugLoc dl = getCurDebugLoc();
4272 switch (Intrinsic) {
4274 // By default, turn this into a target intrinsic node.
4275 visitTargetIntrinsic(I, Intrinsic);
4277 case Intrinsic::vastart: visitVAStart(I); return 0;
4278 case Intrinsic::vaend: visitVAEnd(I); return 0;
4279 case Intrinsic::vacopy: visitVACopy(I); return 0;
4280 case Intrinsic::returnaddress:
4281 Res = DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4282 getValue(I.getOperand(1)));
4284 if (DisableScheduling)
4285 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4287 case Intrinsic::frameaddress:
4288 Res = DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4289 getValue(I.getOperand(1)));
4291 if (DisableScheduling)
4292 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4294 case Intrinsic::setjmp:
4295 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4296 case Intrinsic::longjmp:
4297 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4298 case Intrinsic::memcpy: {
4299 SDValue Op1 = getValue(I.getOperand(1));
4300 SDValue Op2 = getValue(I.getOperand(2));
4301 SDValue Op3 = getValue(I.getOperand(3));
4302 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4303 Res = DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
4304 I.getOperand(1), 0, I.getOperand(2), 0);
4306 if (DisableScheduling)
4307 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4310 case Intrinsic::memset: {
4311 SDValue Op1 = getValue(I.getOperand(1));
4312 SDValue Op2 = getValue(I.getOperand(2));
4313 SDValue Op3 = getValue(I.getOperand(3));
4314 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4315 Res = DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
4316 I.getOperand(1), 0);
4318 if (DisableScheduling)
4319 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4322 case Intrinsic::memmove: {
4323 SDValue Op1 = getValue(I.getOperand(1));
4324 SDValue Op2 = getValue(I.getOperand(2));
4325 SDValue Op3 = getValue(I.getOperand(3));
4326 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4328 // If the source and destination are known to not be aliases, we can
4329 // lower memmove as memcpy.
4330 uint64_t Size = -1ULL;
4331 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4332 Size = C->getZExtValue();
4333 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4334 AliasAnalysis::NoAlias) {
4335 Res = DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
4336 I.getOperand(1), 0, I.getOperand(2), 0);
4338 if (DisableScheduling)
4339 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4343 Res = DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
4344 I.getOperand(1), 0, I.getOperand(2), 0);
4346 if (DisableScheduling)
4347 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4350 case Intrinsic::dbg_stoppoint:
4351 case Intrinsic::dbg_region_start:
4352 case Intrinsic::dbg_region_end:
4353 case Intrinsic::dbg_func_start:
4354 // FIXME - Remove this instructions once the dust settles.
4356 case Intrinsic::dbg_declare: {
4357 if (OptLevel != CodeGenOpt::None)
4358 // FIXME: Variable debug info is not supported here.
4360 DwarfWriter *DW = DAG.getDwarfWriter();
4363 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4364 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
4367 MDNode *Variable = DI.getVariable();
4368 Value *Address = DI.getAddress();
4369 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4370 Address = BCI->getOperand(0);
4371 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4372 // Don't handle byval struct arguments or VLAs, for example.
4375 DenseMap<const AllocaInst*, int>::iterator SI =
4376 FuncInfo.StaticAllocaMap.find(AI);
4377 if (SI == FuncInfo.StaticAllocaMap.end())
4379 int FI = SI->second;
4381 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4383 MetadataContext &TheMetadata =
4384 DI.getParent()->getContext().getMetadata();
4385 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
4386 MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI);
4387 MMI->setVariableDbgInfo(Variable, FI, Dbg);
4391 case Intrinsic::eh_exception: {
4392 // Insert the EXCEPTIONADDR instruction.
4393 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
4394 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4396 Ops[0] = DAG.getRoot();
4397 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4399 DAG.setRoot(Op.getValue(1));
4400 if (DisableScheduling)
4401 DAG.AssignOrdering(Op.getNode(), SDNodeOrder);
4405 case Intrinsic::eh_selector: {
4406 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4408 if (CurMBB->isLandingPad())
4409 AddCatchInfo(I, MMI, CurMBB);
4412 FuncInfo.CatchInfoLost.insert(&I);
4414 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4415 unsigned Reg = TLI.getExceptionSelectorRegister();
4416 if (Reg) CurMBB->addLiveIn(Reg);
4419 // Insert the EHSELECTION instruction.
4420 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4422 Ops[0] = getValue(I.getOperand(1));
4424 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4426 DAG.setRoot(Op.getValue(1));
4428 Res = DAG.getSExtOrTrunc(Op, dl, MVT::i32);
4430 if (DisableScheduling) {
4431 DAG.AssignOrdering(Op.getNode(), SDNodeOrder);
4432 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4437 case Intrinsic::eh_typeid_for: {
4438 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4441 // Find the type id for the given typeinfo.
4442 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4443 unsigned TypeID = MMI->getTypeIDFor(GV);
4444 Res = DAG.getConstant(TypeID, MVT::i32);
4446 // Return something different to eh_selector.
4447 Res = DAG.getConstant(1, MVT::i32);
4451 if (DisableScheduling)
4452 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4456 case Intrinsic::eh_return_i32:
4457 case Intrinsic::eh_return_i64:
4458 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4459 MMI->setCallsEHReturn(true);
4460 Res = DAG.getNode(ISD::EH_RETURN, dl,
4463 getValue(I.getOperand(1)),
4464 getValue(I.getOperand(2)));
4466 if (DisableScheduling)
4467 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4469 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4473 case Intrinsic::eh_unwind_init:
4474 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4475 MMI->setCallsUnwindInit(true);
4478 case Intrinsic::eh_dwarf_cfa: {
4479 EVT VT = getValue(I.getOperand(1)).getValueType();
4480 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4481 TLI.getPointerTy());
4482 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4484 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4485 TLI.getPointerTy()),
4487 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4489 DAG.getConstant(0, TLI.getPointerTy()));
4490 Res = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4493 if (DisableScheduling) {
4494 DAG.AssignOrdering(CfaArg.getNode(), SDNodeOrder);
4495 DAG.AssignOrdering(Offset.getNode(), SDNodeOrder);
4496 DAG.AssignOrdering(FA.getNode(), SDNodeOrder);
4497 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4501 case Intrinsic::convertff:
4502 case Intrinsic::convertfsi:
4503 case Intrinsic::convertfui:
4504 case Intrinsic::convertsif:
4505 case Intrinsic::convertuif:
4506 case Intrinsic::convertss:
4507 case Intrinsic::convertsu:
4508 case Intrinsic::convertus:
4509 case Intrinsic::convertuu: {
4510 ISD::CvtCode Code = ISD::CVT_INVALID;
4511 switch (Intrinsic) {
4512 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4513 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4514 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4515 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4516 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4517 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4518 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4519 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4520 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4522 EVT DestVT = TLI.getValueType(I.getType());
4523 Value *Op1 = I.getOperand(1);
4524 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4525 DAG.getValueType(DestVT),
4526 DAG.getValueType(getValue(Op1).getValueType()),
4527 getValue(I.getOperand(2)),
4528 getValue(I.getOperand(3)),
4531 if (DisableScheduling)
4532 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4535 case Intrinsic::sqrt:
4536 Res = DAG.getNode(ISD::FSQRT, dl,
4537 getValue(I.getOperand(1)).getValueType(),
4538 getValue(I.getOperand(1)));
4540 if (DisableScheduling)
4541 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4543 case Intrinsic::powi:
4544 Res = DAG.getNode(ISD::FPOWI, dl,
4545 getValue(I.getOperand(1)).getValueType(),
4546 getValue(I.getOperand(1)),
4547 getValue(I.getOperand(2)));
4549 if (DisableScheduling)
4550 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4552 case Intrinsic::sin:
4553 Res = DAG.getNode(ISD::FSIN, dl,
4554 getValue(I.getOperand(1)).getValueType(),
4555 getValue(I.getOperand(1)));
4557 if (DisableScheduling)
4558 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4560 case Intrinsic::cos:
4561 Res = DAG.getNode(ISD::FCOS, dl,
4562 getValue(I.getOperand(1)).getValueType(),
4563 getValue(I.getOperand(1)));
4565 if (DisableScheduling)
4566 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4568 case Intrinsic::log:
4571 case Intrinsic::log2:
4574 case Intrinsic::log10:
4577 case Intrinsic::exp:
4580 case Intrinsic::exp2:
4583 case Intrinsic::pow:
4586 case Intrinsic::pcmarker: {
4587 SDValue Tmp = getValue(I.getOperand(1));
4588 Res = DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp);
4590 if (DisableScheduling)
4591 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4594 case Intrinsic::readcyclecounter: {
4595 SDValue Op = getRoot();
4596 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4597 DAG.getVTList(MVT::i64, MVT::Other),
4600 DAG.setRoot(Res.getValue(1));
4601 if (DisableScheduling)
4602 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4605 case Intrinsic::bswap:
4606 Res = DAG.getNode(ISD::BSWAP, dl,
4607 getValue(I.getOperand(1)).getValueType(),
4608 getValue(I.getOperand(1)));
4610 if (DisableScheduling)
4611 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4613 case Intrinsic::cttz: {
4614 SDValue Arg = getValue(I.getOperand(1));
4615 EVT Ty = Arg.getValueType();
4616 Res = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4618 if (DisableScheduling)
4619 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4622 case Intrinsic::ctlz: {
4623 SDValue Arg = getValue(I.getOperand(1));
4624 EVT Ty = Arg.getValueType();
4625 Res = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4627 if (DisableScheduling)
4628 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4631 case Intrinsic::ctpop: {
4632 SDValue Arg = getValue(I.getOperand(1));
4633 EVT Ty = Arg.getValueType();
4634 Res = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4636 if (DisableScheduling)
4637 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4640 case Intrinsic::stacksave: {
4641 SDValue Op = getRoot();
4642 Res = DAG.getNode(ISD::STACKSAVE, dl,
4643 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4645 DAG.setRoot(Res.getValue(1));
4646 if (DisableScheduling)
4647 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4650 case Intrinsic::stackrestore: {
4651 Res = getValue(I.getOperand(1));
4652 Res = DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res);
4654 if (DisableScheduling)
4655 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4658 case Intrinsic::stackprotector: {
4659 // Emit code into the DAG to store the stack guard onto the stack.
4660 MachineFunction &MF = DAG.getMachineFunction();
4661 MachineFrameInfo *MFI = MF.getFrameInfo();
4662 EVT PtrTy = TLI.getPointerTy();
4664 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4665 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4667 int FI = FuncInfo.StaticAllocaMap[Slot];
4668 MFI->setStackProtectorIndex(FI);
4670 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4672 // Store the stack protector onto the stack.
4673 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4674 PseudoSourceValue::getFixedStack(FI),
4678 if (DisableScheduling)
4679 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4682 case Intrinsic::objectsize: {
4683 // If we don't know by now, we're never going to know.
4684 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4686 assert(CI && "Non-constant type in __builtin_object_size?");
4688 SDValue Arg = getValue(I.getOperand(0));
4689 EVT Ty = Arg.getValueType();
4691 if (CI->getZExtValue() < 2)
4692 Res = DAG.getConstant(-1ULL, Ty);
4694 Res = DAG.getConstant(0, Ty);
4697 if (DisableScheduling)
4698 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4701 case Intrinsic::var_annotation:
4702 // Discard annotate attributes
4705 case Intrinsic::init_trampoline: {
4706 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4710 Ops[1] = getValue(I.getOperand(1));
4711 Ops[2] = getValue(I.getOperand(2));
4712 Ops[3] = getValue(I.getOperand(3));
4713 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4714 Ops[5] = DAG.getSrcValue(F);
4716 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4717 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4721 DAG.setRoot(Res.getValue(1));
4722 if (DisableScheduling)
4723 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4726 case Intrinsic::gcroot:
4728 Value *Alloca = I.getOperand(1);
4729 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4731 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4732 GFI->addStackRoot(FI->getIndex(), TypeMap);
4735 case Intrinsic::gcread:
4736 case Intrinsic::gcwrite:
4737 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4739 case Intrinsic::flt_rounds:
4740 Res = DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32);
4742 if (DisableScheduling)
4743 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4745 case Intrinsic::trap:
4746 Res = DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot());
4748 if (DisableScheduling)
4749 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4751 case Intrinsic::uadd_with_overflow:
4752 return implVisitAluOverflow(I, ISD::UADDO);
4753 case Intrinsic::sadd_with_overflow:
4754 return implVisitAluOverflow(I, ISD::SADDO);
4755 case Intrinsic::usub_with_overflow:
4756 return implVisitAluOverflow(I, ISD::USUBO);
4757 case Intrinsic::ssub_with_overflow:
4758 return implVisitAluOverflow(I, ISD::SSUBO);
4759 case Intrinsic::umul_with_overflow:
4760 return implVisitAluOverflow(I, ISD::UMULO);
4761 case Intrinsic::smul_with_overflow:
4762 return implVisitAluOverflow(I, ISD::SMULO);
4764 case Intrinsic::prefetch: {
4767 Ops[1] = getValue(I.getOperand(1));
4768 Ops[2] = getValue(I.getOperand(2));
4769 Ops[3] = getValue(I.getOperand(3));
4770 Res = DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4);
4772 if (DisableScheduling)
4773 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4777 case Intrinsic::memory_barrier: {
4780 for (int x = 1; x < 6; ++x)
4781 Ops[x] = getValue(I.getOperand(x));
4783 Res = DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6);
4785 if (DisableScheduling)
4786 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4789 case Intrinsic::atomic_cmp_swap: {
4790 SDValue Root = getRoot();
4792 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4793 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4795 getValue(I.getOperand(1)),
4796 getValue(I.getOperand(2)),
4797 getValue(I.getOperand(3)),
4800 DAG.setRoot(L.getValue(1));
4801 if (DisableScheduling)
4802 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
4805 case Intrinsic::atomic_load_add:
4806 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4807 case Intrinsic::atomic_load_sub:
4808 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4809 case Intrinsic::atomic_load_or:
4810 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4811 case Intrinsic::atomic_load_xor:
4812 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4813 case Intrinsic::atomic_load_and:
4814 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4815 case Intrinsic::atomic_load_nand:
4816 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4817 case Intrinsic::atomic_load_max:
4818 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4819 case Intrinsic::atomic_load_min:
4820 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4821 case Intrinsic::atomic_load_umin:
4822 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4823 case Intrinsic::atomic_load_umax:
4824 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4825 case Intrinsic::atomic_swap:
4826 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4828 case Intrinsic::invariant_start:
4829 case Intrinsic::lifetime_start:
4830 // Discard region information.
4831 Res = DAG.getUNDEF(TLI.getPointerTy());
4833 if (DisableScheduling)
4834 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4836 case Intrinsic::invariant_end:
4837 case Intrinsic::lifetime_end:
4838 // Discard region information.
4843 /// Test if the given instruction is in a position to be optimized
4844 /// with a tail-call. This roughly means that it's in a block with
4845 /// a return and there's nothing that needs to be scheduled
4846 /// between it and the return.
4848 /// This function only tests target-independent requirements.
4849 /// For target-dependent requirements, a target should override
4850 /// TargetLowering::IsEligibleForTailCallOptimization.
4853 isInTailCallPosition(const Instruction *I, Attributes CalleeRetAttr,
4854 const TargetLowering &TLI) {
4855 const BasicBlock *ExitBB = I->getParent();
4856 const TerminatorInst *Term = ExitBB->getTerminator();
4857 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4858 const Function *F = ExitBB->getParent();
4860 // The block must end in a return statement or an unreachable.
4861 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4863 // If I will have a chain, make sure no other instruction that will have a
4864 // chain interposes between I and the return.
4865 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4866 !I->isSafeToSpeculativelyExecute())
4867 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4871 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4872 !BBI->isSafeToSpeculativelyExecute())
4876 // If the block ends with a void return or unreachable, it doesn't matter
4877 // what the call's return type is.
4878 if (!Ret || Ret->getNumOperands() == 0) return true;
4880 // If the return value is undef, it doesn't matter what the call's
4882 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4884 // Conservatively require the attributes of the call to match those of
4885 // the return. Ignore noalias because it doesn't affect the call sequence.
4886 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4887 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4890 // Otherwise, make sure the unmodified return value of I is the return value.
4891 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4892 U = dyn_cast<Instruction>(U->getOperand(0))) {
4895 if (!U->hasOneUse())
4899 // Check for a truly no-op truncate.
4900 if (isa<TruncInst>(U) &&
4901 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4903 // Check for a truly no-op bitcast.
4904 if (isa<BitCastInst>(U) &&
4905 (U->getOperand(0)->getType() == U->getType() ||
4906 (isa<PointerType>(U->getOperand(0)->getType()) &&
4907 isa<PointerType>(U->getType()))))
4909 // Otherwise it's not a true no-op.
4916 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4918 MachineBasicBlock *LandingPad) {
4919 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4920 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4921 const Type *RetTy = FTy->getReturnType();
4922 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4923 unsigned BeginLabel = 0, EndLabel = 0;
4925 TargetLowering::ArgListTy Args;
4926 TargetLowering::ArgListEntry Entry;
4927 Args.reserve(CS.arg_size());
4929 // Check whether the function can return without sret-demotion.
4930 SmallVector<EVT, 4> OutVTs;
4931 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4932 SmallVector<uint64_t, 4> Offsets;
4933 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4934 OutVTs, OutsFlags, TLI, &Offsets);
4936 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4937 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4939 SDValue DemoteStackSlot;
4941 if (!CanLowerReturn) {
4942 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4943 FTy->getReturnType());
4944 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4945 FTy->getReturnType());
4946 MachineFunction &MF = DAG.getMachineFunction();
4947 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4948 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4950 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4951 Entry.Node = DemoteStackSlot;
4952 Entry.Ty = StackSlotPtrType;
4953 Entry.isSExt = false;
4954 Entry.isZExt = false;
4955 Entry.isInReg = false;
4956 Entry.isSRet = true;
4957 Entry.isNest = false;
4958 Entry.isByVal = false;
4959 Entry.Alignment = Align;
4960 Args.push_back(Entry);
4961 RetTy = Type::getVoidTy(FTy->getContext());
4964 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4966 SDValue ArgNode = getValue(*i);
4967 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4969 unsigned attrInd = i - CS.arg_begin() + 1;
4970 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4971 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4972 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4973 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4974 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4975 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4976 Entry.Alignment = CS.getParamAlignment(attrInd);
4977 Args.push_back(Entry);
4980 if (LandingPad && MMI) {
4981 // Insert a label before the invoke call to mark the try range. This can be
4982 // used to detect deletion of the invoke via the MachineModuleInfo.
4983 BeginLabel = MMI->NextLabelID();
4985 // Both PendingLoads and PendingExports must be flushed here;
4986 // this call might not return.
4988 SDValue Label = DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4989 getControlRoot(), BeginLabel);
4991 if (DisableScheduling)
4992 DAG.AssignOrdering(Label.getNode(), SDNodeOrder);
4995 // Check if target-independent constraints permit a tail call here.
4996 // Target-dependent constraints are checked within TLI.LowerCallTo.
4998 !isInTailCallPosition(CS.getInstruction(),
4999 CS.getAttributes().getRetAttributes(),
5003 std::pair<SDValue,SDValue> Result =
5004 TLI.LowerCallTo(getRoot(), RetTy,
5005 CS.paramHasAttr(0, Attribute::SExt),
5006 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
5007 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
5008 CS.getCallingConv(),
5010 !CS.getInstruction()->use_empty(),
5011 Callee, Args, DAG, getCurDebugLoc(), SDNodeOrder);
5012 assert((isTailCall || Result.second.getNode()) &&
5013 "Non-null chain expected with non-tail call!");
5014 assert((Result.second.getNode() || !Result.first.getNode()) &&
5015 "Null value expected with tail call!");
5016 if (Result.first.getNode()) {
5017 setValue(CS.getInstruction(), Result.first);
5018 if (DisableScheduling)
5019 DAG.AssignOrdering(Result.first.getNode(), SDNodeOrder);
5020 } else if (!CanLowerReturn && Result.second.getNode()) {
5021 // The instruction result is the result of loading from the
5022 // hidden sret parameter.
5023 SmallVector<EVT, 1> PVTs;
5024 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5026 ComputeValueVTs(TLI, PtrRetTy, PVTs);
5027 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5028 EVT PtrVT = PVTs[0];
5029 unsigned NumValues = OutVTs.size();
5030 SmallVector<SDValue, 4> Values(NumValues);
5031 SmallVector<SDValue, 4> Chains(NumValues);
5033 for (unsigned i = 0; i < NumValues; ++i) {
5034 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5036 DAG.getConstant(Offsets[i], PtrVT));
5037 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
5038 Add, NULL, Offsets[i], false, 1);
5040 Chains[i] = L.getValue(1);
5042 if (DisableScheduling) {
5043 DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
5044 DAG.AssignOrdering(L.getNode(), SDNodeOrder);
5048 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5049 MVT::Other, &Chains[0], NumValues);
5050 PendingLoads.push_back(Chain);
5052 SDValue MV = DAG.getNode(ISD::MERGE_VALUES,
5054 DAG.getVTList(&OutVTs[0], NumValues),
5055 &Values[0], NumValues);
5056 setValue(CS.getInstruction(), MV);
5058 if (DisableScheduling) {
5059 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
5060 DAG.AssignOrdering(MV.getNode(), SDNodeOrder);
5064 // As a special case, a null chain means that a tail call has been emitted and
5065 // the DAG root is already updated.
5066 if (Result.second.getNode()) {
5067 DAG.setRoot(Result.second);
5068 if (DisableScheduling)
5069 DAG.AssignOrdering(Result.second.getNode(), SDNodeOrder);
5074 if (LandingPad && MMI) {
5075 // Insert a label at the end of the invoke call to mark the try range. This
5076 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5077 EndLabel = MMI->NextLabelID();
5078 SDValue Label = DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
5079 getRoot(), EndLabel);
5082 if (DisableScheduling)
5083 DAG.AssignOrdering(Label.getNode(), SDNodeOrder);
5085 // Inform MachineModuleInfo of range.
5086 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
5090 void SelectionDAGBuilder::visitCall(CallInst &I) {
5091 const char *RenameFn = 0;
5092 if (Function *F = I.getCalledFunction()) {
5093 if (F->isDeclaration()) {
5094 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
5096 if (unsigned IID = II->getIntrinsicID(F)) {
5097 RenameFn = visitIntrinsicCall(I, IID);
5102 if (unsigned IID = F->getIntrinsicID()) {
5103 RenameFn = visitIntrinsicCall(I, IID);
5109 // Check for well-known libc/libm calls. If the function is internal, it
5110 // can't be a library call.
5111 if (!F->hasLocalLinkage() && F->hasName()) {
5112 StringRef Name = F->getName();
5113 if (Name == "copysign" || Name == "copysignf") {
5114 if (I.getNumOperands() == 3 && // Basic sanity checks.
5115 I.getOperand(1)->getType()->isFloatingPoint() &&
5116 I.getType() == I.getOperand(1)->getType() &&
5117 I.getType() == I.getOperand(2)->getType()) {
5118 SDValue LHS = getValue(I.getOperand(1));
5119 SDValue RHS = getValue(I.getOperand(2));
5120 SDValue Res = DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5121 LHS.getValueType(), LHS, RHS);
5123 if (DisableScheduling)
5124 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5127 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5128 if (I.getNumOperands() == 2 && // Basic sanity checks.
5129 I.getOperand(1)->getType()->isFloatingPoint() &&
5130 I.getType() == I.getOperand(1)->getType()) {
5131 SDValue Tmp = getValue(I.getOperand(1));
5132 SDValue Res = DAG.getNode(ISD::FABS, getCurDebugLoc(),
5133 Tmp.getValueType(), Tmp);
5135 if (DisableScheduling)
5136 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5139 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5140 if (I.getNumOperands() == 2 && // Basic sanity checks.
5141 I.getOperand(1)->getType()->isFloatingPoint() &&
5142 I.getType() == I.getOperand(1)->getType() &&
5143 I.onlyReadsMemory()) {
5144 SDValue Tmp = getValue(I.getOperand(1));
5145 SDValue Res = DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5146 Tmp.getValueType(), Tmp);
5148 if (DisableScheduling)
5149 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5152 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5153 if (I.getNumOperands() == 2 && // Basic sanity checks.
5154 I.getOperand(1)->getType()->isFloatingPoint() &&
5155 I.getType() == I.getOperand(1)->getType() &&
5156 I.onlyReadsMemory()) {
5157 SDValue Tmp = getValue(I.getOperand(1));
5158 SDValue Res = DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5159 Tmp.getValueType(), Tmp);
5161 if (DisableScheduling)
5162 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5165 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5166 if (I.getNumOperands() == 2 && // Basic sanity checks.
5167 I.getOperand(1)->getType()->isFloatingPoint() &&
5168 I.getType() == I.getOperand(1)->getType() &&
5169 I.onlyReadsMemory()) {
5170 SDValue Tmp = getValue(I.getOperand(1));
5171 SDValue Res = DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5172 Tmp.getValueType(), Tmp);
5174 if (DisableScheduling)
5175 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
5180 } else if (isa<InlineAsm>(I.getOperand(0))) {
5187 Callee = getValue(I.getOperand(0));
5189 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5191 if (DisableScheduling)
5192 DAG.AssignOrdering(Callee.getNode(), SDNodeOrder);
5194 // Check if we can potentially perform a tail call. More detailed
5195 // checking is be done within LowerCallTo, after more information
5196 // about the call is known.
5197 bool isTailCall = PerformTailCallOpt && I.isTailCall();
5199 LowerCallTo(&I, Callee, isTailCall);
5202 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
5203 /// this value and returns the result as a ValueVT value. This uses
5204 /// Chain/Flag as the input and updates them for the output Chain/Flag.
5205 /// If the Flag pointer is NULL, no flag is used.
5206 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
5207 unsigned Order, SDValue &Chain,
5208 SDValue *Flag) const {
5209 // Assemble the legal parts into the final values.
5210 SmallVector<SDValue, 4> Values(ValueVTs.size());
5211 SmallVector<SDValue, 8> Parts;
5212 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
5213 // Copy the legal parts from the registers.
5214 EVT ValueVT = ValueVTs[Value];
5215 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
5216 EVT RegisterVT = RegVTs[Value];
5218 Parts.resize(NumRegs);
5219 for (unsigned i = 0; i != NumRegs; ++i) {
5222 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
5224 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
5225 *Flag = P.getValue(2);
5228 Chain = P.getValue(1);
5230 if (DisableScheduling)
5231 DAG.AssignOrdering(P.getNode(), Order);
5233 // If the source register was virtual and if we know something about it,
5234 // add an assert node.
5235 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
5236 RegisterVT.isInteger() && !RegisterVT.isVector()) {
5237 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
5238 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5239 if (FLI.LiveOutRegInfo.size() > SlotNo) {
5240 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
5242 unsigned RegSize = RegisterVT.getSizeInBits();
5243 unsigned NumSignBits = LOI.NumSignBits;
5244 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
5246 // FIXME: We capture more information than the dag can represent. For
5247 // now, just use the tightest assertzext/assertsext possible.
5249 EVT FromVT(MVT::Other);
5250 if (NumSignBits == RegSize)
5251 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
5252 else if (NumZeroBits >= RegSize-1)
5253 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
5254 else if (NumSignBits > RegSize-8)
5255 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
5256 else if (NumZeroBits >= RegSize-8)
5257 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
5258 else if (NumSignBits > RegSize-16)
5259 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
5260 else if (NumZeroBits >= RegSize-16)
5261 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
5262 else if (NumSignBits > RegSize-32)
5263 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
5264 else if (NumZeroBits >= RegSize-32)
5265 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
5267 if (FromVT != MVT::Other) {
5268 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
5269 RegisterVT, P, DAG.getValueType(FromVT));
5271 if (DisableScheduling)
5272 DAG.AssignOrdering(P.getNode(), Order);
5280 Values[Value] = getCopyFromParts(DAG, dl, Order, Parts.begin(),
5281 NumRegs, RegisterVT, ValueVT);
5282 if (DisableScheduling)
5283 DAG.AssignOrdering(Values[Value].getNode(), Order);
5288 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5289 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
5290 &Values[0], ValueVTs.size());
5291 if (DisableScheduling)
5292 DAG.AssignOrdering(Res.getNode(), Order);
5296 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
5297 /// specified value into the registers specified by this object. This uses
5298 /// Chain/Flag as the input and updates them for the output Chain/Flag.
5299 /// If the Flag pointer is NULL, no flag is used.
5300 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
5301 unsigned Order, SDValue &Chain,
5302 SDValue *Flag) const {
5303 // Get the list of the values's legal parts.
5304 unsigned NumRegs = Regs.size();
5305 SmallVector<SDValue, 8> Parts(NumRegs);
5306 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
5307 EVT ValueVT = ValueVTs[Value];
5308 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
5309 EVT RegisterVT = RegVTs[Value];
5311 getCopyToParts(DAG, dl, Order,
5312 Val.getValue(Val.getResNo() + Value),
5313 &Parts[Part], NumParts, RegisterVT);
5317 // Copy the parts into the registers.
5318 SmallVector<SDValue, 8> Chains(NumRegs);
5319 for (unsigned i = 0; i != NumRegs; ++i) {
5322 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
5324 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
5325 *Flag = Part.getValue(1);
5328 Chains[i] = Part.getValue(0);
5330 if (DisableScheduling)
5331 DAG.AssignOrdering(Part.getNode(), Order);
5334 if (NumRegs == 1 || Flag)
5335 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
5336 // flagged to it. That is the CopyToReg nodes and the user are considered
5337 // a single scheduling unit. If we create a TokenFactor and return it as
5338 // chain, then the TokenFactor is both a predecessor (operand) of the
5339 // user as well as a successor (the TF operands are flagged to the user).
5340 // c1, f1 = CopyToReg
5341 // c2, f2 = CopyToReg
5342 // c3 = TokenFactor c1, c2
5345 Chain = Chains[NumRegs-1];
5347 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
5349 if (DisableScheduling)
5350 DAG.AssignOrdering(Chain.getNode(), Order);
5353 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
5354 /// operand list. This adds the code marker and includes the number of
5355 /// values added into it.
5356 void RegsForValue::AddInlineAsmOperands(unsigned Code,
5357 bool HasMatching,unsigned MatchingIdx,
5358 SelectionDAG &DAG, unsigned Order,
5359 std::vector<SDValue> &Ops) const {
5360 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5361 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
5362 unsigned Flag = Code | (Regs.size() << 3);
5364 Flag |= 0x80000000 | (MatchingIdx << 16);
5366 SDValue Res = DAG.getTargetConstant(Flag, IntPtrTy);
5369 if (DisableScheduling)
5370 DAG.AssignOrdering(Res.getNode(), Order);
5372 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
5373 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
5374 EVT RegisterVT = RegVTs[Value];
5375 for (unsigned i = 0; i != NumRegs; ++i) {
5376 assert(Reg < Regs.size() && "Mismatch in # registers expected");
5377 SDValue Res = DAG.getRegister(Regs[Reg++], RegisterVT);
5380 if (DisableScheduling)
5381 DAG.AssignOrdering(Res.getNode(), Order);
5386 /// isAllocatableRegister - If the specified register is safe to allocate,
5387 /// i.e. it isn't a stack pointer or some other special register, return the
5388 /// register class for the register. Otherwise, return null.
5389 static const TargetRegisterClass *
5390 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5391 const TargetLowering &TLI,
5392 const TargetRegisterInfo *TRI) {
5393 EVT FoundVT = MVT::Other;
5394 const TargetRegisterClass *FoundRC = 0;
5395 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5396 E = TRI->regclass_end(); RCI != E; ++RCI) {
5397 EVT ThisVT = MVT::Other;
5399 const TargetRegisterClass *RC = *RCI;
5400 // If none of the the value types for this register class are valid, we
5401 // can't use it. For example, 64-bit reg classes on 32-bit targets.
5402 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5404 if (TLI.isTypeLegal(*I)) {
5405 // If we have already found this register in a different register class,
5406 // choose the one with the largest VT specified. For example, on
5407 // PowerPC, we favor f64 register classes over f32.
5408 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5415 if (ThisVT == MVT::Other) continue;
5417 // NOTE: This isn't ideal. In particular, this might allocate the
5418 // frame pointer in functions that need it (due to them not being taken
5419 // out of allocation, because a variable sized allocation hasn't been seen
5420 // yet). This is a slight code pessimization, but should still work.
5421 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5422 E = RC->allocation_order_end(MF); I != E; ++I)
5424 // We found a matching register class. Keep looking at others in case
5425 // we find one with larger registers that this physreg is also in.
5436 /// AsmOperandInfo - This contains information for each constraint that we are
5438 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
5439 public TargetLowering::AsmOperandInfo {
5441 /// CallOperand - If this is the result output operand or a clobber
5442 /// this is null, otherwise it is the incoming operand to the CallInst.
5443 /// This gets modified as the asm is processed.
5444 SDValue CallOperand;
5446 /// AssignedRegs - If this is a register or register class operand, this
5447 /// contains the set of register corresponding to the operand.
5448 RegsForValue AssignedRegs;
5450 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
5451 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5454 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5455 /// busy in OutputRegs/InputRegs.
5456 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5457 std::set<unsigned> &OutputRegs,
5458 std::set<unsigned> &InputRegs,
5459 const TargetRegisterInfo &TRI) const {
5461 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5462 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5465 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5466 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5470 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5471 /// corresponds to. If there is no Value* for this operand, it returns
5473 EVT getCallOperandValEVT(LLVMContext &Context,
5474 const TargetLowering &TLI,
5475 const TargetData *TD) const {
5476 if (CallOperandVal == 0) return MVT::Other;
5478 if (isa<BasicBlock>(CallOperandVal))
5479 return TLI.getPointerTy();
5481 const llvm::Type *OpTy = CallOperandVal->getType();
5483 // If this is an indirect operand, the operand is a pointer to the
5486 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5488 llvm_report_error("Indirect operand for inline asm not a pointer!");
5489 OpTy = PtrTy->getElementType();
5492 // If OpTy is not a single value, it may be a struct/union that we
5493 // can tile with integers.
5494 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5495 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5504 OpTy = IntegerType::get(Context, BitSize);
5509 return TLI.getValueType(OpTy, true);
5513 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5515 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5516 const TargetRegisterInfo &TRI) {
5517 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5519 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5520 for (; *Aliases; ++Aliases)
5521 Regs.insert(*Aliases);
5524 } // end llvm namespace.
5527 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5528 /// specified operand. We prefer to assign virtual registers, to allow the
5529 /// register allocator to handle the assignment process. However, if the asm
5530 /// uses features that we can't model on machineinstrs, we have SDISel do the
5531 /// allocation. This produces generally horrible, but correct, code.
5533 /// OpInfo describes the operand.
5534 /// Input and OutputRegs are the set of already allocated physical registers.
5536 void SelectionDAGBuilder::
5537 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5538 std::set<unsigned> &OutputRegs,
5539 std::set<unsigned> &InputRegs) {
5540 LLVMContext &Context = FuncInfo.Fn->getContext();
5542 // Compute whether this value requires an input register, an output register,
5544 bool isOutReg = false;
5545 bool isInReg = false;
5546 switch (OpInfo.Type) {
5547 case InlineAsm::isOutput:
5550 // If there is an input constraint that matches this, we need to reserve
5551 // the input register so no other inputs allocate to it.
5552 isInReg = OpInfo.hasMatchingInput();
5554 case InlineAsm::isInput:
5558 case InlineAsm::isClobber:
5565 MachineFunction &MF = DAG.getMachineFunction();
5566 SmallVector<unsigned, 4> Regs;
5568 // If this is a constraint for a single physreg, or a constraint for a
5569 // register class, find it.
5570 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5571 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5572 OpInfo.ConstraintVT);
5574 unsigned NumRegs = 1;
5575 if (OpInfo.ConstraintVT != MVT::Other) {
5576 // If this is a FP input in an integer register (or visa versa) insert a bit
5577 // cast of the input value. More generally, handle any case where the input
5578 // value disagrees with the register class we plan to stick this in.
5579 if (OpInfo.Type == InlineAsm::isInput &&
5580 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5581 // Try to convert to the first EVT that the reg class contains. If the
5582 // types are identical size, use a bitcast to convert (e.g. two differing
5584 EVT RegVT = *PhysReg.second->vt_begin();
5585 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5586 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5587 RegVT, OpInfo.CallOperand);
5588 OpInfo.ConstraintVT = RegVT;
5589 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5590 // If the input is a FP value and we want it in FP registers, do a
5591 // bitcast to the corresponding integer type. This turns an f64 value
5592 // into i64, which can be passed with two i32 values on a 32-bit
5594 RegVT = EVT::getIntegerVT(Context,
5595 OpInfo.ConstraintVT.getSizeInBits());
5596 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5597 RegVT, OpInfo.CallOperand);
5598 OpInfo.ConstraintVT = RegVT;
5601 if (DisableScheduling)
5602 DAG.AssignOrdering(OpInfo.CallOperand.getNode(), SDNodeOrder);
5605 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5609 EVT ValueVT = OpInfo.ConstraintVT;
5611 // If this is a constraint for a specific physical register, like {r17},
5613 if (unsigned AssignedReg = PhysReg.first) {
5614 const TargetRegisterClass *RC = PhysReg.second;
5615 if (OpInfo.ConstraintVT == MVT::Other)
5616 ValueVT = *RC->vt_begin();
5618 // Get the actual register value type. This is important, because the user
5619 // may have asked for (e.g.) the AX register in i32 type. We need to
5620 // remember that AX is actually i16 to get the right extension.
5621 RegVT = *RC->vt_begin();
5623 // This is a explicit reference to a physical register.
5624 Regs.push_back(AssignedReg);
5626 // If this is an expanded reference, add the rest of the regs to Regs.
5628 TargetRegisterClass::iterator I = RC->begin();
5629 for (; *I != AssignedReg; ++I)
5630 assert(I != RC->end() && "Didn't find reg!");
5632 // Already added the first reg.
5634 for (; NumRegs; --NumRegs, ++I) {
5635 assert(I != RC->end() && "Ran out of registers to allocate!");
5640 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5641 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5642 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5646 // Otherwise, if this was a reference to an LLVM register class, create vregs
5647 // for this reference.
5648 if (const TargetRegisterClass *RC = PhysReg.second) {
5649 RegVT = *RC->vt_begin();
5650 if (OpInfo.ConstraintVT == MVT::Other)
5653 // Create the appropriate number of virtual registers.
5654 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5655 for (; NumRegs; --NumRegs)
5656 Regs.push_back(RegInfo.createVirtualRegister(RC));
5658 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5662 // This is a reference to a register class that doesn't directly correspond
5663 // to an LLVM register class. Allocate NumRegs consecutive, available,
5664 // registers from the class.
5665 std::vector<unsigned> RegClassRegs
5666 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5667 OpInfo.ConstraintVT);
5669 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5670 unsigned NumAllocated = 0;
5671 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5672 unsigned Reg = RegClassRegs[i];
5673 // See if this register is available.
5674 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5675 (isInReg && InputRegs.count(Reg))) { // Already used.
5676 // Make sure we find consecutive registers.
5681 // Check to see if this register is allocatable (i.e. don't give out the
5683 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5684 if (!RC) { // Couldn't allocate this register.
5685 // Reset NumAllocated to make sure we return consecutive registers.
5690 // Okay, this register is good, we can use it.
5693 // If we allocated enough consecutive registers, succeed.
5694 if (NumAllocated == NumRegs) {
5695 unsigned RegStart = (i-NumAllocated)+1;
5696 unsigned RegEnd = i+1;
5697 // Mark all of the allocated registers used.
5698 for (unsigned i = RegStart; i != RegEnd; ++i)
5699 Regs.push_back(RegClassRegs[i]);
5701 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5702 OpInfo.ConstraintVT);
5703 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5708 // Otherwise, we couldn't allocate enough registers for this.
5711 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5712 /// processed uses a memory 'm' constraint.
5714 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5715 const TargetLowering &TLI) {
5716 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5717 InlineAsm::ConstraintInfo &CI = CInfos[i];
5718 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5719 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5720 if (CType == TargetLowering::C_Memory)
5724 // Indirect operand accesses access memory.
5732 /// visitInlineAsm - Handle a call to an InlineAsm object.
5734 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
5735 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5737 /// ConstraintOperands - Information about all of the constraints.
5738 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5740 std::set<unsigned> OutputRegs, InputRegs;
5742 // Do a prepass over the constraints, canonicalizing them, and building up the
5743 // ConstraintOperands list.
5744 std::vector<InlineAsm::ConstraintInfo>
5745 ConstraintInfos = IA->ParseConstraints();
5747 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5749 SDValue Chain, Flag;
5751 // We won't need to flush pending loads if this asm doesn't touch
5752 // memory and is nonvolatile.
5753 if (hasMemory || IA->hasSideEffects())
5756 Chain = DAG.getRoot();
5758 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5759 unsigned ResNo = 0; // ResNo - The result number of the next output.
5760 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5761 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5762 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5764 EVT OpVT = MVT::Other;
5766 // Compute the value type for each operand.
5767 switch (OpInfo.Type) {
5768 case InlineAsm::isOutput:
5769 // Indirect outputs just consume an argument.
5770 if (OpInfo.isIndirect) {
5771 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5775 // The return value of the call is this value. As such, there is no
5776 // corresponding argument.
5777 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5779 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5780 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5782 assert(ResNo == 0 && "Asm only has one result!");
5783 OpVT = TLI.getValueType(CS.getType());
5787 case InlineAsm::isInput:
5788 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5790 case InlineAsm::isClobber:
5795 // If this is an input or an indirect output, process the call argument.
5796 // BasicBlocks are labels, currently appearing only in asm's.
5797 if (OpInfo.CallOperandVal) {
5798 // Strip bitcasts, if any. This mostly comes up for functions.
5799 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5801 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5802 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5804 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5807 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5810 OpInfo.ConstraintVT = OpVT;
5813 // Second pass over the constraints: compute which constraint option to use
5814 // and assign registers to constraints that want a specific physreg.
5815 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5816 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5818 // If this is an output operand with a matching input operand, look up the
5819 // matching input. If their types mismatch, e.g. one is an integer, the
5820 // other is floating point, or their sizes are different, flag it as an
5822 if (OpInfo.hasMatchingInput()) {
5823 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5824 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5825 if ((OpInfo.ConstraintVT.isInteger() !=
5826 Input.ConstraintVT.isInteger()) ||
5827 (OpInfo.ConstraintVT.getSizeInBits() !=
5828 Input.ConstraintVT.getSizeInBits())) {
5829 llvm_report_error("Unsupported asm: input constraint"
5830 " with a matching output constraint of incompatible"
5833 Input.ConstraintVT = OpInfo.ConstraintVT;
5837 // Compute the constraint code and ConstraintType to use.
5838 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5840 // If this is a memory input, and if the operand is not indirect, do what we
5841 // need to to provide an address for the memory input.
5842 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5843 !OpInfo.isIndirect) {
5844 assert(OpInfo.Type == InlineAsm::isInput &&
5845 "Can only indirectify direct input operands!");
5847 // Memory operands really want the address of the value. If we don't have
5848 // an indirect input, put it in the constpool if we can, otherwise spill
5849 // it to a stack slot.
5851 // If the operand is a float, integer, or vector constant, spill to a
5852 // constant pool entry to get its address.
5853 Value *OpVal = OpInfo.CallOperandVal;
5854 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5855 isa<ConstantVector>(OpVal)) {
5856 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5857 TLI.getPointerTy());
5859 // Otherwise, create a stack slot and emit a store to it before the
5861 const Type *Ty = OpVal->getType();
5862 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5863 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5864 MachineFunction &MF = DAG.getMachineFunction();
5865 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5866 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5867 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5868 OpInfo.CallOperand, StackSlot, NULL, 0);
5869 OpInfo.CallOperand = StackSlot;
5870 if (DisableScheduling)
5871 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
5874 // There is no longer a Value* corresponding to this operand.
5875 OpInfo.CallOperandVal = 0;
5877 // It is now an indirect operand.
5878 OpInfo.isIndirect = true;
5880 if (DisableScheduling)
5881 DAG.AssignOrdering(OpInfo.CallOperand.getNode(), SDNodeOrder);
5884 // If this constraint is for a specific register, allocate it before
5886 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5887 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5890 ConstraintInfos.clear();
5892 // Second pass - Loop over all of the operands, assigning virtual or physregs
5893 // to register class operands.
5894 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5895 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5897 // C_Register operands have already been allocated, Other/Memory don't need
5899 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5900 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5903 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5904 std::vector<SDValue> AsmNodeOperands;
5905 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5906 AsmNodeOperands.push_back(
5907 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5910 // Loop over all of the inputs, copying the operand values into the
5911 // appropriate registers and processing the output regs.
5912 RegsForValue RetValRegs;
5914 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5915 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5917 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5918 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5920 switch (OpInfo.Type) {
5921 case InlineAsm::isOutput: {
5922 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5923 OpInfo.ConstraintType != TargetLowering::C_Register) {
5924 // Memory output, or 'other' output (e.g. 'X' constraint).
5925 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5927 // Add information to the INLINEASM node to know about this output.
5928 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5929 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5930 TLI.getPointerTy()));
5931 AsmNodeOperands.push_back(OpInfo.CallOperand);
5935 // Otherwise, this is a register or register class output.
5937 // Copy the output from the appropriate register. Find a register that
5939 if (OpInfo.AssignedRegs.Regs.empty()) {
5940 llvm_report_error("Couldn't allocate output reg for"
5941 " constraint '" + OpInfo.ConstraintCode + "'!");
5944 // If this is an indirect operand, store through the pointer after the
5946 if (OpInfo.isIndirect) {
5947 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5948 OpInfo.CallOperandVal));
5950 // This is the result value of the call.
5951 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5953 // Concatenate this output onto the outputs list.
5954 RetValRegs.append(OpInfo.AssignedRegs);
5957 // Add information to the INLINEASM node to know that this register is
5959 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5960 6 /* EARLYCLOBBER REGDEF */ :
5968 case InlineAsm::isInput: {
5969 SDValue InOperandVal = OpInfo.CallOperand;
5971 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5972 // If this is required to match an output register we have already set,
5973 // just use its register.
5974 unsigned OperandNo = OpInfo.getMatchedOperand();
5976 // Scan until we find the definition we already emitted of this operand.
5977 // When we find it, create a RegsForValue operand.
5978 unsigned CurOp = 2; // The first operand.
5979 for (; OperandNo; --OperandNo) {
5980 // Advance to the next operand.
5982 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5983 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5984 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5985 (OpFlag & 7) == 4 /*MEM*/) &&
5986 "Skipped past definitions?");
5987 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5991 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5992 if ((OpFlag & 7) == 2 /*REGDEF*/
5993 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5994 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5995 if (OpInfo.isIndirect) {
5996 llvm_report_error("Don't know how to handle tied indirect "
5997 "register inputs yet!");
5999 RegsForValue MatchedRegs;
6000 MatchedRegs.TLI = &TLI;
6001 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6002 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
6003 MatchedRegs.RegVTs.push_back(RegVT);
6004 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6005 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6008 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
6010 // Use the produced MatchedRegs object to
6011 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6012 SDNodeOrder, Chain, &Flag);
6013 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
6014 true, OpInfo.getMatchedOperand(),
6015 DAG, SDNodeOrder, AsmNodeOperands);
6018 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
6019 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
6020 "Unexpected number of operands");
6021 // Add information to the INLINEASM node to know about this input.
6022 // See InlineAsm.h isUseOperandTiedToDef.
6023 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
6024 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6025 TLI.getPointerTy()));
6026 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6031 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6032 assert(!OpInfo.isIndirect &&
6033 "Don't know how to handle indirect other inputs yet!");
6035 std::vector<SDValue> Ops;
6036 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
6037 hasMemory, Ops, DAG);
6039 llvm_report_error("Invalid operand for inline asm"
6040 " constraint '" + OpInfo.ConstraintCode + "'!");
6043 // Add information to the INLINEASM node to know about this input.
6044 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
6045 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6046 TLI.getPointerTy()));
6047 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6049 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6050 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6051 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6052 "Memory operands expect pointer values");
6054 // Add information to the INLINEASM node to know about this input.
6055 unsigned ResOpType = 4/*MEM*/ | (1<<3);
6056 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6057 TLI.getPointerTy()));
6058 AsmNodeOperands.push_back(InOperandVal);
6062 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6063 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6064 "Unknown constraint type!");
6065 assert(!OpInfo.isIndirect &&
6066 "Don't know how to handle indirect register inputs yet!");
6068 // Copy the input into the appropriate registers.
6069 if (OpInfo.AssignedRegs.Regs.empty()) {
6070 llvm_report_error("Couldn't allocate input reg for"
6071 " constraint '"+ OpInfo.ConstraintCode +"'!");
6074 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6075 SDNodeOrder, Chain, &Flag);
6077 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
6082 case InlineAsm::isClobber: {
6083 // Add the clobbered value to the operand list, so that the register
6084 // allocator is aware that the physreg got clobbered.
6085 if (!OpInfo.AssignedRegs.Regs.empty())
6086 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
6087 false, 0, DAG, SDNodeOrder,
6094 // Finish up input operands.
6095 AsmNodeOperands[0] = Chain;
6096 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6098 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
6099 DAG.getVTList(MVT::Other, MVT::Flag),
6100 &AsmNodeOperands[0], AsmNodeOperands.size());
6101 Flag = Chain.getValue(1);
6103 if (DisableScheduling)
6104 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
6106 // If this asm returns a register value, copy the result from that register
6107 // and set it as the value of the call.
6108 if (!RetValRegs.Regs.empty()) {
6109 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
6110 SDNodeOrder, Chain, &Flag);
6112 // FIXME: Why don't we do this for inline asms with MRVs?
6113 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6114 EVT ResultType = TLI.getValueType(CS.getType());
6116 // If any of the results of the inline asm is a vector, it may have the
6117 // wrong width/num elts. This can happen for register classes that can
6118 // contain multiple different value types. The preg or vreg allocated may
6119 // not have the same VT as was expected. Convert it to the right type
6120 // with bit_convert.
6121 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6122 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
6125 } else if (ResultType != Val.getValueType() &&
6126 ResultType.isInteger() && Val.getValueType().isInteger()) {
6127 // If a result value was tied to an input value, the computed result may
6128 // have a wider width than the expected result. Extract the relevant
6130 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
6133 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6135 if (DisableScheduling)
6136 DAG.AssignOrdering(Val.getNode(), SDNodeOrder);
6139 setValue(CS.getInstruction(), Val);
6140 // Don't need to use this as a chain in this case.
6141 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6145 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
6147 // Process indirect outputs, first output all of the flagged copies out of
6149 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6150 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6151 Value *Ptr = IndirectStoresToEmit[i].second;
6152 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
6153 SDNodeOrder, Chain, &Flag);
6154 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6158 // Emit the non-flagged stores from the physregs.
6159 SmallVector<SDValue, 8> OutChains;
6160 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6161 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6162 StoresToEmit[i].first,
6163 getValue(StoresToEmit[i].second),
6164 StoresToEmit[i].second, 0);
6165 OutChains.push_back(Val);
6166 if (DisableScheduling)
6167 DAG.AssignOrdering(Val.getNode(), SDNodeOrder);
6170 if (!OutChains.empty())
6171 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
6172 &OutChains[0], OutChains.size());
6174 if (DisableScheduling)
6175 DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
6180 void SelectionDAGBuilder::visitVAStart(CallInst &I) {
6181 SDValue Res = DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6182 MVT::Other, getRoot(),
6183 getValue(I.getOperand(1)),
6184 DAG.getSrcValue(I.getOperand(1)));
6186 if (DisableScheduling)
6187 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
6190 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
6191 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6192 getRoot(), getValue(I.getOperand(0)),
6193 DAG.getSrcValue(I.getOperand(0)));
6195 DAG.setRoot(V.getValue(1));
6196 if (DisableScheduling)
6197 DAG.AssignOrdering(V.getNode(), SDNodeOrder);
6200 void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
6201 SDValue Res = DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6202 MVT::Other, getRoot(),
6203 getValue(I.getOperand(1)),
6204 DAG.getSrcValue(I.getOperand(1)));
6206 if (DisableScheduling)
6207 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
6210 void SelectionDAGBuilder::visitVACopy(CallInst &I) {
6211 SDValue Res = DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6212 MVT::Other, getRoot(),
6213 getValue(I.getOperand(1)),
6214 getValue(I.getOperand(2)),
6215 DAG.getSrcValue(I.getOperand(1)),
6216 DAG.getSrcValue(I.getOperand(2)));
6218 if (DisableScheduling)
6219 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
6222 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6223 /// implementation, which just calls LowerCall.
6224 /// FIXME: When all targets are
6225 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6226 std::pair<SDValue, SDValue>
6227 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
6228 bool RetSExt, bool RetZExt, bool isVarArg,
6229 bool isInreg, unsigned NumFixedArgs,
6230 CallingConv::ID CallConv, bool isTailCall,
6231 bool isReturnValueUsed,
6233 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl,
6235 assert((!isTailCall || PerformTailCallOpt) &&
6236 "isTailCall set when tail-call optimizations are disabled!");
6238 // Handle all of the outgoing arguments.
6239 SmallVector<ISD::OutputArg, 32> Outs;
6240 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6241 SmallVector<EVT, 4> ValueVTs;
6242 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6243 for (unsigned Value = 0, NumValues = ValueVTs.size();
6244 Value != NumValues; ++Value) {
6245 EVT VT = ValueVTs[Value];
6246 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6247 SDValue Op = SDValue(Args[i].Node.getNode(),
6248 Args[i].Node.getResNo() + Value);
6249 ISD::ArgFlagsTy Flags;
6250 unsigned OriginalAlignment =
6251 getTargetData()->getABITypeAlignment(ArgTy);
6257 if (Args[i].isInReg)
6261 if (Args[i].isByVal) {
6263 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
6264 const Type *ElementTy = Ty->getElementType();
6265 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
6266 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
6267 // For ByVal, alignment should come from FE. BE will guess if this
6268 // info is not there but there are cases it cannot get right.
6269 if (Args[i].Alignment)
6270 FrameAlign = Args[i].Alignment;
6271 Flags.setByValAlign(FrameAlign);
6272 Flags.setByValSize(FrameSize);
6276 Flags.setOrigAlign(OriginalAlignment);
6278 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6279 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6280 SmallVector<SDValue, 4> Parts(NumParts);
6281 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6284 ExtendKind = ISD::SIGN_EXTEND;
6285 else if (Args[i].isZExt)
6286 ExtendKind = ISD::ZERO_EXTEND;
6288 getCopyToParts(DAG, dl, Order, Op, &Parts[0], NumParts,
6289 PartVT, ExtendKind);
6291 for (unsigned j = 0; j != NumParts; ++j) {
6292 // if it isn't first piece, alignment must be 1
6293 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
6294 if (NumParts > 1 && j == 0)
6295 MyFlags.Flags.setSplit();
6297 MyFlags.Flags.setOrigAlign(1);
6299 Outs.push_back(MyFlags);
6304 // Handle the incoming return values from the call.
6305 SmallVector<ISD::InputArg, 32> Ins;
6306 SmallVector<EVT, 4> RetTys;
6307 ComputeValueVTs(*this, RetTy, RetTys);
6308 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6310 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6311 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6312 for (unsigned i = 0; i != NumRegs; ++i) {
6313 ISD::InputArg MyFlags;
6314 MyFlags.VT = RegisterVT;
6315 MyFlags.Used = isReturnValueUsed;
6317 MyFlags.Flags.setSExt();
6319 MyFlags.Flags.setZExt();
6321 MyFlags.Flags.setInReg();
6322 Ins.push_back(MyFlags);
6326 // Check if target-dependent constraints permit a tail call here.
6327 // Target-independent constraints should be checked by the caller.
6329 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
6332 SmallVector<SDValue, 4> InVals;
6333 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6334 Outs, Ins, dl, DAG, InVals);
6336 // Verify that the target's LowerCall behaved as expected.
6337 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6338 "LowerCall didn't return a valid chain!");
6339 assert((!isTailCall || InVals.empty()) &&
6340 "LowerCall emitted a return value for a tail call!");
6341 assert((isTailCall || InVals.size() == Ins.size()) &&
6342 "LowerCall didn't emit the correct number of values!");
6343 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6344 assert(InVals[i].getNode() &&
6345 "LowerCall emitted a null value!");
6346 assert(Ins[i].VT == InVals[i].getValueType() &&
6347 "LowerCall emitted a value with the wrong type!");
6350 if (DisableScheduling)
6351 DAG.AssignOrdering(Chain.getNode(), Order);
6353 // For a tail call, the return value is merely live-out and there aren't
6354 // any nodes in the DAG representing it. Return a special value to
6355 // indicate that a tail call has been emitted and no more Instructions
6356 // should be processed in the current block.
6359 return std::make_pair(SDValue(), SDValue());
6362 // Collect the legal value parts into potentially illegal values
6363 // that correspond to the original function's return values.
6364 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6366 AssertOp = ISD::AssertSext;
6368 AssertOp = ISD::AssertZext;
6369 SmallVector<SDValue, 4> ReturnValues;
6370 unsigned CurReg = 0;
6371 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6373 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6374 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6376 SDValue ReturnValue =
6377 getCopyFromParts(DAG, dl, Order, &InVals[CurReg], NumRegs,
6378 RegisterVT, VT, AssertOp);
6379 ReturnValues.push_back(ReturnValue);
6380 if (DisableScheduling)
6381 DAG.AssignOrdering(ReturnValue.getNode(), Order);
6385 // For a function returning void, there is no return value. We can't create
6386 // such a node, so we just return a null return value in that case. In
6387 // that case, nothing will actualy look at the value.
6388 if (ReturnValues.empty())
6389 return std::make_pair(SDValue(), Chain);
6391 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6392 DAG.getVTList(&RetTys[0], RetTys.size()),
6393 &ReturnValues[0], ReturnValues.size());
6394 if (DisableScheduling)
6395 DAG.AssignOrdering(Res.getNode(), Order);
6396 return std::make_pair(Res, Chain);
6399 void TargetLowering::LowerOperationWrapper(SDNode *N,
6400 SmallVectorImpl<SDValue> &Results,
6401 SelectionDAG &DAG) {
6402 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6404 Results.push_back(Res);
6407 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6408 llvm_unreachable("LowerOperation not implemented for this target!");
6412 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
6413 SDValue Op = getValue(V);
6414 assert((Op.getOpcode() != ISD::CopyFromReg ||
6415 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6416 "Copy from a reg to the same reg!");
6417 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6419 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6420 SDValue Chain = DAG.getEntryNode();
6421 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0);
6422 PendingExports.push_back(Chain);
6425 #include "llvm/CodeGen/SelectionDAGISel.h"
6427 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
6428 // If this is the entry block, emit arguments.
6429 Function &F = *LLVMBB->getParent();
6430 SelectionDAG &DAG = SDB->DAG;
6431 SDValue OldRoot = DAG.getRoot();
6432 DebugLoc dl = SDB->getCurDebugLoc();
6433 const TargetData *TD = TLI.getTargetData();
6434 SmallVector<ISD::InputArg, 16> Ins;
6436 // Check whether the function can return without sret-demotion.
6437 SmallVector<EVT, 4> OutVTs;
6438 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
6439 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6440 OutVTs, OutsFlags, TLI);
6441 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
6443 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
6444 OutVTs, OutsFlags, DAG);
6445 if (!FLI.CanLowerReturn) {
6446 // Put in an sret pointer parameter before all the other parameters.
6447 SmallVector<EVT, 1> ValueVTs;
6448 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6450 // NOTE: Assuming that a pointer will never break down to more than one VT
6452 ISD::ArgFlagsTy Flags;
6454 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
6455 ISD::InputArg RetArg(Flags, RegisterVT, true);
6456 Ins.push_back(RetArg);
6459 // Set up the incoming argument description vector.
6461 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
6462 I != E; ++I, ++Idx) {
6463 SmallVector<EVT, 4> ValueVTs;
6464 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6465 bool isArgValueUsed = !I->use_empty();
6466 for (unsigned Value = 0, NumValues = ValueVTs.size();
6467 Value != NumValues; ++Value) {
6468 EVT VT = ValueVTs[Value];
6469 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6470 ISD::ArgFlagsTy Flags;
6471 unsigned OriginalAlignment =
6472 TD->getABITypeAlignment(ArgTy);
6474 if (F.paramHasAttr(Idx, Attribute::ZExt))
6476 if (F.paramHasAttr(Idx, Attribute::SExt))
6478 if (F.paramHasAttr(Idx, Attribute::InReg))
6480 if (F.paramHasAttr(Idx, Attribute::StructRet))
6482 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6484 const PointerType *Ty = cast<PointerType>(I->getType());
6485 const Type *ElementTy = Ty->getElementType();
6486 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6487 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
6488 // For ByVal, alignment should be passed from FE. BE will guess if
6489 // this info is not there but there are cases it cannot get right.
6490 if (F.getParamAlignment(Idx))
6491 FrameAlign = F.getParamAlignment(Idx);
6492 Flags.setByValAlign(FrameAlign);
6493 Flags.setByValSize(FrameSize);
6495 if (F.paramHasAttr(Idx, Attribute::Nest))
6497 Flags.setOrigAlign(OriginalAlignment);
6499 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6500 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6501 for (unsigned i = 0; i != NumRegs; ++i) {
6502 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6503 if (NumRegs > 1 && i == 0)
6504 MyFlags.Flags.setSplit();
6505 // if it isn't first piece, alignment must be 1
6507 MyFlags.Flags.setOrigAlign(1);
6508 Ins.push_back(MyFlags);
6513 // Call the target to set up the argument values.
6514 SmallVector<SDValue, 8> InVals;
6515 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6519 // Verify that the target's LowerFormalArguments behaved as expected.
6520 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6521 "LowerFormalArguments didn't return a valid chain!");
6522 assert(InVals.size() == Ins.size() &&
6523 "LowerFormalArguments didn't emit the correct number of values!");
6525 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6526 assert(InVals[i].getNode() &&
6527 "LowerFormalArguments emitted a null value!");
6528 assert(Ins[i].VT == InVals[i].getValueType() &&
6529 "LowerFormalArguments emitted a value with the wrong type!");
6533 // Update the DAG with the new chain value resulting from argument lowering.
6534 DAG.setRoot(NewRoot);
6536 // Set up the argument values.
6539 if (!FLI.CanLowerReturn) {
6540 // Create a virtual register for the sret pointer, and put in a copy
6541 // from the sret argument into it.
6542 SmallVector<EVT, 1> ValueVTs;
6543 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6544 EVT VT = ValueVTs[0];
6545 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6546 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6547 SDValue ArgValue = getCopyFromParts(DAG, dl, 0, &InVals[0], 1,
6548 RegVT, VT, AssertOp);
6550 MachineFunction& MF = SDB->DAG.getMachineFunction();
6551 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6552 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6553 FLI.DemoteRegister = SRetReg;
6554 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), SRetReg, ArgValue);
6555 DAG.setRoot(NewRoot);
6557 // i indexes lowered arguments. Bump it past the hidden sret argument.
6558 // Idx indexes LLVM arguments. Don't touch it.
6562 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6564 SmallVector<SDValue, 4> ArgValues;
6565 SmallVector<EVT, 4> ValueVTs;
6566 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6567 unsigned NumValues = ValueVTs.size();
6568 for (unsigned Value = 0; Value != NumValues; ++Value) {
6569 EVT VT = ValueVTs[Value];
6570 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6571 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6573 if (!I->use_empty()) {
6574 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6575 if (F.paramHasAttr(Idx, Attribute::SExt))
6576 AssertOp = ISD::AssertSext;
6577 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6578 AssertOp = ISD::AssertZext;
6580 ArgValues.push_back(getCopyFromParts(DAG, dl, 0, &InVals[i],
6581 NumParts, PartVT, VT,
6588 if (!I->use_empty()) {
6589 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6590 SDB->getCurDebugLoc());
6591 SDB->setValue(I, Res);
6593 // If this argument is live outside of the entry block, insert a copy from
6594 // whereever we got it to the vreg that other BB's will reference it as.
6595 SDB->CopyToExportRegsIfNeeded(I);
6599 assert(i == InVals.size() && "Argument register count mismatch!");
6601 // Finally, if the target has anything special to do, allow it to do so.
6602 // FIXME: this should insert code into the DAG!
6603 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
6606 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6607 /// ensure constants are generated when needed. Remember the virtual registers
6608 /// that need to be added to the Machine PHI nodes as input. We cannot just
6609 /// directly add them, because expansion might result in multiple MBB's for one
6610 /// BB. As such, the start of the BB might correspond to a different MBB than
6614 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6615 TerminatorInst *TI = LLVMBB->getTerminator();
6617 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6619 // Check successor nodes' PHI nodes that expect a constant to be available
6621 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6622 BasicBlock *SuccBB = TI->getSuccessor(succ);
6623 if (!isa<PHINode>(SuccBB->begin())) continue;
6624 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6626 // If this terminator has multiple identical successors (common for
6627 // switches), only handle each succ once.
6628 if (!SuccsHandled.insert(SuccMBB)) continue;
6630 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6633 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6634 // nodes and Machine PHI nodes, but the incoming operands have not been
6636 for (BasicBlock::iterator I = SuccBB->begin();
6637 (PN = dyn_cast<PHINode>(I)); ++I) {
6638 // Ignore dead phi's.
6639 if (PN->use_empty()) continue;
6642 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6644 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6645 unsigned &RegOut = SDB->ConstantsOut[C];
6647 RegOut = FuncInfo->CreateRegForValue(C);
6648 SDB->CopyValueToVirtualRegister(C, RegOut);
6652 Reg = FuncInfo->ValueMap[PHIOp];
6654 assert(isa<AllocaInst>(PHIOp) &&
6655 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6656 "Didn't codegen value into a register!??");
6657 Reg = FuncInfo->CreateRegForValue(PHIOp);
6658 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
6662 // Remember that this register needs to added to the machine PHI node as
6663 // the input for this MBB.
6664 SmallVector<EVT, 4> ValueVTs;
6665 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6666 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6667 EVT VT = ValueVTs[vti];
6668 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6669 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6670 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6671 Reg += NumRegisters;
6675 SDB->ConstantsOut.clear();
6678 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6679 /// supports legal types, and it emits MachineInstrs directly instead of
6680 /// creating SelectionDAG nodes.
6683 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6685 TerminatorInst *TI = LLVMBB->getTerminator();
6687 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6688 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
6690 // Check successor nodes' PHI nodes that expect a constant to be available
6692 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6693 BasicBlock *SuccBB = TI->getSuccessor(succ);
6694 if (!isa<PHINode>(SuccBB->begin())) continue;
6695 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6697 // If this terminator has multiple identical successors (common for
6698 // switches), only handle each succ once.
6699 if (!SuccsHandled.insert(SuccMBB)) continue;
6701 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6704 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6705 // nodes and Machine PHI nodes, but the incoming operands have not been
6707 for (BasicBlock::iterator I = SuccBB->begin();
6708 (PN = dyn_cast<PHINode>(I)); ++I) {
6709 // Ignore dead phi's.
6710 if (PN->use_empty()) continue;
6712 // Only handle legal types. Two interesting things to note here. First,
6713 // by bailing out early, we may leave behind some dead instructions,
6714 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6715 // own moves. Second, this check is necessary becuase FastISel doesn't
6716 // use CreateRegForValue to create registers, so it always creates
6717 // exactly one register for each non-void instruction.
6718 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6719 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6722 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6724 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6729 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6731 unsigned Reg = F->getRegForValue(PHIOp);
6733 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6736 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));