SelectionDAGBuilder.cpp revision f2052d5e0eb5028a06f41d2cebb8e22b6876ebc0
1//===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
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/Analysis/ConstantFolding.h"
21#include "llvm/Constants.h"
22#include "llvm/CallingConv.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Function.h"
25#include "llvm/GlobalVariable.h"
26#include "llvm/InlineAsm.h"
27#include "llvm/Instructions.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/IntrinsicInst.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"
57#include <algorithm>
58using namespace llvm;
59
60/// LimitFloatPrecision - Generate low-precision inline sequences for
61/// some float libcalls (6, 8 or 12 bits).
62static unsigned LimitFloatPrecision;
63
64static cl::opt<unsigned, true>
65LimitFPPrecision("limit-float-precision",
66                 cl::desc("Generate low-precision inline sequences "
67                          "for some float libcalls"),
68                 cl::location(LimitFloatPrecision),
69                 cl::init(0));
70
71namespace {
72  /// RegsForValue - This struct represents the registers (physical or virtual)
73  /// that a particular set of values is assigned, and the type information
74  /// about the value. The most common situation is to represent one value at a
75  /// time, but struct or array values are handled element-wise as multiple
76  /// values.  The splitting of aggregates is performed recursively, so that we
77  /// never have aggregate-typed registers. The values at this point do not
78  /// necessarily have legal types, so each value may require one or more
79  /// registers of some legal type.
80  ///
81  struct RegsForValue {
82    /// TLI - The TargetLowering object.
83    ///
84    const TargetLowering *TLI;
85
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.
88    ///
89    SmallVector<EVT, 4> ValueVTs;
90
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.)
95    ///
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.
99    ///
100    SmallVector<EVT, 4> RegVTs;
101
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.
105    ///
106    SmallVector<unsigned, 4> Regs;
107
108    RegsForValue() : TLI(0) {}
109
110    RegsForValue(const TargetLowering &tli,
111                 const SmallVector<unsigned, 4> &regs,
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> &regs,
116                 const SmallVector<EVT, 4> &regvts,
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);
122
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);
130        Reg += NumRegs;
131      }
132    }
133
134    /// append - Add the specified values to this one.
135    void append(const RegsForValue &RHS) {
136      TLI = RHS.TLI;
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());
140    }
141
142
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;
149
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;
156
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;
164  };
165}
166
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).
172static 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);
180
181  if (NumParts > 1) {
182    // Assemble the value from multiple parts.
183    if (!ValueVT.isVector() && ValueVT.isInteger()) {
184      unsigned PartBits = PartVT.getSizeInBits();
185      unsigned ValueBits = ValueVT.getSizeInBits();
186
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);
193      SDValue Lo, Hi;
194
195      EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
196
197      if (RoundParts > 2) {
198        Lo = getCopyFromParts(DAG, dl, Order, Parts, RoundParts / 2,
199                              PartVT, HalfVT);
200        Hi = getCopyFromParts(DAG, dl, Order, Parts + RoundParts / 2,
201                              RoundParts / 2, PartVT, HalfVT);
202      } else {
203        Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
204        Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
205      }
206
207      if (TLI.isBigEndian())
208        std::swap(Lo, Hi);
209
210      Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
211
212      if (DisableScheduling) {
213        DAG.AssignOrdering(Lo.getNode(), Order);
214        DAG.AssignOrdering(Hi.getNode(), Order);
215        DAG.AssignOrdering(Val.getNode(), Order);
216      }
217
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);
224
225        // Combine the round and odd parts.
226        Lo = Val;
227        if (TLI.isBigEndian())
228          std::swap(Lo, Hi);
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);
240      }
241    } else if (ValueVT.isVector()) {
242      // Handle a multi-element vector.
243      EVT IntermediateVT, RegisterVT;
244      unsigned NumIntermediates;
245      unsigned NumRegs =
246        TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
247                                   NumIntermediates, RegisterVT);
248      assert(NumRegs == NumParts
249             && "Part count doesn't match vector breakdown!");
250      NumParts = NumRegs; // Silence a compiler warning.
251      assert(RegisterVT == PartVT
252             && "Part type doesn't match vector breakdown!");
253      assert(RegisterVT == Parts[0].getValueType() &&
254             "Part type doesn't match part!");
255
256      // Assemble the parts into intermediate operands.
257      SmallVector<SDValue, 8> Ops(NumIntermediates);
258      if (NumIntermediates == NumParts) {
259        // If the register was not expanded, truncate or copy the value,
260        // as appropriate.
261        for (unsigned i = 0; i != NumParts; ++i)
262          Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i], 1,
263                                    PartVT, IntermediateVT);
264      } else if (NumParts > 0) {
265        // If the intermediate type was expanded, build the intermediate
266        // operands from the parts.
267        assert(NumParts % NumIntermediates == 0 &&
268               "Must expand into a divisible number of parts!");
269        unsigned Factor = NumParts / NumIntermediates;
270        for (unsigned i = 0; i != NumIntermediates; ++i)
271          Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i * Factor], Factor,
272                                    PartVT, IntermediateVT);
273      }
274
275      // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
276      // intermediate operands.
277      Val = DAG.getNode(IntermediateVT.isVector() ?
278                        ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
279                        ValueVT, &Ops[0], NumIntermediates);
280      if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
281    } else if (PartVT.isFloatingPoint()) {
282      // FP split into multiple FP parts (for ppcf128)
283      assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
284             "Unexpected split");
285      SDValue Lo, Hi;
286      Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
287      Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
288      if (TLI.isBigEndian())
289        std::swap(Lo, Hi);
290      Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
291
292      if (DisableScheduling) {
293        DAG.AssignOrdering(Hi.getNode(), Order);
294        DAG.AssignOrdering(Lo.getNode(), Order);
295        DAG.AssignOrdering(Val.getNode(), Order);
296      }
297    } else {
298      // FP split into integer parts (soft fp)
299      assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
300             !PartVT.isVector() && "Unexpected split");
301      EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
302      Val = getCopyFromParts(DAG, dl, Order, Parts, NumParts, PartVT, IntVT);
303    }
304  }
305
306  // There is now one part, held in Val.  Correct it to match ValueVT.
307  PartVT = Val.getValueType();
308
309  if (PartVT == ValueVT)
310    return Val;
311
312  if (PartVT.isVector()) {
313    assert(ValueVT.isVector() && "Unknown vector conversion!");
314    SDValue Res = DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
315    if (DisableScheduling)
316      DAG.AssignOrdering(Res.getNode(), Order);
317    return Res;
318  }
319
320  if (ValueVT.isVector()) {
321    assert(ValueVT.getVectorElementType() == PartVT &&
322           ValueVT.getVectorNumElements() == 1 &&
323           "Only trivial scalar-to-vector conversions should get here!");
324    SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
325    if (DisableScheduling)
326      DAG.AssignOrdering(Res.getNode(), Order);
327    return Res;
328  }
329
330  if (PartVT.isInteger() &&
331      ValueVT.isInteger()) {
332    if (ValueVT.bitsLT(PartVT)) {
333      // For a truncate, see if we have any information to
334      // indicate whether the truncated bits will always be
335      // zero or sign-extension.
336      if (AssertOp != ISD::DELETED_NODE)
337        Val = DAG.getNode(AssertOp, dl, PartVT, Val,
338                          DAG.getValueType(ValueVT));
339      if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
340      Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
341      if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
342      return Val;
343    } else {
344      Val = DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
345      if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
346      return Val;
347    }
348  }
349
350  if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
351    if (ValueVT.bitsLT(Val.getValueType())) {
352      // FP_ROUND's are always exact here.
353      Val = DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
354                        DAG.getIntPtrConstant(1));
355      if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
356      return Val;
357    }
358
359    Val = DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
360    if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
361    return Val;
362  }
363
364  if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
365    Val = DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
366    if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
367    return Val;
368  }
369
370  llvm_unreachable("Unknown mismatch!");
371  return SDValue();
372}
373
374/// getCopyToParts - Create a series of nodes that contain the specified value
375/// split into legal parts.  If the parts contain more bits than Val, then, for
376/// integers, ExtendKind can be used to specify how to generate the extra bits.
377static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
378                           SDValue Val, SDValue *Parts, unsigned NumParts,
379                           EVT PartVT,
380                           ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
381  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
382  EVT PtrVT = TLI.getPointerTy();
383  EVT ValueVT = Val.getValueType();
384  unsigned PartBits = PartVT.getSizeInBits();
385  unsigned OrigNumParts = NumParts;
386  assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
387
388  if (!NumParts)
389    return;
390
391  if (!ValueVT.isVector()) {
392    if (PartVT == ValueVT) {
393      assert(NumParts == 1 && "No-op copy with multiple parts!");
394      Parts[0] = Val;
395      return;
396    }
397
398    if (NumParts * PartBits > ValueVT.getSizeInBits()) {
399      // If the parts cover more bits than the value has, promote the value.
400      if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
401        assert(NumParts == 1 && "Do not know what to promote to!");
402        Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
403      } else if (PartVT.isInteger() && ValueVT.isInteger()) {
404        ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
405        Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
406      } else {
407        llvm_unreachable("Unknown mismatch!");
408      }
409    } else if (PartBits == ValueVT.getSizeInBits()) {
410      // Different types of the same size.
411      assert(NumParts == 1 && PartVT != ValueVT);
412      Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
413    } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
414      // If the parts cover less bits than value has, truncate the value.
415      if (PartVT.isInteger() && ValueVT.isInteger()) {
416        ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
417        Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
418      } else {
419        llvm_unreachable("Unknown mismatch!");
420      }
421    }
422
423    if (DisableScheduling) DAG.AssignOrdering(Val.getNode(), Order);
424
425    // The value may have changed - recompute ValueVT.
426    ValueVT = Val.getValueType();
427    assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
428           "Failed to tile the value with PartVT!");
429
430    if (NumParts == 1) {
431      assert(PartVT == ValueVT && "Type conversion failed!");
432      Parts[0] = Val;
433      return;
434    }
435
436    // Expand the value into multiple parts.
437    if (NumParts & (NumParts - 1)) {
438      // The number of parts is not a power of 2.  Split off and copy the tail.
439      assert(PartVT.isInteger() && ValueVT.isInteger() &&
440             "Do not know what to expand to!");
441      unsigned RoundParts = 1 << Log2_32(NumParts);
442      unsigned RoundBits = RoundParts * PartBits;
443      unsigned OddParts = NumParts - RoundParts;
444      SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
445                                   DAG.getConstant(RoundBits,
446                                                   TLI.getPointerTy()));
447      getCopyToParts(DAG, dl, Order, OddVal, Parts + RoundParts,
448                     OddParts, PartVT);
449
450      if (TLI.isBigEndian())
451        // The odd parts were reversed by getCopyToParts - unreverse them.
452        std::reverse(Parts + RoundParts, Parts + NumParts);
453
454      NumParts = RoundParts;
455      ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
456      Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
457
458      if (DisableScheduling) {
459        DAG.AssignOrdering(OddVal.getNode(), Order);
460        DAG.AssignOrdering(Val.getNode(), Order);
461      }
462    }
463
464    // The number of parts is a power of 2.  Repeatedly bisect the value using
465    // EXTRACT_ELEMENT.
466    Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
467                           EVT::getIntegerVT(*DAG.getContext(),
468                                             ValueVT.getSizeInBits()),
469                           Val);
470
471    if (DisableScheduling)
472      DAG.AssignOrdering(Parts[0].getNode(), Order);
473
474    for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
475      for (unsigned i = 0; i < NumParts; i += StepSize) {
476        unsigned ThisBits = StepSize * PartBits / 2;
477        EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
478        SDValue &Part0 = Parts[i];
479        SDValue &Part1 = Parts[i+StepSize/2];
480
481        Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
482                            ThisVT, Part0,
483                            DAG.getConstant(1, PtrVT));
484        Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
485                            ThisVT, Part0,
486                            DAG.getConstant(0, PtrVT));
487
488        if (DisableScheduling) {
489          DAG.AssignOrdering(Part0.getNode(), Order);
490          DAG.AssignOrdering(Part1.getNode(), Order);
491        }
492
493        if (ThisBits == PartBits && ThisVT != PartVT) {
494          Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
495                                                PartVT, Part0);
496          Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
497                                                PartVT, Part1);
498          if (DisableScheduling) {
499            DAG.AssignOrdering(Part0.getNode(), Order);
500            DAG.AssignOrdering(Part1.getNode(), Order);
501          }
502        }
503      }
504    }
505
506    if (TLI.isBigEndian())
507      std::reverse(Parts, Parts + OrigNumParts);
508
509    return;
510  }
511
512  // Vector ValueVT.
513  if (NumParts == 1) {
514    if (PartVT != ValueVT) {
515      if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
516        Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
517      } else {
518        assert(ValueVT.getVectorElementType() == PartVT &&
519               ValueVT.getVectorNumElements() == 1 &&
520               "Only trivial vector-to-scalar conversions should get here!");
521        Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
522                          PartVT, Val,
523                          DAG.getConstant(0, PtrVT));
524      }
525    }
526
527    if (DisableScheduling)
528      DAG.AssignOrdering(Val.getNode(), Order);
529
530    Parts[0] = Val;
531    return;
532  }
533
534  // Handle a multi-element vector.
535  EVT IntermediateVT, RegisterVT;
536  unsigned NumIntermediates;
537  unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
538                              IntermediateVT, NumIntermediates, RegisterVT);
539  unsigned NumElements = ValueVT.getVectorNumElements();
540
541  assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
542  NumParts = NumRegs; // Silence a compiler warning.
543  assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
544
545  // Split the vector into intermediate operands.
546  SmallVector<SDValue, 8> Ops(NumIntermediates);
547  for (unsigned i = 0; i != NumIntermediates; ++i) {
548    if (IntermediateVT.isVector())
549      Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
550                           IntermediateVT, Val,
551                           DAG.getConstant(i * (NumElements / NumIntermediates),
552                                           PtrVT));
553    else
554      Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
555                           IntermediateVT, Val,
556                           DAG.getConstant(i, PtrVT));
557
558    if (DisableScheduling)
559      DAG.AssignOrdering(Ops[i].getNode(), Order);
560  }
561
562  // Split the intermediate operands into legal parts.
563  if (NumParts == NumIntermediates) {
564    // If the register was not expanded, promote or copy the value,
565    // as appropriate.
566    for (unsigned i = 0; i != NumParts; ++i)
567      getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i], 1, PartVT);
568  } else if (NumParts > 0) {
569    // If the intermediate type was expanded, split each the value into
570    // legal parts.
571    assert(NumParts % NumIntermediates == 0 &&
572           "Must expand into a divisible number of parts!");
573    unsigned Factor = NumParts / NumIntermediates;
574    for (unsigned i = 0; i != NumIntermediates; ++i)
575      getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i*Factor], Factor, PartVT);
576  }
577}
578
579
580void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
581  AA = &aa;
582  GFI = gfi;
583  TD = DAG.getTarget().getTargetData();
584}
585
586/// clear - Clear out the curret SelectionDAG and the associated
587/// state and prepare this SelectionDAGBuilder object to be used
588/// for a new block. This doesn't clear out information about
589/// additional blocks that are needed to complete switch lowering
590/// or PHI node updating; that information is cleared out as it is
591/// consumed.
592void SelectionDAGBuilder::clear() {
593  NodeMap.clear();
594  PendingLoads.clear();
595  PendingExports.clear();
596  EdgeMapping.clear();
597  DAG.clear();
598  CurDebugLoc = DebugLoc::getUnknownLoc();
599  HasTailCall = false;
600}
601
602/// getRoot - Return the current virtual root of the Selection DAG,
603/// flushing any PendingLoad items. This must be done before emitting
604/// a store or any other node that may need to be ordered after any
605/// prior load instructions.
606///
607SDValue SelectionDAGBuilder::getRoot() {
608  if (PendingLoads.empty())
609    return DAG.getRoot();
610
611  if (PendingLoads.size() == 1) {
612    SDValue Root = PendingLoads[0];
613    DAG.setRoot(Root);
614    PendingLoads.clear();
615    return Root;
616  }
617
618  // Otherwise, we have to make a token factor node.
619  SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
620                               &PendingLoads[0], PendingLoads.size());
621  PendingLoads.clear();
622  DAG.setRoot(Root);
623  return Root;
624}
625
626/// getControlRoot - Similar to getRoot, but instead of flushing all the
627/// PendingLoad items, flush all the PendingExports items. It is necessary
628/// to do this before emitting a terminator instruction.
629///
630SDValue SelectionDAGBuilder::getControlRoot() {
631  SDValue Root = DAG.getRoot();
632
633  if (PendingExports.empty())
634    return Root;
635
636  // Turn all of the CopyToReg chains into one factored node.
637  if (Root.getOpcode() != ISD::EntryToken) {
638    unsigned i = 0, e = PendingExports.size();
639    for (; i != e; ++i) {
640      assert(PendingExports[i].getNode()->getNumOperands() > 1);
641      if (PendingExports[i].getNode()->getOperand(0) == Root)
642        break;  // Don't add the root if we already indirectly depend on it.
643    }
644
645    if (i == e)
646      PendingExports.push_back(Root);
647  }
648
649  Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
650                     &PendingExports[0],
651                     PendingExports.size());
652  PendingExports.clear();
653  DAG.setRoot(Root);
654  return Root;
655}
656
657void SelectionDAGBuilder::visit(Instruction &I) {
658  visit(I.getOpcode(), I);
659}
660
661void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
662  // We're processing a new instruction.
663  ++SDNodeOrder;
664
665  // Note: this doesn't use InstVisitor, because it has to work with
666  // ConstantExpr's in addition to instructions.
667  switch (Opcode) {
668  default: llvm_unreachable("Unknown instruction type encountered!");
669    // Build the switch statement using the Instruction.def file.
670#define HANDLE_INST(NUM, OPCODE, CLASS) \
671  case Instruction::OPCODE: return visit##OPCODE((CLASS&)I);
672#include "llvm/Instruction.def"
673  }
674}
675
676SDValue SelectionDAGBuilder::getValue(const Value *V) {
677  SDValue &N = NodeMap[V];
678  if (N.getNode()) return N;
679
680  if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
681    EVT VT = TLI.getValueType(V->getType(), true);
682
683    if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
684      return N = DAG.getConstant(*CI, VT);
685
686    if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
687      return N = DAG.getGlobalAddress(GV, VT);
688
689    if (isa<ConstantPointerNull>(C))
690      return N = DAG.getConstant(0, TLI.getPointerTy());
691
692    if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
693      return N = DAG.getConstantFP(*CFP, VT);
694
695    if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
696      return N = DAG.getUNDEF(VT);
697
698    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
699      visit(CE->getOpcode(), *CE);
700      SDValue N1 = NodeMap[V];
701      assert(N1.getNode() && "visit didn't populate the ValueMap!");
702      return N1;
703    }
704
705    if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
706      SmallVector<SDValue, 4> Constants;
707      for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
708           OI != OE; ++OI) {
709        SDNode *Val = getValue(*OI).getNode();
710        // If the operand is an empty aggregate, there are no values.
711        if (!Val) continue;
712        // Add each leaf value from the operand to the Constants list
713        // to form a flattened list of all the values.
714        for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
715          Constants.push_back(SDValue(Val, i));
716      }
717
718      SDValue Res = DAG.getMergeValues(&Constants[0], Constants.size(),
719                                       getCurDebugLoc());
720      if (DisableScheduling)
721        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
722      return Res;
723    }
724
725    if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
726      assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
727             "Unknown struct or array constant!");
728
729      SmallVector<EVT, 4> ValueVTs;
730      ComputeValueVTs(TLI, C->getType(), ValueVTs);
731      unsigned NumElts = ValueVTs.size();
732      if (NumElts == 0)
733        return SDValue(); // empty struct
734      SmallVector<SDValue, 4> Constants(NumElts);
735      for (unsigned i = 0; i != NumElts; ++i) {
736        EVT EltVT = ValueVTs[i];
737        if (isa<UndefValue>(C))
738          Constants[i] = DAG.getUNDEF(EltVT);
739        else if (EltVT.isFloatingPoint())
740          Constants[i] = DAG.getConstantFP(0, EltVT);
741        else
742          Constants[i] = DAG.getConstant(0, EltVT);
743      }
744
745      SDValue Res = DAG.getMergeValues(&Constants[0], NumElts,
746                                       getCurDebugLoc());
747      if (DisableScheduling)
748        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
749      return Res;
750    }
751
752    if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
753      return DAG.getBlockAddress(BA, VT);
754
755    const VectorType *VecTy = cast<VectorType>(V->getType());
756    unsigned NumElements = VecTy->getNumElements();
757
758    // Now that we know the number and type of the elements, get that number of
759    // elements into the Ops array based on what kind of constant it is.
760    SmallVector<SDValue, 16> Ops;
761    if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
762      for (unsigned i = 0; i != NumElements; ++i)
763        Ops.push_back(getValue(CP->getOperand(i)));
764    } else {
765      assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
766      EVT EltVT = TLI.getValueType(VecTy->getElementType());
767
768      SDValue Op;
769      if (EltVT.isFloatingPoint())
770        Op = DAG.getConstantFP(0, EltVT);
771      else
772        Op = DAG.getConstant(0, EltVT);
773      Ops.assign(NumElements, Op);
774    }
775
776    // Create a BUILD_VECTOR node.
777    SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
778                              VT, &Ops[0], Ops.size());
779    if (DisableScheduling)
780      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
781
782    return NodeMap[V] = Res;
783  }
784
785  // If this is a static alloca, generate it as the frameindex instead of
786  // computation.
787  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
788    DenseMap<const AllocaInst*, int>::iterator SI =
789      FuncInfo.StaticAllocaMap.find(AI);
790    if (SI != FuncInfo.StaticAllocaMap.end())
791      return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
792  }
793
794  unsigned InReg = FuncInfo.ValueMap[V];
795  assert(InReg && "Value not in map!");
796
797  RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
798  SDValue Chain = DAG.getEntryNode();
799  return RFV.getCopyFromRegs(DAG, getCurDebugLoc(),
800                             SDNodeOrder, Chain, NULL);
801}
802
803/// Get the EVTs and ArgFlags collections that represent the return type
804/// of the given function.  This does not require a DAG or a return value, and
805/// is suitable for use before any DAGs for the function are constructed.
806static void getReturnInfo(const Type* ReturnType,
807                   Attributes attr, SmallVectorImpl<EVT> &OutVTs,
808                   SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
809                   TargetLowering &TLI,
810                   SmallVectorImpl<uint64_t> *Offsets = 0) {
811  SmallVector<EVT, 4> ValueVTs;
812  ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets);
813  unsigned NumValues = ValueVTs.size();
814  if ( NumValues == 0 ) return;
815
816  for (unsigned j = 0, f = NumValues; j != f; ++j) {
817    EVT VT = ValueVTs[j];
818    ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
819
820    if (attr & Attribute::SExt)
821      ExtendKind = ISD::SIGN_EXTEND;
822    else if (attr & Attribute::ZExt)
823      ExtendKind = ISD::ZERO_EXTEND;
824
825    // FIXME: C calling convention requires the return type to be promoted to
826    // at least 32-bit. But this is not necessary for non-C calling
827    // conventions. The frontend should mark functions whose return values
828    // require promoting with signext or zeroext attributes.
829    if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
830      EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
831      if (VT.bitsLT(MinVT))
832        VT = MinVT;
833    }
834
835    unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
836    EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
837    // 'inreg' on function refers to return value
838    ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
839    if (attr & Attribute::InReg)
840      Flags.setInReg();
841
842    // Propagate extension type if any
843    if (attr & Attribute::SExt)
844      Flags.setSExt();
845    else if (attr & Attribute::ZExt)
846      Flags.setZExt();
847
848    for (unsigned i = 0; i < NumParts; ++i) {
849      OutVTs.push_back(PartVT);
850      OutFlags.push_back(Flags);
851    }
852  }
853}
854
855void SelectionDAGBuilder::visitRet(ReturnInst &I) {
856  SDValue Chain = getControlRoot();
857  SmallVector<ISD::OutputArg, 8> Outs;
858  FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
859
860  if (!FLI.CanLowerReturn) {
861    unsigned DemoteReg = FLI.DemoteRegister;
862    const Function *F = I.getParent()->getParent();
863
864    // Emit a store of the return value through the virtual register.
865    // Leave Outs empty so that LowerReturn won't try to load return
866    // registers the usual way.
867    SmallVector<EVT, 1> PtrValueVTs;
868    ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
869                    PtrValueVTs);
870
871    SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
872    SDValue RetOp = getValue(I.getOperand(0));
873
874    SmallVector<EVT, 4> ValueVTs;
875    SmallVector<uint64_t, 4> Offsets;
876    ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
877    unsigned NumValues = ValueVTs.size();
878
879    SmallVector<SDValue, 4> Chains(NumValues);
880    EVT PtrVT = PtrValueVTs[0];
881    for (unsigned i = 0; i != NumValues; ++i) {
882      SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
883                                DAG.getConstant(Offsets[i], PtrVT));
884      Chains[i] =
885        DAG.getStore(Chain, getCurDebugLoc(),
886                     SDValue(RetOp.getNode(), RetOp.getResNo() + i),
887                     Add, NULL, Offsets[i], false, 0);
888
889      if (DisableScheduling) {
890        DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
891        DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder);
892      }
893    }
894
895    Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
896                        MVT::Other, &Chains[0], NumValues);
897
898    if (DisableScheduling)
899      DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
900  } else {
901    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
902      SmallVector<EVT, 4> ValueVTs;
903      ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
904      unsigned NumValues = ValueVTs.size();
905      if (NumValues == 0) continue;
906
907      SDValue RetOp = getValue(I.getOperand(i));
908      for (unsigned j = 0, f = NumValues; j != f; ++j) {
909        EVT VT = ValueVTs[j];
910
911        ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
912
913        const Function *F = I.getParent()->getParent();
914        if (F->paramHasAttr(0, Attribute::SExt))
915          ExtendKind = ISD::SIGN_EXTEND;
916        else if (F->paramHasAttr(0, Attribute::ZExt))
917          ExtendKind = ISD::ZERO_EXTEND;
918
919        // FIXME: C calling convention requires the return type to be promoted
920        // to at least 32-bit. But this is not necessary for non-C calling
921        // conventions. The frontend should mark functions whose return values
922        // require promoting with signext or zeroext attributes.
923        if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
924          EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
925          if (VT.bitsLT(MinVT))
926            VT = MinVT;
927        }
928
929        unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
930        EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
931        SmallVector<SDValue, 4> Parts(NumParts);
932        getCopyToParts(DAG, getCurDebugLoc(), SDNodeOrder,
933                       SDValue(RetOp.getNode(), RetOp.getResNo() + j),
934                       &Parts[0], NumParts, PartVT, ExtendKind);
935
936        // 'inreg' on function refers to return value
937        ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
938        if (F->paramHasAttr(0, Attribute::InReg))
939          Flags.setInReg();
940
941        // Propagate extension type if any
942        if (F->paramHasAttr(0, Attribute::SExt))
943          Flags.setSExt();
944        else if (F->paramHasAttr(0, Attribute::ZExt))
945          Flags.setZExt();
946
947        for (unsigned i = 0; i < NumParts; ++i)
948          Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
949      }
950    }
951  }
952
953  bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
954  CallingConv::ID CallConv =
955    DAG.getMachineFunction().getFunction()->getCallingConv();
956  Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
957                          Outs, getCurDebugLoc(), DAG);
958
959  // Verify that the target's LowerReturn behaved as expected.
960  assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
961         "LowerReturn didn't return a valid chain!");
962
963  // Update the DAG with the new chain value resulting from return lowering.
964  DAG.setRoot(Chain);
965
966  if (DisableScheduling)
967    DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
968}
969
970/// CopyToExportRegsIfNeeded - If the given value has virtual registers
971/// created for it, emit nodes to copy the value into the virtual
972/// registers.
973void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
974  if (!V->use_empty()) {
975    DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
976    if (VMI != FuncInfo.ValueMap.end())
977      CopyValueToVirtualRegister(V, VMI->second);
978  }
979}
980
981/// ExportFromCurrentBlock - If this condition isn't known to be exported from
982/// the current basic block, add it to ValueMap now so that we'll get a
983/// CopyTo/FromReg.
984void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
985  // No need to export constants.
986  if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
987
988  // Already exported?
989  if (FuncInfo.isExportedInst(V)) return;
990
991  unsigned Reg = FuncInfo.InitializeRegForValue(V);
992  CopyValueToVirtualRegister(V, Reg);
993}
994
995bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
996                                                     const BasicBlock *FromBB) {
997  // The operands of the setcc have to be in this block.  We don't know
998  // how to export them from some other block.
999  if (Instruction *VI = dyn_cast<Instruction>(V)) {
1000    // Can export from current BB.
1001    if (VI->getParent() == FromBB)
1002      return true;
1003
1004    // Is already exported, noop.
1005    return FuncInfo.isExportedInst(V);
1006  }
1007
1008  // If this is an argument, we can export it if the BB is the entry block or
1009  // if it is already exported.
1010  if (isa<Argument>(V)) {
1011    if (FromBB == &FromBB->getParent()->getEntryBlock())
1012      return true;
1013
1014    // Otherwise, can only export this if it is already exported.
1015    return FuncInfo.isExportedInst(V);
1016  }
1017
1018  // Otherwise, constants can always be exported.
1019  return true;
1020}
1021
1022static bool InBlock(const Value *V, const BasicBlock *BB) {
1023  if (const Instruction *I = dyn_cast<Instruction>(V))
1024    return I->getParent() == BB;
1025  return true;
1026}
1027
1028/// getFCmpCondCode - Return the ISD condition code corresponding to
1029/// the given LLVM IR floating-point condition code.  This includes
1030/// consideration of global floating-point math flags.
1031///
1032static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1033  ISD::CondCode FPC, FOC;
1034  switch (Pred) {
1035  case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1036  case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1037  case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1038  case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1039  case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1040  case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1041  case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1042  case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1043  case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1044  case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1045  case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1046  case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1047  case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1048  case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1049  case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1050  case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1051  default:
1052    llvm_unreachable("Invalid FCmp predicate opcode!");
1053    FOC = FPC = ISD::SETFALSE;
1054    break;
1055  }
1056  if (FiniteOnlyFPMath())
1057    return FOC;
1058  else
1059    return FPC;
1060}
1061
1062/// getICmpCondCode - Return the ISD condition code corresponding to
1063/// the given LLVM IR integer condition code.
1064///
1065static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1066  switch (Pred) {
1067  case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
1068  case ICmpInst::ICMP_NE:  return ISD::SETNE;
1069  case ICmpInst::ICMP_SLE: return ISD::SETLE;
1070  case ICmpInst::ICMP_ULE: return ISD::SETULE;
1071  case ICmpInst::ICMP_SGE: return ISD::SETGE;
1072  case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1073  case ICmpInst::ICMP_SLT: return ISD::SETLT;
1074  case ICmpInst::ICMP_ULT: return ISD::SETULT;
1075  case ICmpInst::ICMP_SGT: return ISD::SETGT;
1076  case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1077  default:
1078    llvm_unreachable("Invalid ICmp predicate opcode!");
1079    return ISD::SETNE;
1080  }
1081}
1082
1083/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1084/// This function emits a branch and is used at the leaves of an OR or an
1085/// AND operator tree.
1086///
1087void
1088SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1089                                                  MachineBasicBlock *TBB,
1090                                                  MachineBasicBlock *FBB,
1091                                                  MachineBasicBlock *CurBB) {
1092  const BasicBlock *BB = CurBB->getBasicBlock();
1093
1094  // If the leaf of the tree is a comparison, merge the condition into
1095  // the caseblock.
1096  if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1097    // The operands of the cmp have to be in this block.  We don't know
1098    // how to export them from some other block.  If this is the first block
1099    // of the sequence, no exporting is needed.
1100    if (CurBB == CurMBB ||
1101        (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1102         isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1103      ISD::CondCode Condition;
1104      if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1105        Condition = getICmpCondCode(IC->getPredicate());
1106      } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1107        Condition = getFCmpCondCode(FC->getPredicate());
1108      } else {
1109        Condition = ISD::SETEQ; // silence warning.
1110        llvm_unreachable("Unknown compare instruction");
1111      }
1112
1113      CaseBlock CB(Condition, BOp->getOperand(0),
1114                   BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1115      SwitchCases.push_back(CB);
1116      return;
1117    }
1118  }
1119
1120  // Create a CaseBlock record representing this branch.
1121  CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1122               NULL, TBB, FBB, CurBB);
1123  SwitchCases.push_back(CB);
1124}
1125
1126/// FindMergedConditions - If Cond is an expression like
1127void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1128                                               MachineBasicBlock *TBB,
1129                                               MachineBasicBlock *FBB,
1130                                               MachineBasicBlock *CurBB,
1131                                               unsigned Opc) {
1132  // If this node is not part of the or/and tree, emit it as a branch.
1133  Instruction *BOp = dyn_cast<Instruction>(Cond);
1134  if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1135      (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1136      BOp->getParent() != CurBB->getBasicBlock() ||
1137      !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1138      !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1139    EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1140    return;
1141  }
1142
1143  //  Create TmpBB after CurBB.
1144  MachineFunction::iterator BBI = CurBB;
1145  MachineFunction &MF = DAG.getMachineFunction();
1146  MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1147  CurBB->getParent()->insert(++BBI, TmpBB);
1148
1149  if (Opc == Instruction::Or) {
1150    // Codegen X | Y as:
1151    //   jmp_if_X TBB
1152    //   jmp TmpBB
1153    // TmpBB:
1154    //   jmp_if_Y TBB
1155    //   jmp FBB
1156    //
1157
1158    // Emit the LHS condition.
1159    FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1160
1161    // Emit the RHS condition into TmpBB.
1162    FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1163  } else {
1164    assert(Opc == Instruction::And && "Unknown merge op!");
1165    // Codegen X & Y as:
1166    //   jmp_if_X TmpBB
1167    //   jmp FBB
1168    // TmpBB:
1169    //   jmp_if_Y TBB
1170    //   jmp FBB
1171    //
1172    //  This requires creation of TmpBB after CurBB.
1173
1174    // Emit the LHS condition.
1175    FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1176
1177    // Emit the RHS condition into TmpBB.
1178    FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1179  }
1180}
1181
1182/// If the set of cases should be emitted as a series of branches, return true.
1183/// If we should emit this as a bunch of and/or'd together conditions, return
1184/// false.
1185bool
1186SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1187  if (Cases.size() != 2) return true;
1188
1189  // If this is two comparisons of the same values or'd or and'd together, they
1190  // will get folded into a single comparison, so don't emit two blocks.
1191  if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1192       Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1193      (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1194       Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1195    return false;
1196  }
1197
1198  // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1199  // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1200  if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1201      Cases[0].CC == Cases[1].CC &&
1202      isa<Constant>(Cases[0].CmpRHS) &&
1203      cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1204    if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1205      return false;
1206    if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1207      return false;
1208  }
1209
1210  return true;
1211}
1212
1213void SelectionDAGBuilder::visitBr(BranchInst &I) {
1214  // Update machine-CFG edges.
1215  MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1216
1217  // Figure out which block is immediately after the current one.
1218  MachineBasicBlock *NextBlock = 0;
1219  MachineFunction::iterator BBI = CurMBB;
1220  if (++BBI != FuncInfo.MF->end())
1221    NextBlock = BBI;
1222
1223  if (I.isUnconditional()) {
1224    // Update machine-CFG edges.
1225    CurMBB->addSuccessor(Succ0MBB);
1226
1227    // If this is not a fall-through branch, emit the branch.
1228    if (Succ0MBB != NextBlock) {
1229      SDValue V = DAG.getNode(ISD::BR, getCurDebugLoc(),
1230                              MVT::Other, getControlRoot(),
1231                              DAG.getBasicBlock(Succ0MBB));
1232      DAG.setRoot(V);
1233
1234      if (DisableScheduling)
1235        DAG.AssignOrdering(V.getNode(), SDNodeOrder);
1236    }
1237
1238    return;
1239  }
1240
1241  // If this condition is one of the special cases we handle, do special stuff
1242  // now.
1243  Value *CondVal = I.getCondition();
1244  MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1245
1246  // If this is a series of conditions that are or'd or and'd together, emit
1247  // this as a sequence of branches instead of setcc's with and/or operations.
1248  // For example, instead of something like:
1249  //     cmp A, B
1250  //     C = seteq
1251  //     cmp D, E
1252  //     F = setle
1253  //     or C, F
1254  //     jnz foo
1255  // Emit:
1256  //     cmp A, B
1257  //     je foo
1258  //     cmp D, E
1259  //     jle foo
1260  //
1261  if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1262    if (BOp->hasOneUse() &&
1263        (BOp->getOpcode() == Instruction::And ||
1264         BOp->getOpcode() == Instruction::Or)) {
1265      FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1266      // If the compares in later blocks need to use values not currently
1267      // exported from this block, export them now.  This block should always
1268      // be the first entry.
1269      assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1270
1271      // Allow some cases to be rejected.
1272      if (ShouldEmitAsBranches(SwitchCases)) {
1273        for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1274          ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1275          ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1276        }
1277
1278        // Emit the branch for this block.
1279        visitSwitchCase(SwitchCases[0]);
1280        SwitchCases.erase(SwitchCases.begin());
1281        return;
1282      }
1283
1284      // Okay, we decided not to do this, remove any inserted MBB's and clear
1285      // SwitchCases.
1286      for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1287        FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1288
1289      SwitchCases.clear();
1290    }
1291  }
1292
1293  // Create a CaseBlock record representing this branch.
1294  CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1295               NULL, Succ0MBB, Succ1MBB, CurMBB);
1296
1297  // Use visitSwitchCase to actually insert the fast branch sequence for this
1298  // cond branch.
1299  visitSwitchCase(CB);
1300}
1301
1302/// visitSwitchCase - Emits the necessary code to represent a single node in
1303/// the binary search tree resulting from lowering a switch instruction.
1304void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
1305  SDValue Cond;
1306  SDValue CondLHS = getValue(CB.CmpLHS);
1307  DebugLoc dl = getCurDebugLoc();
1308
1309  // Build the setcc now.
1310  if (CB.CmpMHS == NULL) {
1311    // Fold "(X == true)" to X and "(X == false)" to !X to
1312    // handle common cases produced by branch lowering.
1313    if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1314        CB.CC == ISD::SETEQ)
1315      Cond = CondLHS;
1316    else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1317             CB.CC == ISD::SETEQ) {
1318      SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1319      Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1320    } else
1321      Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1322  } else {
1323    assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1324
1325    const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1326    const APInt& High  = cast<ConstantInt>(CB.CmpRHS)->getValue();
1327
1328    SDValue CmpOp = getValue(CB.CmpMHS);
1329    EVT VT = CmpOp.getValueType();
1330
1331    if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1332      Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1333                          ISD::SETLE);
1334    } else {
1335      SDValue SUB = DAG.getNode(ISD::SUB, dl,
1336                                VT, CmpOp, DAG.getConstant(Low, VT));
1337      Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1338                          DAG.getConstant(High-Low, VT), ISD::SETULE);
1339    }
1340  }
1341
1342  if (DisableScheduling)
1343    DAG.AssignOrdering(Cond.getNode(), SDNodeOrder);
1344
1345  // Update successor info
1346  CurMBB->addSuccessor(CB.TrueBB);
1347  CurMBB->addSuccessor(CB.FalseBB);
1348
1349  // Set NextBlock to be the MBB immediately after the current one, if any.
1350  // This is used to avoid emitting unnecessary branches to the next block.
1351  MachineBasicBlock *NextBlock = 0;
1352  MachineFunction::iterator BBI = CurMBB;
1353  if (++BBI != FuncInfo.MF->end())
1354    NextBlock = BBI;
1355
1356  // If the lhs block is the next block, invert the condition so that we can
1357  // fall through to the lhs instead of the rhs block.
1358  if (CB.TrueBB == NextBlock) {
1359    std::swap(CB.TrueBB, CB.FalseBB);
1360    SDValue True = DAG.getConstant(1, Cond.getValueType());
1361    Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1362
1363    if (DisableScheduling)
1364      DAG.AssignOrdering(Cond.getNode(), SDNodeOrder);
1365  }
1366
1367  SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1368                               MVT::Other, getControlRoot(), Cond,
1369                               DAG.getBasicBlock(CB.TrueBB));
1370
1371  if (DisableScheduling)
1372    DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1373
1374  // If the branch was constant folded, fix up the CFG.
1375  if (BrCond.getOpcode() == ISD::BR) {
1376    CurMBB->removeSuccessor(CB.FalseBB);
1377  } else {
1378    // Otherwise, go ahead and insert the false branch.
1379    if (BrCond == getControlRoot())
1380      CurMBB->removeSuccessor(CB.TrueBB);
1381
1382    if (CB.FalseBB != NextBlock) {
1383      BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1384                           DAG.getBasicBlock(CB.FalseBB));
1385
1386      if (DisableScheduling)
1387        DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1388    }
1389  }
1390
1391  DAG.setRoot(BrCond);
1392}
1393
1394/// visitJumpTable - Emit JumpTable node in the current MBB
1395void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1396  // Emit the code for the jump table
1397  assert(JT.Reg != -1U && "Should lower JT Header first!");
1398  EVT PTy = TLI.getPointerTy();
1399  SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1400                                     JT.Reg, PTy);
1401  SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1402  SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1403                                    MVT::Other, Index.getValue(1),
1404                                    Table, Index);
1405  DAG.setRoot(BrJumpTable);
1406
1407  if (DisableScheduling) {
1408    DAG.AssignOrdering(Index.getNode(), SDNodeOrder);
1409    DAG.AssignOrdering(Table.getNode(), SDNodeOrder);
1410    DAG.AssignOrdering(BrJumpTable.getNode(), SDNodeOrder);
1411  }
1412}
1413
1414/// visitJumpTableHeader - This function emits necessary code to produce index
1415/// in the JumpTable from switch case.
1416void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1417                                               JumpTableHeader &JTH) {
1418  // Subtract the lowest switch case value from the value being switched on and
1419  // conditional branch to default mbb if the result is greater than the
1420  // difference between smallest and largest cases.
1421  SDValue SwitchOp = getValue(JTH.SValue);
1422  EVT VT = SwitchOp.getValueType();
1423  SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1424                            DAG.getConstant(JTH.First, VT));
1425
1426  // The SDNode we just created, which holds the value being switched on minus
1427  // the the smallest case value, needs to be copied to a virtual register so it
1428  // can be used as an index into the jump table in a subsequent basic block.
1429  // This value may be smaller or larger than the target's pointer type, and
1430  // therefore require extension or truncating.
1431  SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1432
1433  unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1434  SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1435                                    JumpTableReg, SwitchOp);
1436  JT.Reg = JumpTableReg;
1437
1438  // Emit the range check for the jump table, and branch to the default block
1439  // for the switch statement if the value being switched on exceeds the largest
1440  // case in the switch.
1441  SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1442                             TLI.getSetCCResultType(Sub.getValueType()), Sub,
1443                             DAG.getConstant(JTH.Last-JTH.First,VT),
1444                             ISD::SETUGT);
1445
1446  if (DisableScheduling) {
1447    DAG.AssignOrdering(Sub.getNode(), SDNodeOrder);
1448    DAG.AssignOrdering(SwitchOp.getNode(), SDNodeOrder);
1449    DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder);
1450    DAG.AssignOrdering(CMP.getNode(), SDNodeOrder);
1451  }
1452
1453  // Set NextBlock to be the MBB immediately after the current one, if any.
1454  // This is used to avoid emitting unnecessary branches to the next block.
1455  MachineBasicBlock *NextBlock = 0;
1456  MachineFunction::iterator BBI = CurMBB;
1457
1458  if (++BBI != FuncInfo.MF->end())
1459    NextBlock = BBI;
1460
1461  SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1462                               MVT::Other, CopyTo, CMP,
1463                               DAG.getBasicBlock(JT.Default));
1464
1465  if (DisableScheduling)
1466    DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1467
1468  if (JT.MBB != NextBlock) {
1469    BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1470                         DAG.getBasicBlock(JT.MBB));
1471
1472    if (DisableScheduling)
1473      DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1474  }
1475
1476  DAG.setRoot(BrCond);
1477}
1478
1479/// visitBitTestHeader - This function emits necessary code to produce value
1480/// suitable for "bit tests"
1481void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
1482  // Subtract the minimum value
1483  SDValue SwitchOp = getValue(B.SValue);
1484  EVT VT = SwitchOp.getValueType();
1485  SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1486                            DAG.getConstant(B.First, VT));
1487
1488  // Check range
1489  SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1490                                  TLI.getSetCCResultType(Sub.getValueType()),
1491                                  Sub, DAG.getConstant(B.Range, VT),
1492                                  ISD::SETUGT);
1493
1494  SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1495                                       TLI.getPointerTy());
1496
1497  B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1498  SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1499                                    B.Reg, ShiftOp);
1500
1501  if (DisableScheduling) {
1502    DAG.AssignOrdering(Sub.getNode(), SDNodeOrder);
1503    DAG.AssignOrdering(RangeCmp.getNode(), SDNodeOrder);
1504    DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder);
1505    DAG.AssignOrdering(CopyTo.getNode(), SDNodeOrder);
1506  }
1507
1508  // Set NextBlock to be the MBB immediately after the current one, if any.
1509  // This is used to avoid emitting unnecessary branches to the next block.
1510  MachineBasicBlock *NextBlock = 0;
1511  MachineFunction::iterator BBI = CurMBB;
1512  if (++BBI != FuncInfo.MF->end())
1513    NextBlock = BBI;
1514
1515  MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1516
1517  CurMBB->addSuccessor(B.Default);
1518  CurMBB->addSuccessor(MBB);
1519
1520  SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1521                                MVT::Other, CopyTo, RangeCmp,
1522                                DAG.getBasicBlock(B.Default));
1523
1524  if (DisableScheduling)
1525    DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1526
1527  if (MBB != NextBlock) {
1528    BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1529                          DAG.getBasicBlock(MBB));
1530
1531    if (DisableScheduling)
1532      DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1533  }
1534
1535  DAG.setRoot(BrRange);
1536}
1537
1538/// visitBitTestCase - this function produces one "bit test"
1539void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1540                                           unsigned Reg,
1541                                           BitTestCase &B) {
1542  // Make desired shift
1543  SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1544                                       TLI.getPointerTy());
1545  SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1546                                  TLI.getPointerTy(),
1547                                  DAG.getConstant(1, TLI.getPointerTy()),
1548                                  ShiftOp);
1549
1550  // Emit bit tests and jumps
1551  SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1552                              TLI.getPointerTy(), SwitchVal,
1553                              DAG.getConstant(B.Mask, TLI.getPointerTy()));
1554  SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1555                                TLI.getSetCCResultType(AndOp.getValueType()),
1556                                AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1557                                ISD::SETNE);
1558
1559  if (DisableScheduling) {
1560    DAG.AssignOrdering(ShiftOp.getNode(), SDNodeOrder);
1561    DAG.AssignOrdering(SwitchVal.getNode(), SDNodeOrder);
1562    DAG.AssignOrdering(AndOp.getNode(), SDNodeOrder);
1563    DAG.AssignOrdering(AndCmp.getNode(), SDNodeOrder);
1564  }
1565
1566  CurMBB->addSuccessor(B.TargetBB);
1567  CurMBB->addSuccessor(NextMBB);
1568
1569  SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1570                              MVT::Other, getControlRoot(),
1571                              AndCmp, DAG.getBasicBlock(B.TargetBB));
1572
1573  if (DisableScheduling)
1574    DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1575
1576  // Set NextBlock to be the MBB immediately after the current one, if any.
1577  // This is used to avoid emitting unnecessary branches to the next block.
1578  MachineBasicBlock *NextBlock = 0;
1579  MachineFunction::iterator BBI = CurMBB;
1580  if (++BBI != FuncInfo.MF->end())
1581    NextBlock = BBI;
1582
1583  if (NextMBB != NextBlock) {
1584    BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1585                        DAG.getBasicBlock(NextMBB));
1586
1587    if (DisableScheduling)
1588      DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1589  }
1590
1591  DAG.setRoot(BrAnd);
1592}
1593
1594void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
1595  // Retrieve successors.
1596  MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1597  MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1598
1599  const Value *Callee(I.getCalledValue());
1600  if (isa<InlineAsm>(Callee))
1601    visitInlineAsm(&I);
1602  else
1603    LowerCallTo(&I, getValue(Callee), false, LandingPad);
1604
1605  // If the value of the invoke is used outside of its defining block, make it
1606  // available as a virtual register.
1607  CopyToExportRegsIfNeeded(&I);
1608
1609  // Update successor info
1610  CurMBB->addSuccessor(Return);
1611  CurMBB->addSuccessor(LandingPad);
1612
1613  // Drop into normal successor.
1614  SDValue Branch = DAG.getNode(ISD::BR, getCurDebugLoc(),
1615                               MVT::Other, getControlRoot(),
1616                               DAG.getBasicBlock(Return));
1617  DAG.setRoot(Branch);
1618
1619  if (DisableScheduling)
1620    DAG.AssignOrdering(Branch.getNode(), SDNodeOrder);
1621}
1622
1623void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
1624}
1625
1626/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1627/// small case ranges).
1628bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1629                                                 CaseRecVector& WorkList,
1630                                                 Value* SV,
1631                                                 MachineBasicBlock* Default) {
1632  Case& BackCase  = *(CR.Range.second-1);
1633
1634  // Size is the number of Cases represented by this range.
1635  size_t Size = CR.Range.second - CR.Range.first;
1636  if (Size > 3)
1637    return false;
1638
1639  // Get the MachineFunction which holds the current MBB.  This is used when
1640  // inserting any additional MBBs necessary to represent the switch.
1641  MachineFunction *CurMF = FuncInfo.MF;
1642
1643  // Figure out which block is immediately after the current one.
1644  MachineBasicBlock *NextBlock = 0;
1645  MachineFunction::iterator BBI = CR.CaseBB;
1646
1647  if (++BBI != FuncInfo.MF->end())
1648    NextBlock = BBI;
1649
1650  // TODO: If any two of the cases has the same destination, and if one value
1651  // is the same as the other, but has one bit unset that the other has set,
1652  // use bit manipulation to do two compares at once.  For example:
1653  // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1654
1655  // Rearrange the case blocks so that the last one falls through if possible.
1656  if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1657    // The last case block won't fall through into 'NextBlock' if we emit the
1658    // branches in this order.  See if rearranging a case value would help.
1659    for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1660      if (I->BB == NextBlock) {
1661        std::swap(*I, BackCase);
1662        break;
1663      }
1664    }
1665  }
1666
1667  // Create a CaseBlock record representing a conditional branch to
1668  // the Case's target mbb if the value being switched on SV is equal
1669  // to C.
1670  MachineBasicBlock *CurBlock = CR.CaseBB;
1671  for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1672    MachineBasicBlock *FallThrough;
1673    if (I != E-1) {
1674      FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1675      CurMF->insert(BBI, FallThrough);
1676
1677      // Put SV in a virtual register to make it available from the new blocks.
1678      ExportFromCurrentBlock(SV);
1679    } else {
1680      // If the last case doesn't match, go to the default block.
1681      FallThrough = Default;
1682    }
1683
1684    Value *RHS, *LHS, *MHS;
1685    ISD::CondCode CC;
1686    if (I->High == I->Low) {
1687      // This is just small small case range :) containing exactly 1 case
1688      CC = ISD::SETEQ;
1689      LHS = SV; RHS = I->High; MHS = NULL;
1690    } else {
1691      CC = ISD::SETLE;
1692      LHS = I->Low; MHS = SV; RHS = I->High;
1693    }
1694    CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1695
1696    // If emitting the first comparison, just call visitSwitchCase to emit the
1697    // code into the current block.  Otherwise, push the CaseBlock onto the
1698    // vector to be later processed by SDISel, and insert the node's MBB
1699    // before the next MBB.
1700    if (CurBlock == CurMBB)
1701      visitSwitchCase(CB);
1702    else
1703      SwitchCases.push_back(CB);
1704
1705    CurBlock = FallThrough;
1706  }
1707
1708  return true;
1709}
1710
1711static inline bool areJTsAllowed(const TargetLowering &TLI) {
1712  return !DisableJumpTables &&
1713          (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1714           TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1715}
1716
1717static APInt ComputeRange(const APInt &First, const APInt &Last) {
1718  APInt LastExt(Last), FirstExt(First);
1719  uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1720  LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1721  return (LastExt - FirstExt + 1ULL);
1722}
1723
1724/// handleJTSwitchCase - Emit jumptable for current switch case range
1725bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1726                                             CaseRecVector& WorkList,
1727                                             Value* SV,
1728                                             MachineBasicBlock* Default) {
1729  Case& FrontCase = *CR.Range.first;
1730  Case& BackCase  = *(CR.Range.second-1);
1731
1732  const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1733  const APInt &Last  = cast<ConstantInt>(BackCase.High)->getValue();
1734
1735  APInt TSize(First.getBitWidth(), 0);
1736  for (CaseItr I = CR.Range.first, E = CR.Range.second;
1737       I!=E; ++I)
1738    TSize += I->size();
1739
1740  if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
1741    return false;
1742
1743  APInt Range = ComputeRange(First, Last);
1744  double Density = TSize.roundToDouble() / Range.roundToDouble();
1745  if (Density < 0.4)
1746    return false;
1747
1748  DEBUG(dbgs() << "Lowering jump table\n"
1749               << "First entry: " << First << ". Last entry: " << Last << '\n'
1750               << "Range: " << Range
1751               << "Size: " << TSize << ". Density: " << Density << "\n\n");
1752
1753  // Get the MachineFunction which holds the current MBB.  This is used when
1754  // inserting any additional MBBs necessary to represent the switch.
1755  MachineFunction *CurMF = FuncInfo.MF;
1756
1757  // Figure out which block is immediately after the current one.
1758  MachineFunction::iterator BBI = CR.CaseBB;
1759  ++BBI;
1760
1761  const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1762
1763  // Create a new basic block to hold the code for loading the address
1764  // of the jump table, and jumping to it.  Update successor information;
1765  // we will either branch to the default case for the switch, or the jump
1766  // table.
1767  MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1768  CurMF->insert(BBI, JumpTableBB);
1769  CR.CaseBB->addSuccessor(Default);
1770  CR.CaseBB->addSuccessor(JumpTableBB);
1771
1772  // Build a vector of destination BBs, corresponding to each target
1773  // of the jump table. If the value of the jump table slot corresponds to
1774  // a case statement, push the case's BB onto the vector, otherwise, push
1775  // the default BB.
1776  std::vector<MachineBasicBlock*> DestBBs;
1777  APInt TEI = First;
1778  for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1779    const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1780    const APInt& High = cast<ConstantInt>(I->High)->getValue();
1781
1782    if (Low.sle(TEI) && TEI.sle(High)) {
1783      DestBBs.push_back(I->BB);
1784      if (TEI==High)
1785        ++I;
1786    } else {
1787      DestBBs.push_back(Default);
1788    }
1789  }
1790
1791  // Update successor info. Add one edge to each unique successor.
1792  BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1793  for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1794         E = DestBBs.end(); I != E; ++I) {
1795    if (!SuccsHandled[(*I)->getNumber()]) {
1796      SuccsHandled[(*I)->getNumber()] = true;
1797      JumpTableBB->addSuccessor(*I);
1798    }
1799  }
1800
1801  // Create a jump table index for this jump table, or return an existing
1802  // one.
1803  unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1804
1805  // Set the jump table information so that we can codegen it as a second
1806  // MachineBasicBlock
1807  JumpTable JT(-1U, JTI, JumpTableBB, Default);
1808  JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1809  if (CR.CaseBB == CurMBB)
1810    visitJumpTableHeader(JT, JTH);
1811
1812  JTCases.push_back(JumpTableBlock(JTH, JT));
1813
1814  return true;
1815}
1816
1817/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1818/// 2 subtrees.
1819bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1820                                                  CaseRecVector& WorkList,
1821                                                  Value* SV,
1822                                                  MachineBasicBlock* Default) {
1823  // Get the MachineFunction which holds the current MBB.  This is used when
1824  // inserting any additional MBBs necessary to represent the switch.
1825  MachineFunction *CurMF = FuncInfo.MF;
1826
1827  // Figure out which block is immediately after the current one.
1828  MachineFunction::iterator BBI = CR.CaseBB;
1829  ++BBI;
1830
1831  Case& FrontCase = *CR.Range.first;
1832  Case& BackCase  = *(CR.Range.second-1);
1833  const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1834
1835  // Size is the number of Cases represented by this range.
1836  unsigned Size = CR.Range.second - CR.Range.first;
1837
1838  const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1839  const APInt &Last  = cast<ConstantInt>(BackCase.High)->getValue();
1840  double FMetric = 0;
1841  CaseItr Pivot = CR.Range.first + Size/2;
1842
1843  // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1844  // (heuristically) allow us to emit JumpTable's later.
1845  APInt TSize(First.getBitWidth(), 0);
1846  for (CaseItr I = CR.Range.first, E = CR.Range.second;
1847       I!=E; ++I)
1848    TSize += I->size();
1849
1850  APInt LSize = FrontCase.size();
1851  APInt RSize = TSize-LSize;
1852  DEBUG(dbgs() << "Selecting best pivot: \n"
1853               << "First: " << First << ", Last: " << Last <<'\n'
1854               << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1855  for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1856       J!=E; ++I, ++J) {
1857    const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1858    const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1859    APInt Range = ComputeRange(LEnd, RBegin);
1860    assert((Range - 2ULL).isNonNegative() &&
1861           "Invalid case distance");
1862    double LDensity = (double)LSize.roundToDouble() /
1863                           (LEnd - First + 1ULL).roundToDouble();
1864    double RDensity = (double)RSize.roundToDouble() /
1865                           (Last - RBegin + 1ULL).roundToDouble();
1866    double Metric = Range.logBase2()*(LDensity+RDensity);
1867    // Should always split in some non-trivial place
1868    DEBUG(dbgs() <<"=>Step\n"
1869                 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1870                 << "LDensity: " << LDensity
1871                 << ", RDensity: " << RDensity << '\n'
1872                 << "Metric: " << Metric << '\n');
1873    if (FMetric < Metric) {
1874      Pivot = J;
1875      FMetric = Metric;
1876      DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
1877    }
1878
1879    LSize += J->size();
1880    RSize -= J->size();
1881  }
1882  if (areJTsAllowed(TLI)) {
1883    // If our case is dense we *really* should handle it earlier!
1884    assert((FMetric > 0) && "Should handle dense range earlier!");
1885  } else {
1886    Pivot = CR.Range.first + Size/2;
1887  }
1888
1889  CaseRange LHSR(CR.Range.first, Pivot);
1890  CaseRange RHSR(Pivot, CR.Range.second);
1891  Constant *C = Pivot->Low;
1892  MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1893
1894  // We know that we branch to the LHS if the Value being switched on is
1895  // less than the Pivot value, C.  We use this to optimize our binary
1896  // tree a bit, by recognizing that if SV is greater than or equal to the
1897  // LHS's Case Value, and that Case Value is exactly one less than the
1898  // Pivot's Value, then we can branch directly to the LHS's Target,
1899  // rather than creating a leaf node for it.
1900  if ((LHSR.second - LHSR.first) == 1 &&
1901      LHSR.first->High == CR.GE &&
1902      cast<ConstantInt>(C)->getValue() ==
1903      (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1904    TrueBB = LHSR.first->BB;
1905  } else {
1906    TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1907    CurMF->insert(BBI, TrueBB);
1908    WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1909
1910    // Put SV in a virtual register to make it available from the new blocks.
1911    ExportFromCurrentBlock(SV);
1912  }
1913
1914  // Similar to the optimization above, if the Value being switched on is
1915  // known to be less than the Constant CR.LT, and the current Case Value
1916  // is CR.LT - 1, then we can branch directly to the target block for
1917  // the current Case Value, rather than emitting a RHS leaf node for it.
1918  if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1919      cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1920      (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1921    FalseBB = RHSR.first->BB;
1922  } else {
1923    FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1924    CurMF->insert(BBI, FalseBB);
1925    WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1926
1927    // Put SV in a virtual register to make it available from the new blocks.
1928    ExportFromCurrentBlock(SV);
1929  }
1930
1931  // Create a CaseBlock record representing a conditional branch to
1932  // the LHS node if the value being switched on SV is less than C.
1933  // Otherwise, branch to LHS.
1934  CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1935
1936  if (CR.CaseBB == CurMBB)
1937    visitSwitchCase(CB);
1938  else
1939    SwitchCases.push_back(CB);
1940
1941  return true;
1942}
1943
1944/// handleBitTestsSwitchCase - if current case range has few destination and
1945/// range span less, than machine word bitwidth, encode case range into series
1946/// of masks and emit bit tests with these masks.
1947bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1948                                                   CaseRecVector& WorkList,
1949                                                   Value* SV,
1950                                                   MachineBasicBlock* Default){
1951  EVT PTy = TLI.getPointerTy();
1952  unsigned IntPtrBits = PTy.getSizeInBits();
1953
1954  Case& FrontCase = *CR.Range.first;
1955  Case& BackCase  = *(CR.Range.second-1);
1956
1957  // Get the MachineFunction which holds the current MBB.  This is used when
1958  // inserting any additional MBBs necessary to represent the switch.
1959  MachineFunction *CurMF = FuncInfo.MF;
1960
1961  // If target does not have legal shift left, do not emit bit tests at all.
1962  if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1963    return false;
1964
1965  size_t numCmps = 0;
1966  for (CaseItr I = CR.Range.first, E = CR.Range.second;
1967       I!=E; ++I) {
1968    // Single case counts one, case range - two.
1969    numCmps += (I->Low == I->High ? 1 : 2);
1970  }
1971
1972  // Count unique destinations
1973  SmallSet<MachineBasicBlock*, 4> Dests;
1974  for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1975    Dests.insert(I->BB);
1976    if (Dests.size() > 3)
1977      // Don't bother the code below, if there are too much unique destinations
1978      return false;
1979  }
1980  DEBUG(dbgs() << "Total number of unique destinations: "
1981        << Dests.size() << '\n'
1982        << "Total number of comparisons: " << numCmps << '\n');
1983
1984  // Compute span of values.
1985  const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1986  const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1987  APInt cmpRange = maxValue - minValue;
1988
1989  DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
1990               << "Low bound: " << minValue << '\n'
1991               << "High bound: " << maxValue << '\n');
1992
1993  if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1994      (!(Dests.size() == 1 && numCmps >= 3) &&
1995       !(Dests.size() == 2 && numCmps >= 5) &&
1996       !(Dests.size() >= 3 && numCmps >= 6)))
1997    return false;
1998
1999  DEBUG(dbgs() << "Emitting bit tests\n");
2000  APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2001
2002  // Optimize the case where all the case values fit in a
2003  // word without having to subtract minValue. In this case,
2004  // we can optimize away the subtraction.
2005  if (minValue.isNonNegative() &&
2006      maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
2007    cmpRange = maxValue;
2008  } else {
2009    lowBound = minValue;
2010  }
2011
2012  CaseBitsVector CasesBits;
2013  unsigned i, count = 0;
2014
2015  for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2016    MachineBasicBlock* Dest = I->BB;
2017    for (i = 0; i < count; ++i)
2018      if (Dest == CasesBits[i].BB)
2019        break;
2020
2021    if (i == count) {
2022      assert((count < 3) && "Too much destinations to test!");
2023      CasesBits.push_back(CaseBits(0, Dest, 0));
2024      count++;
2025    }
2026
2027    const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2028    const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2029
2030    uint64_t lo = (lowValue - lowBound).getZExtValue();
2031    uint64_t hi = (highValue - lowBound).getZExtValue();
2032
2033    for (uint64_t j = lo; j <= hi; j++) {
2034      CasesBits[i].Mask |=  1ULL << j;
2035      CasesBits[i].Bits++;
2036    }
2037
2038  }
2039  std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2040
2041  BitTestInfo BTC;
2042
2043  // Figure out which block is immediately after the current one.
2044  MachineFunction::iterator BBI = CR.CaseBB;
2045  ++BBI;
2046
2047  const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2048
2049  DEBUG(dbgs() << "Cases:\n");
2050  for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2051    DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2052                 << ", Bits: " << CasesBits[i].Bits
2053                 << ", BB: " << CasesBits[i].BB << '\n');
2054
2055    MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2056    CurMF->insert(BBI, CaseBB);
2057    BTC.push_back(BitTestCase(CasesBits[i].Mask,
2058                              CaseBB,
2059                              CasesBits[i].BB));
2060
2061    // Put SV in a virtual register to make it available from the new blocks.
2062    ExportFromCurrentBlock(SV);
2063  }
2064
2065  BitTestBlock BTB(lowBound, cmpRange, SV,
2066                   -1U, (CR.CaseBB == CurMBB),
2067                   CR.CaseBB, Default, BTC);
2068
2069  if (CR.CaseBB == CurMBB)
2070    visitBitTestHeader(BTB);
2071
2072  BitTestCases.push_back(BTB);
2073
2074  return true;
2075}
2076
2077/// Clusterify - Transform simple list of Cases into list of CaseRange's
2078size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2079                                       const SwitchInst& SI) {
2080  size_t numCmps = 0;
2081
2082  // Start with "simple" cases
2083  for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2084    MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2085    Cases.push_back(Case(SI.getSuccessorValue(i),
2086                         SI.getSuccessorValue(i),
2087                         SMBB));
2088  }
2089  std::sort(Cases.begin(), Cases.end(), CaseCmp());
2090
2091  // Merge case into clusters
2092  if (Cases.size() >= 2)
2093    // Must recompute end() each iteration because it may be
2094    // invalidated by erase if we hold on to it
2095    for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2096      const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2097      const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2098      MachineBasicBlock* nextBB = J->BB;
2099      MachineBasicBlock* currentBB = I->BB;
2100
2101      // If the two neighboring cases go to the same destination, merge them
2102      // into a single case.
2103      if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2104        I->High = J->High;
2105        J = Cases.erase(J);
2106      } else {
2107        I = J++;
2108      }
2109    }
2110
2111  for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2112    if (I->Low != I->High)
2113      // A range counts double, since it requires two compares.
2114      ++numCmps;
2115  }
2116
2117  return numCmps;
2118}
2119
2120void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
2121  // Figure out which block is immediately after the current one.
2122  MachineBasicBlock *NextBlock = 0;
2123  MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2124
2125  // If there is only the default destination, branch to it if it is not the
2126  // next basic block.  Otherwise, just fall through.
2127  if (SI.getNumOperands() == 2) {
2128    // Update machine-CFG edges.
2129
2130    // If this is not a fall-through branch, emit the branch.
2131    CurMBB->addSuccessor(Default);
2132    if (Default != NextBlock) {
2133      SDValue Res = DAG.getNode(ISD::BR, getCurDebugLoc(),
2134                                MVT::Other, getControlRoot(),
2135                                DAG.getBasicBlock(Default));
2136      DAG.setRoot(Res);
2137
2138      if (DisableScheduling)
2139        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2140    }
2141
2142    return;
2143  }
2144
2145  // If there are any non-default case statements, create a vector of Cases
2146  // representing each one, and sort the vector so that we can efficiently
2147  // create a binary search tree from them.
2148  CaseVector Cases;
2149  size_t numCmps = Clusterify(Cases, SI);
2150  DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2151               << ". Total compares: " << numCmps << '\n');
2152  numCmps = 0;
2153
2154  // Get the Value to be switched on and default basic blocks, which will be
2155  // inserted into CaseBlock records, representing basic blocks in the binary
2156  // search tree.
2157  Value *SV = SI.getOperand(0);
2158
2159  // Push the initial CaseRec onto the worklist
2160  CaseRecVector WorkList;
2161  WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2162
2163  while (!WorkList.empty()) {
2164    // Grab a record representing a case range to process off the worklist
2165    CaseRec CR = WorkList.back();
2166    WorkList.pop_back();
2167
2168    if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2169      continue;
2170
2171    // If the range has few cases (two or less) emit a series of specific
2172    // tests.
2173    if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2174      continue;
2175
2176    // If the switch has more than 5 blocks, and at least 40% dense, and the
2177    // target supports indirect branches, then emit a jump table rather than
2178    // lowering the switch to a binary tree of conditional branches.
2179    if (handleJTSwitchCase(CR, WorkList, SV, Default))
2180      continue;
2181
2182    // Emit binary tree. We need to pick a pivot, and push left and right ranges
2183    // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2184    handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2185  }
2186}
2187
2188void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
2189  // Update machine-CFG edges.
2190  for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2191    CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2192
2193  SDValue Res = DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2194                            MVT::Other, getControlRoot(),
2195                            getValue(I.getAddress()));
2196  DAG.setRoot(Res);
2197
2198  if (DisableScheduling)
2199    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2200}
2201
2202void SelectionDAGBuilder::visitFSub(User &I) {
2203  // -0.0 - X --> fneg
2204  const Type *Ty = I.getType();
2205  if (isa<VectorType>(Ty)) {
2206    if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2207      const VectorType *DestTy = cast<VectorType>(I.getType());
2208      const Type *ElTy = DestTy->getElementType();
2209      unsigned VL = DestTy->getNumElements();
2210      std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2211      Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2212      if (CV == CNZ) {
2213        SDValue Op2 = getValue(I.getOperand(1));
2214        SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2215                                  Op2.getValueType(), Op2);
2216        setValue(&I, Res);
2217
2218        if (DisableScheduling)
2219          DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2220
2221        return;
2222      }
2223    }
2224  }
2225
2226  if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2227    if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2228      SDValue Op2 = getValue(I.getOperand(1));
2229      SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2230                                Op2.getValueType(), Op2);
2231      setValue(&I, Res);
2232
2233      if (DisableScheduling)
2234        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2235
2236      return;
2237    }
2238
2239  visitBinary(I, ISD::FSUB);
2240}
2241
2242void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
2243  SDValue Op1 = getValue(I.getOperand(0));
2244  SDValue Op2 = getValue(I.getOperand(1));
2245  SDValue Res = DAG.getNode(OpCode, getCurDebugLoc(),
2246                            Op1.getValueType(), Op1, Op2);
2247  setValue(&I, Res);
2248
2249  if (DisableScheduling)
2250    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2251}
2252
2253void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
2254  SDValue Op1 = getValue(I.getOperand(0));
2255  SDValue Op2 = getValue(I.getOperand(1));
2256  if (!isa<VectorType>(I.getType()) &&
2257      Op2.getValueType() != TLI.getShiftAmountTy()) {
2258    // If the operand is smaller than the shift count type, promote it.
2259    EVT PTy = TLI.getPointerTy();
2260    EVT STy = TLI.getShiftAmountTy();
2261    if (STy.bitsGT(Op2.getValueType()))
2262      Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2263                        TLI.getShiftAmountTy(), Op2);
2264    // If the operand is larger than the shift count type but the shift
2265    // count type has enough bits to represent any shift value, truncate
2266    // it now. This is a common case and it exposes the truncate to
2267    // optimization early.
2268    else if (STy.getSizeInBits() >=
2269             Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2270      Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2271                        TLI.getShiftAmountTy(), Op2);
2272    // Otherwise we'll need to temporarily settle for some other
2273    // convenient type; type legalization will make adjustments as
2274    // needed.
2275    else if (PTy.bitsLT(Op2.getValueType()))
2276      Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2277                        TLI.getPointerTy(), Op2);
2278    else if (PTy.bitsGT(Op2.getValueType()))
2279      Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2280                        TLI.getPointerTy(), Op2);
2281  }
2282
2283  SDValue Res = DAG.getNode(Opcode, getCurDebugLoc(),
2284                            Op1.getValueType(), Op1, Op2);
2285  setValue(&I, Res);
2286
2287  if (DisableScheduling) {
2288    DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
2289    DAG.AssignOrdering(Op2.getNode(), SDNodeOrder);
2290    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2291  }
2292}
2293
2294void SelectionDAGBuilder::visitICmp(User &I) {
2295  ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2296  if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2297    predicate = IC->getPredicate();
2298  else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2299    predicate = ICmpInst::Predicate(IC->getPredicate());
2300  SDValue Op1 = getValue(I.getOperand(0));
2301  SDValue Op2 = getValue(I.getOperand(1));
2302  ISD::CondCode Opcode = getICmpCondCode(predicate);
2303
2304  EVT DestVT = TLI.getValueType(I.getType());
2305  SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode);
2306  setValue(&I, Res);
2307
2308  if (DisableScheduling)
2309    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2310}
2311
2312void SelectionDAGBuilder::visitFCmp(User &I) {
2313  FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2314  if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2315    predicate = FC->getPredicate();
2316  else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2317    predicate = FCmpInst::Predicate(FC->getPredicate());
2318  SDValue Op1 = getValue(I.getOperand(0));
2319  SDValue Op2 = getValue(I.getOperand(1));
2320  ISD::CondCode Condition = getFCmpCondCode(predicate);
2321  EVT DestVT = TLI.getValueType(I.getType());
2322  SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition);
2323  setValue(&I, Res);
2324
2325  if (DisableScheduling)
2326    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2327}
2328
2329void SelectionDAGBuilder::visitSelect(User &I) {
2330  SmallVector<EVT, 4> ValueVTs;
2331  ComputeValueVTs(TLI, I.getType(), ValueVTs);
2332  unsigned NumValues = ValueVTs.size();
2333  if (NumValues == 0) return;
2334
2335  SmallVector<SDValue, 4> Values(NumValues);
2336  SDValue Cond     = getValue(I.getOperand(0));
2337  SDValue TrueVal  = getValue(I.getOperand(1));
2338  SDValue FalseVal = getValue(I.getOperand(2));
2339
2340  for (unsigned i = 0; i != NumValues; ++i) {
2341    Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2342                            TrueVal.getNode()->getValueType(i), Cond,
2343                            SDValue(TrueVal.getNode(),
2344                                    TrueVal.getResNo() + i),
2345                            SDValue(FalseVal.getNode(),
2346                                    FalseVal.getResNo() + i));
2347
2348    if (DisableScheduling)
2349      DAG.AssignOrdering(Values[i].getNode(), SDNodeOrder);
2350  }
2351
2352  SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2353                            DAG.getVTList(&ValueVTs[0], NumValues),
2354                            &Values[0], NumValues);
2355  setValue(&I, Res);
2356
2357  if (DisableScheduling)
2358    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2359}
2360
2361void SelectionDAGBuilder::visitTrunc(User &I) {
2362  // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2363  SDValue N = getValue(I.getOperand(0));
2364  EVT DestVT = TLI.getValueType(I.getType());
2365  SDValue Res = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2366  setValue(&I, Res);
2367
2368  if (DisableScheduling)
2369    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2370}
2371
2372void SelectionDAGBuilder::visitZExt(User &I) {
2373  // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2374  // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2375  SDValue N = getValue(I.getOperand(0));
2376  EVT DestVT = TLI.getValueType(I.getType());
2377  SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2378  setValue(&I, Res);
2379
2380  if (DisableScheduling)
2381    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2382}
2383
2384void SelectionDAGBuilder::visitSExt(User &I) {
2385  // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2386  // SExt also can't be a cast to bool for same reason. So, nothing much to do
2387  SDValue N = getValue(I.getOperand(0));
2388  EVT DestVT = TLI.getValueType(I.getType());
2389  SDValue Res = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N);
2390  setValue(&I, Res);
2391
2392  if (DisableScheduling)
2393    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2394}
2395
2396void SelectionDAGBuilder::visitFPTrunc(User &I) {
2397  // FPTrunc is never a no-op cast, no need to check
2398  SDValue N = getValue(I.getOperand(0));
2399  EVT DestVT = TLI.getValueType(I.getType());
2400  SDValue Res = DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2401                            DestVT, N, DAG.getIntPtrConstant(0));
2402  setValue(&I, Res);
2403
2404  if (DisableScheduling)
2405    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2406}
2407
2408void SelectionDAGBuilder::visitFPExt(User &I){
2409  // FPTrunc is never a no-op cast, no need to check
2410  SDValue N = getValue(I.getOperand(0));
2411  EVT DestVT = TLI.getValueType(I.getType());
2412  SDValue Res = DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N);
2413  setValue(&I, Res);
2414
2415  if (DisableScheduling)
2416    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2417}
2418
2419void SelectionDAGBuilder::visitFPToUI(User &I) {
2420  // FPToUI is never a no-op cast, no need to check
2421  SDValue N = getValue(I.getOperand(0));
2422  EVT DestVT = TLI.getValueType(I.getType());
2423  SDValue Res = DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N);
2424  setValue(&I, Res);
2425
2426  if (DisableScheduling)
2427    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2428}
2429
2430void SelectionDAGBuilder::visitFPToSI(User &I) {
2431  // FPToSI is never a no-op cast, no need to check
2432  SDValue N = getValue(I.getOperand(0));
2433  EVT DestVT = TLI.getValueType(I.getType());
2434  SDValue Res = DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N);
2435  setValue(&I, Res);
2436
2437  if (DisableScheduling)
2438    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2439}
2440
2441void SelectionDAGBuilder::visitUIToFP(User &I) {
2442  // UIToFP is never a no-op cast, no need to check
2443  SDValue N = getValue(I.getOperand(0));
2444  EVT DestVT = TLI.getValueType(I.getType());
2445  SDValue Res = DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N);
2446  setValue(&I, Res);
2447
2448  if (DisableScheduling)
2449    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2450}
2451
2452void SelectionDAGBuilder::visitSIToFP(User &I){
2453  // SIToFP is never a no-op cast, no need to check
2454  SDValue N = getValue(I.getOperand(0));
2455  EVT DestVT = TLI.getValueType(I.getType());
2456  SDValue Res = DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N);
2457  setValue(&I, Res);
2458
2459  if (DisableScheduling)
2460    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2461}
2462
2463void SelectionDAGBuilder::visitPtrToInt(User &I) {
2464  // What to do depends on the size of the integer and the size of the pointer.
2465  // We can either truncate, zero extend, or no-op, accordingly.
2466  SDValue N = getValue(I.getOperand(0));
2467  EVT SrcVT = N.getValueType();
2468  EVT DestVT = TLI.getValueType(I.getType());
2469  SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2470  setValue(&I, Res);
2471
2472  if (DisableScheduling)
2473    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2474}
2475
2476void SelectionDAGBuilder::visitIntToPtr(User &I) {
2477  // What to do depends on the size of the integer and the size of the pointer.
2478  // We can either truncate, zero extend, or no-op, accordingly.
2479  SDValue N = getValue(I.getOperand(0));
2480  EVT SrcVT = N.getValueType();
2481  EVT DestVT = TLI.getValueType(I.getType());
2482  SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2483  setValue(&I, Res);
2484
2485  if (DisableScheduling)
2486    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2487}
2488
2489void SelectionDAGBuilder::visitBitCast(User &I) {
2490  SDValue N = getValue(I.getOperand(0));
2491  EVT DestVT = TLI.getValueType(I.getType());
2492
2493  // BitCast assures us that source and destination are the same size so this is
2494  // either a BIT_CONVERT or a no-op.
2495  if (DestVT != N.getValueType()) {
2496    SDValue Res = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2497                              DestVT, N); // convert types.
2498    setValue(&I, Res);
2499
2500    if (DisableScheduling)
2501      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2502  } else {
2503    setValue(&I, N);            // noop cast.
2504  }
2505}
2506
2507void SelectionDAGBuilder::visitInsertElement(User &I) {
2508  SDValue InVec = getValue(I.getOperand(0));
2509  SDValue InVal = getValue(I.getOperand(1));
2510  SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2511                              TLI.getPointerTy(),
2512                              getValue(I.getOperand(2)));
2513  SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2514                            TLI.getValueType(I.getType()),
2515                            InVec, InVal, InIdx);
2516  setValue(&I, Res);
2517
2518  if (DisableScheduling) {
2519    DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder);
2520    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2521  }
2522}
2523
2524void SelectionDAGBuilder::visitExtractElement(User &I) {
2525  SDValue InVec = getValue(I.getOperand(0));
2526  SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2527                              TLI.getPointerTy(),
2528                              getValue(I.getOperand(1)));
2529  SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2530                            TLI.getValueType(I.getType()), InVec, InIdx);
2531  setValue(&I, Res);
2532
2533  if (DisableScheduling) {
2534    DAG.AssignOrdering(InIdx.getNode(), SDNodeOrder);
2535    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2536  }
2537}
2538
2539
2540// Utility for visitShuffleVector - Returns true if the mask is mask starting
2541// from SIndx and increasing to the element length (undefs are allowed).
2542static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2543  unsigned MaskNumElts = Mask.size();
2544  for (unsigned i = 0; i != MaskNumElts; ++i)
2545    if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2546      return false;
2547  return true;
2548}
2549
2550void SelectionDAGBuilder::visitShuffleVector(User &I) {
2551  SmallVector<int, 8> Mask;
2552  SDValue Src1 = getValue(I.getOperand(0));
2553  SDValue Src2 = getValue(I.getOperand(1));
2554
2555  // Convert the ConstantVector mask operand into an array of ints, with -1
2556  // representing undef values.
2557  SmallVector<Constant*, 8> MaskElts;
2558  cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2559                                                     MaskElts);
2560  unsigned MaskNumElts = MaskElts.size();
2561  for (unsigned i = 0; i != MaskNumElts; ++i) {
2562    if (isa<UndefValue>(MaskElts[i]))
2563      Mask.push_back(-1);
2564    else
2565      Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2566  }
2567
2568  EVT VT = TLI.getValueType(I.getType());
2569  EVT SrcVT = Src1.getValueType();
2570  unsigned SrcNumElts = SrcVT.getVectorNumElements();
2571
2572  if (SrcNumElts == MaskNumElts) {
2573    SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2574                                       &Mask[0]);
2575    setValue(&I, Res);
2576
2577    if (DisableScheduling)
2578      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2579
2580    return;
2581  }
2582
2583  // Normalize the shuffle vector since mask and vector length don't match.
2584  if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2585    // Mask is longer than the source vectors and is a multiple of the source
2586    // vectors.  We can use concatenate vector to make the mask and vectors
2587    // lengths match.
2588    if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2589      // The shuffle is concatenating two vectors together.
2590      SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2591                                VT, Src1, Src2);
2592      setValue(&I, Res);
2593
2594      if (DisableScheduling)
2595        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2596
2597      return;
2598    }
2599
2600    // Pad both vectors with undefs to make them the same length as the mask.
2601    unsigned NumConcat = MaskNumElts / SrcNumElts;
2602    bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2603    bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2604    SDValue UndefVal = DAG.getUNDEF(SrcVT);
2605
2606    SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2607    SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2608    MOps1[0] = Src1;
2609    MOps2[0] = Src2;
2610
2611    Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2612                                                  getCurDebugLoc(), VT,
2613                                                  &MOps1[0], NumConcat);
2614    Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2615                                                  getCurDebugLoc(), VT,
2616                                                  &MOps2[0], NumConcat);
2617
2618    // Readjust mask for new input vector length.
2619    SmallVector<int, 8> MappedOps;
2620    for (unsigned i = 0; i != MaskNumElts; ++i) {
2621      int Idx = Mask[i];
2622      if (Idx < (int)SrcNumElts)
2623        MappedOps.push_back(Idx);
2624      else
2625        MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2626    }
2627
2628    SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2629                                       &MappedOps[0]);
2630    setValue(&I, Res);
2631
2632    if (DisableScheduling) {
2633      DAG.AssignOrdering(Src1.getNode(), SDNodeOrder);
2634      DAG.AssignOrdering(Src2.getNode(), SDNodeOrder);
2635      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2636    }
2637
2638    return;
2639  }
2640
2641  if (SrcNumElts > MaskNumElts) {
2642    // Analyze the access pattern of the vector to see if we can extract
2643    // two subvectors and do the shuffle. The analysis is done by calculating
2644    // the range of elements the mask access on both vectors.
2645    int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2646    int MaxRange[2] = {-1, -1};
2647
2648    for (unsigned i = 0; i != MaskNumElts; ++i) {
2649      int Idx = Mask[i];
2650      int Input = 0;
2651      if (Idx < 0)
2652        continue;
2653
2654      if (Idx >= (int)SrcNumElts) {
2655        Input = 1;
2656        Idx -= SrcNumElts;
2657      }
2658      if (Idx > MaxRange[Input])
2659        MaxRange[Input] = Idx;
2660      if (Idx < MinRange[Input])
2661        MinRange[Input] = Idx;
2662    }
2663
2664    // Check if the access is smaller than the vector size and can we find
2665    // a reasonable extract index.
2666    int RangeUse[2] = { 2, 2 };  // 0 = Unused, 1 = Extract, 2 = Can not
2667                                 // Extract.
2668    int StartIdx[2];  // StartIdx to extract from
2669    for (int Input=0; Input < 2; ++Input) {
2670      if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2671        RangeUse[Input] = 0; // Unused
2672        StartIdx[Input] = 0;
2673      } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2674        // Fits within range but we should see if we can find a good
2675        // start index that is a multiple of the mask length.
2676        if (MaxRange[Input] < (int)MaskNumElts) {
2677          RangeUse[Input] = 1; // Extract from beginning of the vector
2678          StartIdx[Input] = 0;
2679        } else {
2680          StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2681          if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2682              StartIdx[Input] + MaskNumElts < SrcNumElts)
2683            RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2684        }
2685      }
2686    }
2687
2688    if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2689      SDValue Res = DAG.getUNDEF(VT);
2690      setValue(&I, Res);  // Vectors are not used.
2691
2692      if (DisableScheduling)
2693        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2694
2695      return;
2696    }
2697    else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2698      // Extract appropriate subvector and generate a vector shuffle
2699      for (int Input=0; Input < 2; ++Input) {
2700        SDValue &Src = Input == 0 ? Src1 : Src2;
2701        if (RangeUse[Input] == 0)
2702          Src = DAG.getUNDEF(VT);
2703        else
2704          Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2705                            Src, DAG.getIntPtrConstant(StartIdx[Input]));
2706
2707        if (DisableScheduling)
2708          DAG.AssignOrdering(Src.getNode(), SDNodeOrder);
2709      }
2710
2711      // Calculate new mask.
2712      SmallVector<int, 8> MappedOps;
2713      for (unsigned i = 0; i != MaskNumElts; ++i) {
2714        int Idx = Mask[i];
2715        if (Idx < 0)
2716          MappedOps.push_back(Idx);
2717        else if (Idx < (int)SrcNumElts)
2718          MappedOps.push_back(Idx - StartIdx[0]);
2719        else
2720          MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2721      }
2722
2723      SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2724                                         &MappedOps[0]);
2725      setValue(&I, Res);
2726
2727      if (DisableScheduling)
2728        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2729
2730      return;
2731    }
2732  }
2733
2734  // We can't use either concat vectors or extract subvectors so fall back to
2735  // replacing the shuffle with extract and build vector.
2736  // to insert and build vector.
2737  EVT EltVT = VT.getVectorElementType();
2738  EVT PtrVT = TLI.getPointerTy();
2739  SmallVector<SDValue,8> Ops;
2740  for (unsigned i = 0; i != MaskNumElts; ++i) {
2741    if (Mask[i] < 0) {
2742      Ops.push_back(DAG.getUNDEF(EltVT));
2743    } else {
2744      int Idx = Mask[i];
2745      SDValue Res;
2746
2747      if (Idx < (int)SrcNumElts)
2748        Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2749                          EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2750      else
2751        Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2752                          EltVT, Src2,
2753                          DAG.getConstant(Idx - SrcNumElts, PtrVT));
2754
2755      Ops.push_back(Res);
2756
2757      if (DisableScheduling)
2758        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2759    }
2760  }
2761
2762  SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2763                            VT, &Ops[0], Ops.size());
2764  setValue(&I, Res);
2765
2766  if (DisableScheduling)
2767    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2768}
2769
2770void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
2771  const Value *Op0 = I.getOperand(0);
2772  const Value *Op1 = I.getOperand(1);
2773  const Type *AggTy = I.getType();
2774  const Type *ValTy = Op1->getType();
2775  bool IntoUndef = isa<UndefValue>(Op0);
2776  bool FromUndef = isa<UndefValue>(Op1);
2777
2778  unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2779                                            I.idx_begin(), I.idx_end());
2780
2781  SmallVector<EVT, 4> AggValueVTs;
2782  ComputeValueVTs(TLI, AggTy, AggValueVTs);
2783  SmallVector<EVT, 4> ValValueVTs;
2784  ComputeValueVTs(TLI, ValTy, ValValueVTs);
2785
2786  unsigned NumAggValues = AggValueVTs.size();
2787  unsigned NumValValues = ValValueVTs.size();
2788  SmallVector<SDValue, 4> Values(NumAggValues);
2789
2790  SDValue Agg = getValue(Op0);
2791  SDValue Val = getValue(Op1);
2792  unsigned i = 0;
2793  // Copy the beginning value(s) from the original aggregate.
2794  for (; i != LinearIndex; ++i)
2795    Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2796                SDValue(Agg.getNode(), Agg.getResNo() + i);
2797  // Copy values from the inserted value(s).
2798  for (; i != LinearIndex + NumValValues; ++i)
2799    Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2800                SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2801  // Copy remaining value(s) from the original aggregate.
2802  for (; i != NumAggValues; ++i)
2803    Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2804                SDValue(Agg.getNode(), Agg.getResNo() + i);
2805
2806  SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2807                            DAG.getVTList(&AggValueVTs[0], NumAggValues),
2808                            &Values[0], NumAggValues);
2809  setValue(&I, Res);
2810
2811  if (DisableScheduling)
2812    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2813}
2814
2815void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
2816  const Value *Op0 = I.getOperand(0);
2817  const Type *AggTy = Op0->getType();
2818  const Type *ValTy = I.getType();
2819  bool OutOfUndef = isa<UndefValue>(Op0);
2820
2821  unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2822                                            I.idx_begin(), I.idx_end());
2823
2824  SmallVector<EVT, 4> ValValueVTs;
2825  ComputeValueVTs(TLI, ValTy, ValValueVTs);
2826
2827  unsigned NumValValues = ValValueVTs.size();
2828  SmallVector<SDValue, 4> Values(NumValValues);
2829
2830  SDValue Agg = getValue(Op0);
2831  // Copy out the selected value(s).
2832  for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2833    Values[i - LinearIndex] =
2834      OutOfUndef ?
2835        DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2836        SDValue(Agg.getNode(), Agg.getResNo() + i);
2837
2838  SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2839                            DAG.getVTList(&ValValueVTs[0], NumValValues),
2840                            &Values[0], NumValValues);
2841  setValue(&I, Res);
2842
2843  if (DisableScheduling)
2844    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2845}
2846
2847void SelectionDAGBuilder::visitGetElementPtr(User &I) {
2848  SDValue N = getValue(I.getOperand(0));
2849  const Type *Ty = I.getOperand(0)->getType();
2850
2851  for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2852       OI != E; ++OI) {
2853    Value *Idx = *OI;
2854    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2855      unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2856      if (Field) {
2857        // N = N + Offset
2858        uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2859        N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2860                        DAG.getIntPtrConstant(Offset));
2861
2862        if (DisableScheduling)
2863          DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2864      }
2865
2866      Ty = StTy->getElementType(Field);
2867    } else {
2868      Ty = cast<SequentialType>(Ty)->getElementType();
2869
2870      // If this is a constant subscript, handle it quickly.
2871      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2872        if (CI->getZExtValue() == 0) continue;
2873        uint64_t Offs =
2874            TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2875        SDValue OffsVal;
2876        EVT PTy = TLI.getPointerTy();
2877        unsigned PtrBits = PTy.getSizeInBits();
2878        if (PtrBits < 64)
2879          OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2880                                TLI.getPointerTy(),
2881                                DAG.getConstant(Offs, MVT::i64));
2882        else
2883          OffsVal = DAG.getIntPtrConstant(Offs);
2884
2885        N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2886                        OffsVal);
2887
2888        if (DisableScheduling) {
2889          DAG.AssignOrdering(OffsVal.getNode(), SDNodeOrder);
2890          DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2891        }
2892
2893        continue;
2894      }
2895
2896      // N = N + Idx * ElementSize;
2897      APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2898                                TD->getTypeAllocSize(Ty));
2899      SDValue IdxN = getValue(Idx);
2900
2901      // If the index is smaller or larger than intptr_t, truncate or extend
2902      // it.
2903      IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2904
2905      // If this is a multiply by a power of two, turn it into a shl
2906      // immediately.  This is a very common case.
2907      if (ElementSize != 1) {
2908        if (ElementSize.isPowerOf2()) {
2909          unsigned Amt = ElementSize.logBase2();
2910          IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2911                             N.getValueType(), IdxN,
2912                             DAG.getConstant(Amt, TLI.getPointerTy()));
2913        } else {
2914          SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2915          IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2916                             N.getValueType(), IdxN, Scale);
2917        }
2918
2919        if (DisableScheduling)
2920          DAG.AssignOrdering(IdxN.getNode(), SDNodeOrder);
2921      }
2922
2923      N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2924                      N.getValueType(), N, IdxN);
2925
2926      if (DisableScheduling)
2927        DAG.AssignOrdering(N.getNode(), SDNodeOrder);
2928    }
2929  }
2930
2931  setValue(&I, N);
2932}
2933
2934void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
2935  // If this is a fixed sized alloca in the entry block of the function,
2936  // allocate it statically on the stack.
2937  if (FuncInfo.StaticAllocaMap.count(&I))
2938    return;   // getValue will auto-populate this.
2939
2940  const Type *Ty = I.getAllocatedType();
2941  uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2942  unsigned Align =
2943    std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2944             I.getAlignment());
2945
2946  SDValue AllocSize = getValue(I.getArraySize());
2947
2948  AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2949                          AllocSize,
2950                          DAG.getConstant(TySize, AllocSize.getValueType()));
2951
2952  if (DisableScheduling)
2953    DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2954
2955  EVT IntPtr = TLI.getPointerTy();
2956  AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2957
2958  if (DisableScheduling)
2959    DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2960
2961  // Handle alignment.  If the requested alignment is less than or equal to
2962  // the stack alignment, ignore it.  If the size is greater than or equal to
2963  // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2964  unsigned StackAlign =
2965    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2966  if (Align <= StackAlign)
2967    Align = 0;
2968
2969  // Round the size of the allocation up to the stack alignment size
2970  // by add SA-1 to the size.
2971  AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2972                          AllocSize.getValueType(), AllocSize,
2973                          DAG.getIntPtrConstant(StackAlign-1));
2974  if (DisableScheduling)
2975    DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2976
2977  // Mask out the low bits for alignment purposes.
2978  AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2979                          AllocSize.getValueType(), AllocSize,
2980                          DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2981  if (DisableScheduling)
2982    DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder);
2983
2984  SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2985  SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2986  SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2987                            VTs, Ops, 3);
2988  setValue(&I, DSA);
2989  DAG.setRoot(DSA.getValue(1));
2990
2991  if (DisableScheduling)
2992    DAG.AssignOrdering(DSA.getNode(), SDNodeOrder);
2993
2994  // Inform the Frame Information that we have just allocated a variable-sized
2995  // object.
2996  FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2997}
2998
2999void SelectionDAGBuilder::visitLoad(LoadInst &I) {
3000  const Value *SV = I.getOperand(0);
3001  SDValue Ptr = getValue(SV);
3002
3003  const Type *Ty = I.getType();
3004  bool isVolatile = I.isVolatile();
3005  unsigned Alignment = I.getAlignment();
3006
3007  SmallVector<EVT, 4> ValueVTs;
3008  SmallVector<uint64_t, 4> Offsets;
3009  ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3010  unsigned NumValues = ValueVTs.size();
3011  if (NumValues == 0)
3012    return;
3013
3014  SDValue Root;
3015  bool ConstantMemory = false;
3016  if (I.isVolatile())
3017    // Serialize volatile loads with other side effects.
3018    Root = getRoot();
3019  else if (AA->pointsToConstantMemory(SV)) {
3020    // Do not serialize (non-volatile) loads of constant memory with anything.
3021    Root = DAG.getEntryNode();
3022    ConstantMemory = true;
3023  } else {
3024    // Do not serialize non-volatile loads against each other.
3025    Root = DAG.getRoot();
3026  }
3027
3028  SmallVector<SDValue, 4> Values(NumValues);
3029  SmallVector<SDValue, 4> Chains(NumValues);
3030  EVT PtrVT = Ptr.getValueType();
3031  for (unsigned i = 0; i != NumValues; ++i) {
3032    SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3033                            PtrVT, Ptr,
3034                            DAG.getConstant(Offsets[i], PtrVT));
3035    SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
3036                            A, SV, Offsets[i], isVolatile, Alignment);
3037
3038    Values[i] = L;
3039    Chains[i] = L.getValue(1);
3040
3041    if (DisableScheduling) {
3042      DAG.AssignOrdering(A.getNode(), SDNodeOrder);
3043      DAG.AssignOrdering(L.getNode(), SDNodeOrder);
3044    }
3045  }
3046
3047  if (!ConstantMemory) {
3048    SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3049                                MVT::Other, &Chains[0], NumValues);
3050    if (isVolatile)
3051      DAG.setRoot(Chain);
3052    else
3053      PendingLoads.push_back(Chain);
3054
3055    if (DisableScheduling)
3056      DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
3057  }
3058
3059  SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3060                            DAG.getVTList(&ValueVTs[0], NumValues),
3061                            &Values[0], NumValues);
3062  setValue(&I, Res);
3063
3064  if (DisableScheduling)
3065    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
3066}
3067
3068void SelectionDAGBuilder::visitStore(StoreInst &I) {
3069  Value *SrcV = I.getOperand(0);
3070  Value *PtrV = I.getOperand(1);
3071
3072  SmallVector<EVT, 4> ValueVTs;
3073  SmallVector<uint64_t, 4> Offsets;
3074  ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3075  unsigned NumValues = ValueVTs.size();
3076  if (NumValues == 0)
3077    return;
3078
3079  // Get the lowered operands. Note that we do this after
3080  // checking if NumResults is zero, because with zero results
3081  // the operands won't have values in the map.
3082  SDValue Src = getValue(SrcV);
3083  SDValue Ptr = getValue(PtrV);
3084
3085  SDValue Root = getRoot();
3086  SmallVector<SDValue, 4> Chains(NumValues);
3087  EVT PtrVT = Ptr.getValueType();
3088  bool isVolatile = I.isVolatile();
3089  unsigned Alignment = I.getAlignment();
3090
3091  for (unsigned i = 0; i != NumValues; ++i) {
3092    SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3093                              DAG.getConstant(Offsets[i], PtrVT));
3094    Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
3095                             SDValue(Src.getNode(), Src.getResNo() + i),
3096                             Add, PtrV, Offsets[i], isVolatile, Alignment);
3097
3098    if (DisableScheduling) {
3099      DAG.AssignOrdering(Add.getNode(), SDNodeOrder);
3100      DAG.AssignOrdering(Chains[i].getNode(), SDNodeOrder);
3101    }
3102  }
3103
3104  SDValue Res = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3105                            MVT::Other, &Chains[0], NumValues);
3106  DAG.setRoot(Res);
3107
3108  if (DisableScheduling)
3109    DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
3110}
3111
3112/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3113/// node.
3114void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
3115                                               unsigned Intrinsic) {
3116  bool HasChain = !I.doesNotAccessMemory();
3117  bool OnlyLoad = HasChain && I.onlyReadsMemory();
3118
3119  // Build the operand list.
3120  SmallVector<SDValue, 8> Ops;
3121  if (HasChain) {  // If this intrinsic has side-effects, chainify it.
3122    if (OnlyLoad) {
3123      // We don't need to serialize loads against other loads.
3124      Ops.push_back(DAG.getRoot());
3125    } else {
3126      Ops.push_back(getRoot());
3127    }
3128  }
3129
3130  // Info is set by getTgtMemInstrinsic
3131  TargetLowering::IntrinsicInfo Info;
3132  bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3133
3134  // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3135  if (!IsTgtIntrinsic)
3136    Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3137
3138  // Add all operands of the call to the operand list.
3139  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3140    SDValue Op = getValue(I.getOperand(i));
3141    assert(TLI.isTypeLegal(Op.getValueType()) &&
3142           "Intrinsic uses a non-legal type?");
3143    Ops.push_back(Op);
3144  }
3145
3146  SmallVector<EVT, 4> ValueVTs;
3147  ComputeValueVTs(TLI, I.getType(), ValueVTs);
3148#ifndef NDEBUG
3149  for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3150    assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3151           "Intrinsic uses a non-legal type?");
3152  }
3153#endif // NDEBUG
3154
3155  if (HasChain)
3156    ValueVTs.push_back(MVT::Other);
3157
3158  SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3159
3160  // Create the node.
3161  SDValue Result;
3162  if (IsTgtIntrinsic) {
3163    // This is target intrinsic that touches memory
3164    Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3165                                     VTs, &Ops[0], Ops.size(),
3166                                     Info.memVT, Info.ptrVal, Info.offset,
3167                                     Info.align, Info.vol,
3168                                     Info.readMem, Info.writeMem);
3169  } else if (!HasChain) {
3170    Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3171                         VTs, &Ops[0], Ops.size());
3172  } else if (!I.getType()->isVoidTy()) {
3173    Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3174                         VTs, &Ops[0], Ops.size());
3175  } else {
3176    Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3177                         VTs, &Ops[0], Ops.size());
3178  }
3179
3180  if (DisableScheduling)
3181    DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3182
3183  if (HasChain) {
3184    SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3185    if (OnlyLoad)
3186      PendingLoads.push_back(Chain);
3187    else
3188      DAG.setRoot(Chain);
3189  }
3190
3191  if (!I.getType()->isVoidTy()) {
3192    if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3193      EVT VT = TLI.getValueType(PTy);
3194      Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
3195
3196      if (DisableScheduling)
3197        DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3198    }
3199
3200    setValue(&I, Result);
3201  }
3202}
3203
3204/// GetSignificand - Get the significand and build it into a floating-point
3205/// number with exponent of 1:
3206///
3207///   Op = (Op & 0x007fffff) | 0x3f800000;
3208///
3209/// where Op is the hexidecimal representation of floating point value.
3210static SDValue
3211GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
3212  SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3213                           DAG.getConstant(0x007fffff, MVT::i32));
3214  SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3215                           DAG.getConstant(0x3f800000, MVT::i32));
3216  SDValue Res = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3217
3218  if (DisableScheduling) {
3219    DAG.AssignOrdering(t1.getNode(), Order);
3220    DAG.AssignOrdering(t2.getNode(), Order);
3221    DAG.AssignOrdering(Res.getNode(), Order);
3222  }
3223
3224  return Res;
3225}
3226
3227/// GetExponent - Get the exponent:
3228///
3229///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3230///
3231/// where Op is the hexidecimal representation of floating point value.
3232static SDValue
3233GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3234            DebugLoc dl, unsigned Order) {
3235  SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3236                           DAG.getConstant(0x7f800000, MVT::i32));
3237  SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3238                           DAG.getConstant(23, TLI.getPointerTy()));
3239  SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3240                           DAG.getConstant(127, MVT::i32));
3241  SDValue Res = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3242
3243  if (DisableScheduling) {
3244    DAG.AssignOrdering(t0.getNode(), Order);
3245    DAG.AssignOrdering(t1.getNode(), Order);
3246    DAG.AssignOrdering(t2.getNode(), Order);
3247    DAG.AssignOrdering(Res.getNode(), Order);
3248  }
3249
3250  return Res;
3251}
3252
3253/// getF32Constant - Get 32-bit floating point constant.
3254static SDValue
3255getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3256  return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3257}
3258
3259/// Inlined utility function to implement binary input atomic intrinsics for
3260/// visitIntrinsicCall: I is a call instruction
3261///                     Op is the associated NodeType for I
3262const char *
3263SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3264  SDValue Root = getRoot();
3265  SDValue L =
3266    DAG.getAtomic(Op, getCurDebugLoc(),
3267                  getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3268                  Root,
3269                  getValue(I.getOperand(1)),
3270                  getValue(I.getOperand(2)),
3271                  I.getOperand(1));
3272  setValue(&I, L);
3273  DAG.setRoot(L.getValue(1));
3274
3275  if (DisableScheduling)
3276    DAG.AssignOrdering(L.getNode(), SDNodeOrder);
3277
3278  return 0;
3279}
3280
3281// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3282const char *
3283SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3284  SDValue Op1 = getValue(I.getOperand(1));
3285  SDValue Op2 = getValue(I.getOperand(2));
3286
3287  SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3288  SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
3289
3290  setValue(&I, Result);
3291
3292  if (DisableScheduling)
3293    DAG.AssignOrdering(Result.getNode(), SDNodeOrder);
3294
3295  return 0;
3296}
3297
3298/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3299/// limited-precision mode.
3300void
3301SelectionDAGBuilder::visitExp(CallInst &I) {
3302  SDValue result;
3303  DebugLoc dl = getCurDebugLoc();
3304
3305  if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3306      LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3307    SDValue Op = getValue(I.getOperand(1));
3308
3309    // Put the exponent in the right bit position for later addition to the
3310    // final result:
3311    //
3312    //   #define LOG2OFe 1.4426950f
3313    //   IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3314    SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3315                             getF32Constant(DAG, 0x3fb8aa3b));
3316    SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3317
3318    //   FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3319    SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3320    SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3321
3322    if (DisableScheduling) {
3323      DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3324      DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3325      DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3326      DAG.AssignOrdering(X.getNode(), SDNodeOrder);
3327    }
3328
3329    //   IntegerPartOfX <<= 23;
3330    IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3331                                 DAG.getConstant(23, TLI.getPointerTy()));
3332
3333    if (DisableScheduling)
3334      DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3335
3336    if (LimitFloatPrecision <= 6) {
3337      // For floating-point precision of 6:
3338      //
3339      //   TwoToFractionalPartOfX =
3340      //     0.997535578f +
3341      //       (0.735607626f + 0.252464424f * x) * x;
3342      //
3343      // error 0.0144103317, which is 6 bits
3344      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3345                               getF32Constant(DAG, 0x3e814304));
3346      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3347                               getF32Constant(DAG, 0x3f3c50c8));
3348      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3349      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3350                               getF32Constant(DAG, 0x3f7f5e7e));
3351      SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3352
3353      // Add the exponent into the result in integer domain.
3354      SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3355                               TwoToFracPartOfX, IntegerPartOfX);
3356
3357      result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3358
3359      if (DisableScheduling) {
3360        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3361        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3362        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3363        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3364        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3365        DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3366        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3367      }
3368    } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3369      // For floating-point precision of 12:
3370      //
3371      //   TwoToFractionalPartOfX =
3372      //     0.999892986f +
3373      //       (0.696457318f +
3374      //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3375      //
3376      // 0.000107046256 error, which is 13 to 14 bits
3377      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3378                               getF32Constant(DAG, 0x3da235e3));
3379      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3380                               getF32Constant(DAG, 0x3e65b8f3));
3381      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3382      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3383                               getF32Constant(DAG, 0x3f324b07));
3384      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3385      SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3386                               getF32Constant(DAG, 0x3f7ff8fd));
3387      SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3388
3389      // Add the exponent into the result in integer domain.
3390      SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3391                               TwoToFracPartOfX, IntegerPartOfX);
3392
3393      result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3394
3395      if (DisableScheduling) {
3396        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3397        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3398        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3399        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3400        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3401        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3402        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3403        DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3404        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3405      }
3406    } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3407      // For floating-point precision of 18:
3408      //
3409      //   TwoToFractionalPartOfX =
3410      //     0.999999982f +
3411      //       (0.693148872f +
3412      //         (0.240227044f +
3413      //           (0.554906021e-1f +
3414      //             (0.961591928e-2f +
3415      //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3416      //
3417      // error 2.47208000*10^(-7), which is better than 18 bits
3418      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3419                               getF32Constant(DAG, 0x3924b03e));
3420      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3421                               getF32Constant(DAG, 0x3ab24b87));
3422      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3423      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3424                               getF32Constant(DAG, 0x3c1d8c17));
3425      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3426      SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3427                               getF32Constant(DAG, 0x3d634a1d));
3428      SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3429      SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3430                               getF32Constant(DAG, 0x3e75fe14));
3431      SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3432      SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3433                                getF32Constant(DAG, 0x3f317234));
3434      SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3435      SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3436                                getF32Constant(DAG, 0x3f800000));
3437      SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3438                                             MVT::i32, t13);
3439
3440      // Add the exponent into the result in integer domain.
3441      SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3442                                TwoToFracPartOfX, IntegerPartOfX);
3443
3444      result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3445
3446      if (DisableScheduling) {
3447        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3448        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3449        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3450        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3451        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3452        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3453        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3454        DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3455        DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3456        DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
3457        DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
3458        DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
3459        DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
3460        DAG.AssignOrdering(TwoToFracPartOfX.getNode(), SDNodeOrder);
3461        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3462      }
3463    }
3464  } else {
3465    // No special expansion.
3466    result = DAG.getNode(ISD::FEXP, dl,
3467                         getValue(I.getOperand(1)).getValueType(),
3468                         getValue(I.getOperand(1)));
3469    if (DisableScheduling)
3470      DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3471  }
3472
3473  setValue(&I, result);
3474}
3475
3476/// visitLog - Lower a log intrinsic. Handles the special sequences for
3477/// limited-precision mode.
3478void
3479SelectionDAGBuilder::visitLog(CallInst &I) {
3480  SDValue result;
3481  DebugLoc dl = getCurDebugLoc();
3482
3483  if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3484      LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3485    SDValue Op = getValue(I.getOperand(1));
3486    SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3487
3488    if (DisableScheduling)
3489      DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3490
3491    // Scale the exponent by log(2) [0.69314718f].
3492    SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3493    SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3494                                        getF32Constant(DAG, 0x3f317218));
3495
3496    if (DisableScheduling)
3497      DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3498
3499    // Get the significand and build it into a floating-point number with
3500    // exponent of 1.
3501    SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3502
3503    if (LimitFloatPrecision <= 6) {
3504      // For floating-point precision of 6:
3505      //
3506      //   LogofMantissa =
3507      //     -1.1609546f +
3508      //       (1.4034025f - 0.23903021f * x) * x;
3509      //
3510      // error 0.0034276066, which is better than 8 bits
3511      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3512                               getF32Constant(DAG, 0xbe74c456));
3513      SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3514                               getF32Constant(DAG, 0x3fb3a2b1));
3515      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3516      SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3517                                          getF32Constant(DAG, 0x3f949a29));
3518
3519      result = DAG.getNode(ISD::FADD, dl,
3520                           MVT::f32, LogOfExponent, LogOfMantissa);
3521
3522      if (DisableScheduling) {
3523        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3524        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3525        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3526        DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3527        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3528      }
3529    } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3530      // For floating-point precision of 12:
3531      //
3532      //   LogOfMantissa =
3533      //     -1.7417939f +
3534      //       (2.8212026f +
3535      //         (-1.4699568f +
3536      //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3537      //
3538      // error 0.000061011436, which is 14 bits
3539      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3540                               getF32Constant(DAG, 0xbd67b6d6));
3541      SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3542                               getF32Constant(DAG, 0x3ee4f4b8));
3543      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3544      SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3545                               getF32Constant(DAG, 0x3fbc278b));
3546      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3547      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3548                               getF32Constant(DAG, 0x40348e95));
3549      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3550      SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3551                                          getF32Constant(DAG, 0x3fdef31a));
3552
3553      result = DAG.getNode(ISD::FADD, dl,
3554                           MVT::f32, LogOfExponent, LogOfMantissa);
3555
3556      if (DisableScheduling) {
3557        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3558        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3559        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3560        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3561        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3562        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3563        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3564        DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3565        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3566      }
3567    } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3568      // For floating-point precision of 18:
3569      //
3570      //   LogOfMantissa =
3571      //     -2.1072184f +
3572      //       (4.2372794f +
3573      //         (-3.7029485f +
3574      //           (2.2781945f +
3575      //             (-0.87823314f +
3576      //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3577      //
3578      // error 0.0000023660568, which is better than 18 bits
3579      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3580                               getF32Constant(DAG, 0xbc91e5ac));
3581      SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3582                               getF32Constant(DAG, 0x3e4350aa));
3583      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3584      SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3585                               getF32Constant(DAG, 0x3f60d3e3));
3586      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3587      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3588                               getF32Constant(DAG, 0x4011cdf0));
3589      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3590      SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3591                               getF32Constant(DAG, 0x406cfd1c));
3592      SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3593      SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3594                               getF32Constant(DAG, 0x408797cb));
3595      SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3596      SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3597                                          getF32Constant(DAG, 0x4006dcab));
3598
3599      result = DAG.getNode(ISD::FADD, dl,
3600                           MVT::f32, LogOfExponent, LogOfMantissa);
3601
3602      if (DisableScheduling) {
3603        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3604        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3605        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3606        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3607        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3608        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3609        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3610        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3611        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3612        DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3613        DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3614        DAG.AssignOrdering(LogOfMantissa.getNode(), SDNodeOrder);
3615        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3616      }
3617    }
3618  } else {
3619    // No special expansion.
3620    result = DAG.getNode(ISD::FLOG, dl,
3621                         getValue(I.getOperand(1)).getValueType(),
3622                         getValue(I.getOperand(1)));
3623
3624    if (DisableScheduling)
3625      DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3626  }
3627
3628  setValue(&I, result);
3629}
3630
3631/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3632/// limited-precision mode.
3633void
3634SelectionDAGBuilder::visitLog2(CallInst &I) {
3635  SDValue result;
3636  DebugLoc dl = getCurDebugLoc();
3637
3638  if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3639      LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3640    SDValue Op = getValue(I.getOperand(1));
3641    SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3642
3643    if (DisableScheduling)
3644      DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3645
3646    // Get the exponent.
3647    SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3648
3649    if (DisableScheduling)
3650      DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3651
3652    // Get the significand and build it into a floating-point number with
3653    // exponent of 1.
3654    SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3655
3656    // Different possible minimax approximations of significand in
3657    // floating-point for various degrees of accuracy over [1,2].
3658    if (LimitFloatPrecision <= 6) {
3659      // For floating-point precision of 6:
3660      //
3661      //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3662      //
3663      // error 0.0049451742, which is more than 7 bits
3664      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3665                               getF32Constant(DAG, 0xbeb08fe0));
3666      SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3667                               getF32Constant(DAG, 0x40019463));
3668      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3669      SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3670                                           getF32Constant(DAG, 0x3fd6633d));
3671
3672      result = DAG.getNode(ISD::FADD, dl,
3673                           MVT::f32, LogOfExponent, Log2ofMantissa);
3674
3675      if (DisableScheduling) {
3676        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3677        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3678        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3679        DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3680        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3681      }
3682    } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3683      // For floating-point precision of 12:
3684      //
3685      //   Log2ofMantissa =
3686      //     -2.51285454f +
3687      //       (4.07009056f +
3688      //         (-2.12067489f +
3689      //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3690      //
3691      // error 0.0000876136000, which is better than 13 bits
3692      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3693                               getF32Constant(DAG, 0xbda7262e));
3694      SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3695                               getF32Constant(DAG, 0x3f25280b));
3696      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3697      SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3698                               getF32Constant(DAG, 0x4007b923));
3699      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3700      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3701                               getF32Constant(DAG, 0x40823e2f));
3702      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3703      SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3704                                           getF32Constant(DAG, 0x4020d29c));
3705
3706      result = DAG.getNode(ISD::FADD, dl,
3707                           MVT::f32, LogOfExponent, Log2ofMantissa);
3708
3709      if (DisableScheduling) {
3710        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3711        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3712        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3713        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3714        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3715        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3716        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3717        DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3718        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3719      }
3720    } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3721      // For floating-point precision of 18:
3722      //
3723      //   Log2ofMantissa =
3724      //     -3.0400495f +
3725      //       (6.1129976f +
3726      //         (-5.3420409f +
3727      //           (3.2865683f +
3728      //             (-1.2669343f +
3729      //               (0.27515199f -
3730      //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3731      //
3732      // error 0.0000018516, which is better than 18 bits
3733      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3734                               getF32Constant(DAG, 0xbcd2769e));
3735      SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3736                               getF32Constant(DAG, 0x3e8ce0b9));
3737      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3738      SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3739                               getF32Constant(DAG, 0x3fa22ae7));
3740      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3741      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3742                               getF32Constant(DAG, 0x40525723));
3743      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3744      SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3745                               getF32Constant(DAG, 0x40aaf200));
3746      SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3747      SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3748                               getF32Constant(DAG, 0x40c39dad));
3749      SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3750      SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3751                                           getF32Constant(DAG, 0x4042902c));
3752
3753      result = DAG.getNode(ISD::FADD, dl,
3754                           MVT::f32, LogOfExponent, Log2ofMantissa);
3755
3756      if (DisableScheduling) {
3757        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3758        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3759        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3760        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3761        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3762        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3763        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3764        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3765        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3766        DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
3767        DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
3768        DAG.AssignOrdering(Log2ofMantissa.getNode(), SDNodeOrder);
3769        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3770      }
3771    }
3772  } else {
3773    // No special expansion.
3774    result = DAG.getNode(ISD::FLOG2, dl,
3775                         getValue(I.getOperand(1)).getValueType(),
3776                         getValue(I.getOperand(1)));
3777
3778    if (DisableScheduling)
3779      DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3780  }
3781
3782  setValue(&I, result);
3783}
3784
3785/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3786/// limited-precision mode.
3787void
3788SelectionDAGBuilder::visitLog10(CallInst &I) {
3789  SDValue result;
3790  DebugLoc dl = getCurDebugLoc();
3791
3792  if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3793      LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3794    SDValue Op = getValue(I.getOperand(1));
3795    SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3796
3797    if (DisableScheduling)
3798      DAG.AssignOrdering(Op1.getNode(), SDNodeOrder);
3799
3800    // Scale the exponent by log10(2) [0.30102999f].
3801    SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3802    SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3803                                        getF32Constant(DAG, 0x3e9a209a));
3804
3805    if (DisableScheduling)
3806      DAG.AssignOrdering(LogOfExponent.getNode(), SDNodeOrder);
3807
3808    // Get the significand and build it into a floating-point number with
3809    // exponent of 1.
3810    SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
3811
3812    if (LimitFloatPrecision <= 6) {
3813      // For floating-point precision of 6:
3814      //
3815      //   Log10ofMantissa =
3816      //     -0.50419619f +
3817      //       (0.60948995f - 0.10380950f * x) * x;
3818      //
3819      // error 0.0014886165, which is 6 bits
3820      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3821                               getF32Constant(DAG, 0xbdd49a13));
3822      SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3823                               getF32Constant(DAG, 0x3f1c0789));
3824      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3825      SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3826                                            getF32Constant(DAG, 0x3f011300));
3827
3828      result = DAG.getNode(ISD::FADD, dl,
3829                           MVT::f32, LogOfExponent, Log10ofMantissa);
3830
3831      if (DisableScheduling) {
3832        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3833        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3834        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3835        DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3836        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3837      }
3838    } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3839      // For floating-point precision of 12:
3840      //
3841      //   Log10ofMantissa =
3842      //     -0.64831180f +
3843      //       (0.91751397f +
3844      //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3845      //
3846      // error 0.00019228036, which is better than 12 bits
3847      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3848                               getF32Constant(DAG, 0x3d431f31));
3849      SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3850                               getF32Constant(DAG, 0x3ea21fb2));
3851      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3852      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3853                               getF32Constant(DAG, 0x3f6ae232));
3854      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3855      SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3856                                            getF32Constant(DAG, 0x3f25f7c3));
3857
3858      result = DAG.getNode(ISD::FADD, dl,
3859                           MVT::f32, LogOfExponent, Log10ofMantissa);
3860
3861      if (DisableScheduling) {
3862        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3863        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3864        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3865        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3866        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3867        DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3868        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3869      }
3870    } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3871      // For floating-point precision of 18:
3872      //
3873      //   Log10ofMantissa =
3874      //     -0.84299375f +
3875      //       (1.5327582f +
3876      //         (-1.0688956f +
3877      //           (0.49102474f +
3878      //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3879      //
3880      // error 0.0000037995730, which is better than 18 bits
3881      SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3882                               getF32Constant(DAG, 0x3c5d51ce));
3883      SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3884                               getF32Constant(DAG, 0x3e00685a));
3885      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3886      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3887                               getF32Constant(DAG, 0x3efb6798));
3888      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3889      SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3890                               getF32Constant(DAG, 0x3f88d192));
3891      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3892      SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3893                               getF32Constant(DAG, 0x3fc4316c));
3894      SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3895      SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3896                                            getF32Constant(DAG, 0x3f57ce70));
3897
3898      result = DAG.getNode(ISD::FADD, dl,
3899                           MVT::f32, LogOfExponent, Log10ofMantissa);
3900
3901      if (DisableScheduling) {
3902        DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
3903        DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3904        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3905        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3906        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3907        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3908        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3909        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
3910        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
3911        DAG.AssignOrdering(Log10ofMantissa.getNode(), SDNodeOrder);
3912        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3913      }
3914    }
3915  } else {
3916    // No special expansion.
3917    result = DAG.getNode(ISD::FLOG10, dl,
3918                         getValue(I.getOperand(1)).getValueType(),
3919                         getValue(I.getOperand(1)));
3920
3921    if (DisableScheduling)
3922      DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3923  }
3924
3925  setValue(&I, result);
3926}
3927
3928/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3929/// limited-precision mode.
3930void
3931SelectionDAGBuilder::visitExp2(CallInst &I) {
3932  SDValue result;
3933  DebugLoc dl = getCurDebugLoc();
3934
3935  if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3936      LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3937    SDValue Op = getValue(I.getOperand(1));
3938
3939    SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3940
3941    if (DisableScheduling)
3942      DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3943
3944    //   FractionalPartOfX = x - (float)IntegerPartOfX;
3945    SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3946    SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3947
3948    //   IntegerPartOfX <<= 23;
3949    IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3950                                 DAG.getConstant(23, TLI.getPointerTy()));
3951
3952    if (DisableScheduling) {
3953      DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
3954      DAG.AssignOrdering(X.getNode(), SDNodeOrder);
3955      DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
3956    }
3957
3958    if (LimitFloatPrecision <= 6) {
3959      // For floating-point precision of 6:
3960      //
3961      //   TwoToFractionalPartOfX =
3962      //     0.997535578f +
3963      //       (0.735607626f + 0.252464424f * x) * x;
3964      //
3965      // error 0.0144103317, which is 6 bits
3966      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3967                               getF32Constant(DAG, 0x3e814304));
3968      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3969                               getF32Constant(DAG, 0x3f3c50c8));
3970      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3971      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3972                               getF32Constant(DAG, 0x3f7f5e7e));
3973      SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3974      SDValue TwoToFractionalPartOfX =
3975        DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3976
3977      result = DAG.getNode(ISD::BIT_CONVERT, dl,
3978                           MVT::f32, TwoToFractionalPartOfX);
3979
3980      if (DisableScheduling) {
3981        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
3982        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
3983        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
3984        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
3985        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
3986        DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
3987        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
3988      }
3989    } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3990      // For floating-point precision of 12:
3991      //
3992      //   TwoToFractionalPartOfX =
3993      //     0.999892986f +
3994      //       (0.696457318f +
3995      //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3996      //
3997      // error 0.000107046256, which is 13 to 14 bits
3998      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3999                               getF32Constant(DAG, 0x3da235e3));
4000      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4001                               getF32Constant(DAG, 0x3e65b8f3));
4002      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4003      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4004                               getF32Constant(DAG, 0x3f324b07));
4005      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4006      SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4007                               getF32Constant(DAG, 0x3f7ff8fd));
4008      SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
4009      SDValue TwoToFractionalPartOfX =
4010        DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4011
4012      result = DAG.getNode(ISD::BIT_CONVERT, dl,
4013                           MVT::f32, TwoToFractionalPartOfX);
4014
4015      if (DisableScheduling) {
4016        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4017        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4018        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4019        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4020        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4021        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4022        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4023        DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4024        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4025      }
4026    } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4027      // For floating-point precision of 18:
4028      //
4029      //   TwoToFractionalPartOfX =
4030      //     0.999999982f +
4031      //       (0.693148872f +
4032      //         (0.240227044f +
4033      //           (0.554906021e-1f +
4034      //             (0.961591928e-2f +
4035      //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4036      // error 2.47208000*10^(-7), which is better than 18 bits
4037      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4038                               getF32Constant(DAG, 0x3924b03e));
4039      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4040                               getF32Constant(DAG, 0x3ab24b87));
4041      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4042      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4043                               getF32Constant(DAG, 0x3c1d8c17));
4044      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4045      SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4046                               getF32Constant(DAG, 0x3d634a1d));
4047      SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4048      SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4049                               getF32Constant(DAG, 0x3e75fe14));
4050      SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4051      SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4052                                getF32Constant(DAG, 0x3f317234));
4053      SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4054      SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4055                                getF32Constant(DAG, 0x3f800000));
4056      SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
4057      SDValue TwoToFractionalPartOfX =
4058        DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4059
4060      result = DAG.getNode(ISD::BIT_CONVERT, dl,
4061                           MVT::f32, TwoToFractionalPartOfX);
4062
4063      if (DisableScheduling) {
4064        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4065        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4066        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4067        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4068        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4069        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4070        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4071        DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
4072        DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
4073        DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
4074        DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
4075        DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
4076        DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
4077        DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4078        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4079      }
4080    }
4081  } else {
4082    // No special expansion.
4083    result = DAG.getNode(ISD::FEXP2, dl,
4084                         getValue(I.getOperand(1)).getValueType(),
4085                         getValue(I.getOperand(1)));
4086
4087    if (DisableScheduling)
4088      DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4089  }
4090
4091  setValue(&I, result);
4092}
4093
4094/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4095/// limited-precision mode with x == 10.0f.
4096void
4097SelectionDAGBuilder::visitPow(CallInst &I) {
4098  SDValue result;
4099  Value *Val = I.getOperand(1);
4100  DebugLoc dl = getCurDebugLoc();
4101  bool IsExp10 = false;
4102
4103  if (getValue(Val).getValueType() == MVT::f32 &&
4104      getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
4105      LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4106    if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
4107      if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
4108        APFloat Ten(10.0f);
4109        IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
4110      }
4111    }
4112  }
4113
4114  if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4115    SDValue Op = getValue(I.getOperand(2));
4116
4117    // Put the exponent in the right bit position for later addition to the
4118    // final result:
4119    //
4120    //   #define LOG2OF10 3.3219281f
4121    //   IntegerPartOfX = (int32_t)(x * LOG2OF10);
4122    SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4123                             getF32Constant(DAG, 0x40549a78));
4124    SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4125
4126    //   FractionalPartOfX = x - (float)IntegerPartOfX;
4127    SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4128    SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4129
4130    if (DisableScheduling) {
4131      DAG.AssignOrdering(t0.getNode(), SDNodeOrder);
4132      DAG.AssignOrdering(t1.getNode(), SDNodeOrder);
4133      DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
4134      DAG.AssignOrdering(X.getNode(), SDNodeOrder);
4135    }
4136
4137    //   IntegerPartOfX <<= 23;
4138    IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4139                                 DAG.getConstant(23, TLI.getPointerTy()));
4140
4141    if (DisableScheduling)
4142      DAG.AssignOrdering(IntegerPartOfX.getNode(), SDNodeOrder);
4143
4144    if (LimitFloatPrecision <= 6) {
4145      // For floating-point precision of 6:
4146      //
4147      //   twoToFractionalPartOfX =
4148      //     0.997535578f +
4149      //       (0.735607626f + 0.252464424f * x) * x;
4150      //
4151      // error 0.0144103317, which is 6 bits
4152      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4153                               getF32Constant(DAG, 0x3e814304));
4154      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4155                               getF32Constant(DAG, 0x3f3c50c8));
4156      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4157      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4158                               getF32Constant(DAG, 0x3f7f5e7e));
4159      SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
4160      SDValue TwoToFractionalPartOfX =
4161        DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4162
4163      result = DAG.getNode(ISD::BIT_CONVERT, dl,
4164                           MVT::f32, TwoToFractionalPartOfX);
4165
4166      if (DisableScheduling) {
4167        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4168        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4169        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4170        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4171        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4172        DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4173        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4174      }
4175    } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4176      // For floating-point precision of 12:
4177      //
4178      //   TwoToFractionalPartOfX =
4179      //     0.999892986f +
4180      //       (0.696457318f +
4181      //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4182      //
4183      // error 0.000107046256, which is 13 to 14 bits
4184      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4185                               getF32Constant(DAG, 0x3da235e3));
4186      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4187                               getF32Constant(DAG, 0x3e65b8f3));
4188      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4189      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4190                               getF32Constant(DAG, 0x3f324b07));
4191      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4192      SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4193                               getF32Constant(DAG, 0x3f7ff8fd));
4194      SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
4195      SDValue TwoToFractionalPartOfX =
4196        DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4197
4198      result = DAG.getNode(ISD::BIT_CONVERT, dl,
4199                           MVT::f32, TwoToFractionalPartOfX);
4200
4201      if (DisableScheduling) {
4202        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4203        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4204        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4205        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4206        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4207        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4208        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4209        DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4210        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4211      }
4212    } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4213      // For floating-point precision of 18:
4214      //
4215      //   TwoToFractionalPartOfX =
4216      //     0.999999982f +
4217      //       (0.693148872f +
4218      //         (0.240227044f +
4219      //           (0.554906021e-1f +
4220      //             (0.961591928e-2f +
4221      //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4222      // error 2.47208000*10^(-7), which is better than 18 bits
4223      SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4224                               getF32Constant(DAG, 0x3924b03e));
4225      SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4226                               getF32Constant(DAG, 0x3ab24b87));
4227      SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4228      SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4229                               getF32Constant(DAG, 0x3c1d8c17));
4230      SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4231      SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4232                               getF32Constant(DAG, 0x3d634a1d));
4233      SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4234      SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4235                               getF32Constant(DAG, 0x3e75fe14));
4236      SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4237      SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4238                                getF32Constant(DAG, 0x3f317234));
4239      SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4240      SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4241                                getF32Constant(DAG, 0x3f800000));
4242      SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
4243      SDValue TwoToFractionalPartOfX =
4244        DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4245
4246      result = DAG.getNode(ISD::BIT_CONVERT, dl,
4247                           MVT::f32, TwoToFractionalPartOfX);
4248
4249      if (DisableScheduling) {
4250        DAG.AssignOrdering(t2.getNode(), SDNodeOrder);
4251        DAG.AssignOrdering(t3.getNode(), SDNodeOrder);
4252        DAG.AssignOrdering(t4.getNode(), SDNodeOrder);
4253        DAG.AssignOrdering(t5.getNode(), SDNodeOrder);
4254        DAG.AssignOrdering(t6.getNode(), SDNodeOrder);
4255        DAG.AssignOrdering(t7.getNode(), SDNodeOrder);
4256        DAG.AssignOrdering(t8.getNode(), SDNodeOrder);
4257        DAG.AssignOrdering(t9.getNode(), SDNodeOrder);
4258        DAG.AssignOrdering(t10.getNode(), SDNodeOrder);
4259        DAG.AssignOrdering(t11.getNode(), SDNodeOrder);
4260        DAG.AssignOrdering(t12.getNode(), SDNodeOrder);
4261        DAG.AssignOrdering(t13.getNode(), SDNodeOrder);
4262        DAG.AssignOrdering(t14.getNode(), SDNodeOrder);
4263        DAG.AssignOrdering(TwoToFractionalPartOfX.getNode(), SDNodeOrder);
4264        DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4265      }
4266    }
4267  } else {
4268    // No special expansion.
4269    result = DAG.getNode(ISD::FPOW, dl,
4270                         getValue(I.getOperand(1)).getValueType(),
4271                         getValue(I.getOperand(1)),
4272                         getValue(I.getOperand(2)));
4273
4274    if (DisableScheduling)
4275      DAG.AssignOrdering(result.getNode(), SDNodeOrder);
4276  }
4277
4278  setValue(&I, result);
4279}
4280
4281
4282/// ExpandPowI - Expand a llvm.powi intrinsic.
4283static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
4284                          SelectionDAG &DAG) {
4285  // If RHS is a constant, we can expand this out to a multiplication tree,
4286  // otherwise we end up lowering to a call to __powidf2 (for example).  When
4287  // optimizing for size, we only want to do this if the expansion would produce
4288  // a small number of multiplies, otherwise we do the full expansion.
4289  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4290    // Get the exponent as a positive value.
4291    unsigned Val = RHSC->getSExtValue();
4292    if ((int)Val < 0) Val = -Val;
4293
4294    // powi(x, 0) -> 1.0
4295    if (Val == 0)
4296      return DAG.getConstantFP(1.0, LHS.getValueType());
4297
4298    Function *F = DAG.getMachineFunction().getFunction();
4299    if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
4300        // If optimizing for size, don't insert too many multiplies.  This
4301        // inserts up to 5 multiplies.
4302        CountPopulation_32(Val)+Log2_32(Val) < 7) {
4303      // We use the simple binary decomposition method to generate the multiply
4304      // sequence.  There are more optimal ways to do this (for example,
4305      // powi(x,15) generates one more multiply than it should), but this has
4306      // the benefit of being both really simple and much better than a libcall.
4307      SDValue Res;  // Logically starts equal to 1.0
4308      SDValue CurSquare = LHS;
4309      while (Val) {
4310        if (Val & 1) {
4311          if (Res.getNode())
4312            Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4313          else
4314            Res = CurSquare;  // 1.0*CurSquare.
4315        }
4316
4317        CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4318                                CurSquare, CurSquare);
4319        Val >>= 1;
4320      }
4321
4322      // If the original was negative, invert the result, producing 1/(x*x*x).
4323      if (RHSC->getSExtValue() < 0)
4324        Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4325                          DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4326      return Res;
4327    }
4328  }
4329
4330  // Otherwise, expand to a libcall.
4331  return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4332}
4333
4334
4335/// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
4336/// we want to emit this as a call to a named external function, return the name
4337/// otherwise lower it and return null.
4338const char *
4339SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
4340  DebugLoc dl = getCurDebugLoc();
4341  SDValue Res;
4342
4343  switch (Intrinsic) {
4344  default:
4345    // By default, turn this into a target intrinsic node.
4346    visitTargetIntrinsic(I, Intrinsic);
4347    return 0;
4348  case Intrinsic::vastart:  visitVAStart(I); return 0;
4349  case Intrinsic::vaend:    visitVAEnd(I); return 0;
4350  case Intrinsic::vacopy:   visitVACopy(I); return 0;
4351  case Intrinsic::returnaddress:
4352    Res = DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4353                      getValue(I.getOperand(1)));
4354    setValue(&I, Res);
4355    if (DisableScheduling)
4356      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4357    return 0;
4358  case Intrinsic::frameaddress:
4359    Res = DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4360                      getValue(I.getOperand(1)));
4361    setValue(&I, Res);
4362    if (DisableScheduling)
4363      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4364    return 0;
4365  case Intrinsic::setjmp:
4366    return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4367  case Intrinsic::longjmp:
4368    return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4369  case Intrinsic::memcpy: {
4370    SDValue Op1 = getValue(I.getOperand(1));
4371    SDValue Op2 = getValue(I.getOperand(2));
4372    SDValue Op3 = getValue(I.getOperand(3));
4373    unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4374    Res = DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
4375                        I.getOperand(1), 0, I.getOperand(2), 0);
4376    DAG.setRoot(Res);
4377    if (DisableScheduling)
4378      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4379    return 0;
4380  }
4381  case Intrinsic::memset: {
4382    SDValue Op1 = getValue(I.getOperand(1));
4383    SDValue Op2 = getValue(I.getOperand(2));
4384    SDValue Op3 = getValue(I.getOperand(3));
4385    unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4386    Res = DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
4387                        I.getOperand(1), 0);
4388    DAG.setRoot(Res);
4389    if (DisableScheduling)
4390      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4391    return 0;
4392  }
4393  case Intrinsic::memmove: {
4394    SDValue Op1 = getValue(I.getOperand(1));
4395    SDValue Op2 = getValue(I.getOperand(2));
4396    SDValue Op3 = getValue(I.getOperand(3));
4397    unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
4398
4399    // If the source and destination are known to not be aliases, we can
4400    // lower memmove as memcpy.
4401    uint64_t Size = -1ULL;
4402    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4403      Size = C->getZExtValue();
4404    if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4405        AliasAnalysis::NoAlias) {
4406      Res = DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
4407                          I.getOperand(1), 0, I.getOperand(2), 0);
4408      DAG.setRoot(Res);
4409      if (DisableScheduling)
4410        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4411      return 0;
4412    }
4413
4414    Res = DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
4415                         I.getOperand(1), 0, I.getOperand(2), 0);
4416    DAG.setRoot(Res);
4417    if (DisableScheduling)
4418      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4419    return 0;
4420  }
4421  case Intrinsic::dbg_declare: {
4422    if (OptLevel != CodeGenOpt::None)
4423      // FIXME: Variable debug info is not supported here.
4424      return 0;
4425    DwarfWriter *DW = DAG.getDwarfWriter();
4426    if (!DW)
4427      return 0;
4428    DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4429    if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
4430      return 0;
4431
4432    MDNode *Variable = DI.getVariable();
4433    Value *Address = DI.getAddress();
4434    if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4435      Address = BCI->getOperand(0);
4436    AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4437    // Don't handle byval struct arguments or VLAs, for example.
4438    if (!AI)
4439      return 0;
4440    DenseMap<const AllocaInst*, int>::iterator SI =
4441      FuncInfo.StaticAllocaMap.find(AI);
4442    if (SI == FuncInfo.StaticAllocaMap.end())
4443      return 0; // VLAs.
4444    int FI = SI->second;
4445
4446    if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
4447      if (MDNode *Dbg = DI.getMetadata("dbg"))
4448        MMI->setVariableDbgInfo(Variable, FI, Dbg);
4449    return 0;
4450  }
4451  case Intrinsic::eh_exception: {
4452    // Insert the EXCEPTIONADDR instruction.
4453    assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
4454    SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4455    SDValue Ops[1];
4456    Ops[0] = DAG.getRoot();
4457    SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4458    setValue(&I, Op);
4459    DAG.setRoot(Op.getValue(1));
4460    if (DisableScheduling)
4461      DAG.AssignOrdering(Op.getNode(), SDNodeOrder);
4462    return 0;
4463  }
4464
4465  case Intrinsic::eh_selector: {
4466    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4467
4468    if (CurMBB->isLandingPad())
4469      AddCatchInfo(I, MMI, CurMBB);
4470    else {
4471#ifndef NDEBUG
4472      FuncInfo.CatchInfoLost.insert(&I);
4473#endif
4474      // FIXME: Mark exception selector register as live in.  Hack for PR1508.
4475      unsigned Reg = TLI.getExceptionSelectorRegister();
4476      if (Reg) CurMBB->addLiveIn(Reg);
4477    }
4478
4479    // Insert the EHSELECTION instruction.
4480    SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4481    SDValue Ops[2];
4482    Ops[0] = getValue(I.getOperand(1));
4483    Ops[1] = getRoot();
4484    SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4485
4486    DAG.setRoot(Op.getValue(1));
4487
4488    Res = DAG.getSExtOrTrunc(Op, dl, MVT::i32);
4489    setValue(&I, Res);
4490    if (DisableScheduling) {
4491      DAG.AssignOrdering(Op.getNode(), SDNodeOrder);
4492      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4493    }
4494    return 0;
4495  }
4496
4497  case Intrinsic::eh_typeid_for: {
4498    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4499
4500    if (MMI) {
4501      // Find the type id for the given typeinfo.
4502      GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4503      unsigned TypeID = MMI->getTypeIDFor(GV);
4504      Res = DAG.getConstant(TypeID, MVT::i32);
4505    } else {
4506      // Return something different to eh_selector.
4507      Res = DAG.getConstant(1, MVT::i32);
4508    }
4509
4510    setValue(&I, Res);
4511    if (DisableScheduling)
4512      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4513    return 0;
4514  }
4515
4516  case Intrinsic::eh_return_i32:
4517  case Intrinsic::eh_return_i64:
4518    if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4519      MMI->setCallsEHReturn(true);
4520      Res = DAG.getNode(ISD::EH_RETURN, dl,
4521                        MVT::Other,
4522                        getControlRoot(),
4523                        getValue(I.getOperand(1)),
4524                        getValue(I.getOperand(2)));
4525      DAG.setRoot(Res);
4526      if (DisableScheduling)
4527        DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4528    } else {
4529      setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4530    }
4531
4532    return 0;
4533  case Intrinsic::eh_unwind_init:
4534    if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4535      MMI->setCallsUnwindInit(true);
4536    }
4537    return 0;
4538  case Intrinsic::eh_dwarf_cfa: {
4539    EVT VT = getValue(I.getOperand(1)).getValueType();
4540    SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4541                                        TLI.getPointerTy());
4542    SDValue Offset = DAG.getNode(ISD::ADD, dl,
4543                                 TLI.getPointerTy(),
4544                                 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4545                                             TLI.getPointerTy()),
4546                                 CfaArg);
4547    SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4548                             TLI.getPointerTy(),
4549                             DAG.getConstant(0, TLI.getPointerTy()));
4550    Res = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4551                      FA, Offset);
4552    setValue(&I, Res);
4553    if (DisableScheduling) {
4554      DAG.AssignOrdering(CfaArg.getNode(), SDNodeOrder);
4555      DAG.AssignOrdering(Offset.getNode(), SDNodeOrder);
4556      DAG.AssignOrdering(FA.getNode(), SDNodeOrder);
4557      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4558    }
4559    return 0;
4560  }
4561  case Intrinsic::convertff:
4562  case Intrinsic::convertfsi:
4563  case Intrinsic::convertfui:
4564  case Intrinsic::convertsif:
4565  case Intrinsic::convertuif:
4566  case Intrinsic::convertss:
4567  case Intrinsic::convertsu:
4568  case Intrinsic::convertus:
4569  case Intrinsic::convertuu: {
4570    ISD::CvtCode Code = ISD::CVT_INVALID;
4571    switch (Intrinsic) {
4572    case Intrinsic::convertff:  Code = ISD::CVT_FF; break;
4573    case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4574    case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4575    case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4576    case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4577    case Intrinsic::convertss:  Code = ISD::CVT_SS; break;
4578    case Intrinsic::convertsu:  Code = ISD::CVT_SU; break;
4579    case Intrinsic::convertus:  Code = ISD::CVT_US; break;
4580    case Intrinsic::convertuu:  Code = ISD::CVT_UU; break;
4581    }
4582    EVT DestVT = TLI.getValueType(I.getType());
4583    Value *Op1 = I.getOperand(1);
4584    Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4585                               DAG.getValueType(DestVT),
4586                               DAG.getValueType(getValue(Op1).getValueType()),
4587                               getValue(I.getOperand(2)),
4588                               getValue(I.getOperand(3)),
4589                               Code);
4590    setValue(&I, Res);
4591    if (DisableScheduling)
4592      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4593    return 0;
4594  }
4595  case Intrinsic::sqrt:
4596    Res = DAG.getNode(ISD::FSQRT, dl,
4597                      getValue(I.getOperand(1)).getValueType(),
4598                      getValue(I.getOperand(1)));
4599    setValue(&I, Res);
4600    if (DisableScheduling)
4601      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4602    return 0;
4603  case Intrinsic::powi:
4604    Res = ExpandPowI(dl, getValue(I.getOperand(1)), getValue(I.getOperand(2)),
4605                     DAG);
4606    setValue(&I, Res);
4607    if (DisableScheduling)
4608      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4609    return 0;
4610  case Intrinsic::sin:
4611    Res = DAG.getNode(ISD::FSIN, dl,
4612                      getValue(I.getOperand(1)).getValueType(),
4613                      getValue(I.getOperand(1)));
4614    setValue(&I, Res);
4615    if (DisableScheduling)
4616      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4617    return 0;
4618  case Intrinsic::cos:
4619    Res = DAG.getNode(ISD::FCOS, dl,
4620                      getValue(I.getOperand(1)).getValueType(),
4621                      getValue(I.getOperand(1)));
4622    setValue(&I, Res);
4623    if (DisableScheduling)
4624      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4625    return 0;
4626  case Intrinsic::log:
4627    visitLog(I);
4628    return 0;
4629  case Intrinsic::log2:
4630    visitLog2(I);
4631    return 0;
4632  case Intrinsic::log10:
4633    visitLog10(I);
4634    return 0;
4635  case Intrinsic::exp:
4636    visitExp(I);
4637    return 0;
4638  case Intrinsic::exp2:
4639    visitExp2(I);
4640    return 0;
4641  case Intrinsic::pow:
4642    visitPow(I);
4643    return 0;
4644  case Intrinsic::pcmarker: {
4645    SDValue Tmp = getValue(I.getOperand(1));
4646    Res = DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp);
4647    DAG.setRoot(Res);
4648    if (DisableScheduling)
4649      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4650    return 0;
4651  }
4652  case Intrinsic::readcyclecounter: {
4653    SDValue Op = getRoot();
4654    Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4655                      DAG.getVTList(MVT::i64, MVT::Other),
4656                      &Op, 1);
4657    setValue(&I, Res);
4658    DAG.setRoot(Res.getValue(1));
4659    if (DisableScheduling)
4660      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4661    return 0;
4662  }
4663  case Intrinsic::bswap:
4664    Res = DAG.getNode(ISD::BSWAP, dl,
4665                      getValue(I.getOperand(1)).getValueType(),
4666                      getValue(I.getOperand(1)));
4667    setValue(&I, Res);
4668    if (DisableScheduling)
4669      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4670    return 0;
4671  case Intrinsic::cttz: {
4672    SDValue Arg = getValue(I.getOperand(1));
4673    EVT Ty = Arg.getValueType();
4674    Res = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4675    setValue(&I, Res);
4676    if (DisableScheduling)
4677      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4678    return 0;
4679  }
4680  case Intrinsic::ctlz: {
4681    SDValue Arg = getValue(I.getOperand(1));
4682    EVT Ty = Arg.getValueType();
4683    Res = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4684    setValue(&I, Res);
4685    if (DisableScheduling)
4686      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4687    return 0;
4688  }
4689  case Intrinsic::ctpop: {
4690    SDValue Arg = getValue(I.getOperand(1));
4691    EVT Ty = Arg.getValueType();
4692    Res = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4693    setValue(&I, Res);
4694    if (DisableScheduling)
4695      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4696    return 0;
4697  }
4698  case Intrinsic::stacksave: {
4699    SDValue Op = getRoot();
4700    Res = DAG.getNode(ISD::STACKSAVE, dl,
4701                      DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4702    setValue(&I, Res);
4703    DAG.setRoot(Res.getValue(1));
4704    if (DisableScheduling)
4705      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4706    return 0;
4707  }
4708  case Intrinsic::stackrestore: {
4709    Res = getValue(I.getOperand(1));
4710    Res = DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res);
4711    DAG.setRoot(Res);
4712    if (DisableScheduling)
4713      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4714    return 0;
4715  }
4716  case Intrinsic::stackprotector: {
4717    // Emit code into the DAG to store the stack guard onto the stack.
4718    MachineFunction &MF = DAG.getMachineFunction();
4719    MachineFrameInfo *MFI = MF.getFrameInfo();
4720    EVT PtrTy = TLI.getPointerTy();
4721
4722    SDValue Src = getValue(I.getOperand(1));   // The guard's value.
4723    AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4724
4725    int FI = FuncInfo.StaticAllocaMap[Slot];
4726    MFI->setStackProtectorIndex(FI);
4727
4728    SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4729
4730    // Store the stack protector onto the stack.
4731    Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4732                       PseudoSourceValue::getFixedStack(FI),
4733                       0, true);
4734    setValue(&I, Res);
4735    DAG.setRoot(Res);
4736    if (DisableScheduling)
4737      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4738    return 0;
4739  }
4740  case Intrinsic::objectsize: {
4741    // If we don't know by now, we're never going to know.
4742    ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4743
4744    assert(CI && "Non-constant type in __builtin_object_size?");
4745
4746    SDValue Arg = getValue(I.getOperand(0));
4747    EVT Ty = Arg.getValueType();
4748
4749    if (CI->getZExtValue() == 0)
4750      Res = DAG.getConstant(-1ULL, Ty);
4751    else
4752      Res = DAG.getConstant(0, Ty);
4753
4754    setValue(&I, Res);
4755    if (DisableScheduling)
4756      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4757    return 0;
4758  }
4759  case Intrinsic::var_annotation:
4760    // Discard annotate attributes
4761    return 0;
4762
4763  case Intrinsic::init_trampoline: {
4764    const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4765
4766    SDValue Ops[6];
4767    Ops[0] = getRoot();
4768    Ops[1] = getValue(I.getOperand(1));
4769    Ops[2] = getValue(I.getOperand(2));
4770    Ops[3] = getValue(I.getOperand(3));
4771    Ops[4] = DAG.getSrcValue(I.getOperand(1));
4772    Ops[5] = DAG.getSrcValue(F);
4773
4774    Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4775                      DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4776                      Ops, 6);
4777
4778    setValue(&I, Res);
4779    DAG.setRoot(Res.getValue(1));
4780    if (DisableScheduling)
4781      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4782    return 0;
4783  }
4784  case Intrinsic::gcroot:
4785    if (GFI) {
4786      Value *Alloca = I.getOperand(1);
4787      Constant *TypeMap = cast<Constant>(I.getOperand(2));
4788
4789      FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4790      GFI->addStackRoot(FI->getIndex(), TypeMap);
4791    }
4792    return 0;
4793  case Intrinsic::gcread:
4794  case Intrinsic::gcwrite:
4795    llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4796    return 0;
4797  case Intrinsic::flt_rounds:
4798    Res = DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32);
4799    setValue(&I, Res);
4800    if (DisableScheduling)
4801      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4802    return 0;
4803  case Intrinsic::trap:
4804    Res = DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot());
4805    DAG.setRoot(Res);
4806    if (DisableScheduling)
4807      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4808    return 0;
4809  case Intrinsic::uadd_with_overflow:
4810    return implVisitAluOverflow(I, ISD::UADDO);
4811  case Intrinsic::sadd_with_overflow:
4812    return implVisitAluOverflow(I, ISD::SADDO);
4813  case Intrinsic::usub_with_overflow:
4814    return implVisitAluOverflow(I, ISD::USUBO);
4815  case Intrinsic::ssub_with_overflow:
4816    return implVisitAluOverflow(I, ISD::SSUBO);
4817  case Intrinsic::umul_with_overflow:
4818    return implVisitAluOverflow(I, ISD::UMULO);
4819  case Intrinsic::smul_with_overflow:
4820    return implVisitAluOverflow(I, ISD::SMULO);
4821
4822  case Intrinsic::prefetch: {
4823    SDValue Ops[4];
4824    Ops[0] = getRoot();
4825    Ops[1] = getValue(I.getOperand(1));
4826    Ops[2] = getValue(I.getOperand(2));
4827    Ops[3] = getValue(I.getOperand(3));
4828    Res = DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4);
4829    DAG.setRoot(Res);
4830    if (DisableScheduling)
4831      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4832    return 0;
4833  }
4834
4835  case Intrinsic::memory_barrier: {
4836    SDValue Ops[6];
4837    Ops[0] = getRoot();
4838    for (int x = 1; x < 6; ++x)
4839      Ops[x] = getValue(I.getOperand(x));
4840
4841    Res = DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6);
4842    DAG.setRoot(Res);
4843    if (DisableScheduling)
4844      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4845    return 0;
4846  }
4847  case Intrinsic::atomic_cmp_swap: {
4848    SDValue Root = getRoot();
4849    SDValue L =
4850      DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4851                    getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4852                    Root,
4853                    getValue(I.getOperand(1)),
4854                    getValue(I.getOperand(2)),
4855                    getValue(I.getOperand(3)),
4856                    I.getOperand(1));
4857    setValue(&I, L);
4858    DAG.setRoot(L.getValue(1));
4859    if (DisableScheduling)
4860      DAG.AssignOrdering(L.getNode(), SDNodeOrder);
4861    return 0;
4862  }
4863  case Intrinsic::atomic_load_add:
4864    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4865  case Intrinsic::atomic_load_sub:
4866    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4867  case Intrinsic::atomic_load_or:
4868    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4869  case Intrinsic::atomic_load_xor:
4870    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4871  case Intrinsic::atomic_load_and:
4872    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4873  case Intrinsic::atomic_load_nand:
4874    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4875  case Intrinsic::atomic_load_max:
4876    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4877  case Intrinsic::atomic_load_min:
4878    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4879  case Intrinsic::atomic_load_umin:
4880    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4881  case Intrinsic::atomic_load_umax:
4882    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4883  case Intrinsic::atomic_swap:
4884    return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4885
4886  case Intrinsic::invariant_start:
4887  case Intrinsic::lifetime_start:
4888    // Discard region information.
4889    Res = DAG.getUNDEF(TLI.getPointerTy());
4890    setValue(&I, Res);
4891    if (DisableScheduling)
4892      DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
4893    return 0;
4894  case Intrinsic::invariant_end:
4895  case Intrinsic::lifetime_end:
4896    // Discard region information.
4897    return 0;
4898  }
4899}
4900
4901/// Test if the given instruction is in a position to be optimized
4902/// with a tail-call. This roughly means that it's in a block with
4903/// a return and there's nothing that needs to be scheduled
4904/// between it and the return.
4905///
4906/// This function only tests target-independent requirements.
4907/// For target-dependent requirements, a target should override
4908/// TargetLowering::IsEligibleForTailCallOptimization.
4909///
4910static bool
4911isInTailCallPosition(const Instruction *I, Attributes CalleeRetAttr,
4912                     const TargetLowering &TLI) {
4913  const BasicBlock *ExitBB = I->getParent();
4914  const TerminatorInst *Term = ExitBB->getTerminator();
4915  const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4916  const Function *F = ExitBB->getParent();
4917
4918  // The block must end in a return statement or an unreachable.
4919  if (!Ret && !isa<UnreachableInst>(Term)) return false;
4920
4921  // If I will have a chain, make sure no other instruction that will have a
4922  // chain interposes between I and the return.
4923  if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4924      !I->isSafeToSpeculativelyExecute())
4925    for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4926         --BBI) {
4927      if (&*BBI == I)
4928        break;
4929      if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4930          !BBI->isSafeToSpeculativelyExecute())
4931        return false;
4932    }
4933
4934  // If the block ends with a void return or unreachable, it doesn't matter
4935  // what the call's return type is.
4936  if (!Ret || Ret->getNumOperands() == 0) return true;
4937
4938  // If the return value is undef, it doesn't matter what the call's
4939  // return type is.
4940  if (isa<UndefValue>(Ret->getOperand(0))) return true;
4941
4942  // Conservatively require the attributes of the call to match those of
4943  // the return. Ignore noalias because it doesn't affect the call sequence.
4944  unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4945  if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4946    return false;
4947
4948  // Otherwise, make sure the unmodified return value of I is the return value.
4949  for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4950       U = dyn_cast<Instruction>(U->getOperand(0))) {
4951    if (!U)
4952      return false;
4953    if (!U->hasOneUse())
4954      return false;
4955    if (U == I)
4956      break;
4957    // Check for a truly no-op truncate.
4958    if (isa<TruncInst>(U) &&
4959        TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4960      continue;
4961    // Check for a truly no-op bitcast.
4962    if (isa<BitCastInst>(U) &&
4963        (U->getOperand(0)->getType() == U->getType() ||
4964         (isa<PointerType>(U->getOperand(0)->getType()) &&
4965          isa<PointerType>(U->getType()))))
4966      continue;
4967    // Otherwise it's not a true no-op.
4968    return false;
4969  }
4970
4971  return true;
4972}
4973
4974void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4975                                      bool isTailCall,
4976                                      MachineBasicBlock *LandingPad) {
4977  const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4978  const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4979  const Type *RetTy = FTy->getReturnType();
4980  MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4981  unsigned BeginLabel = 0, EndLabel = 0;
4982
4983  TargetLowering::ArgListTy Args;
4984  TargetLowering::ArgListEntry Entry;
4985  Args.reserve(CS.arg_size());
4986
4987  // Check whether the function can return without sret-demotion.
4988  SmallVector<EVT, 4> OutVTs;
4989  SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4990  SmallVector<uint64_t, 4> Offsets;
4991  getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4992                OutVTs, OutsFlags, TLI, &Offsets);
4993
4994  bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4995                        FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4996
4997  SDValue DemoteStackSlot;
4998
4999  if (!CanLowerReturn) {
5000    uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
5001                      FTy->getReturnType());
5002    unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(
5003                      FTy->getReturnType());
5004    MachineFunction &MF = DAG.getMachineFunction();
5005    int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5006    const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
5007
5008    DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5009    Entry.Node = DemoteStackSlot;
5010    Entry.Ty = StackSlotPtrType;
5011    Entry.isSExt = false;
5012    Entry.isZExt = false;
5013    Entry.isInReg = false;
5014    Entry.isSRet = true;
5015    Entry.isNest = false;
5016    Entry.isByVal = false;
5017    Entry.Alignment = Align;
5018    Args.push_back(Entry);
5019    RetTy = Type::getVoidTy(FTy->getContext());
5020  }
5021
5022  for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5023       i != e; ++i) {
5024    SDValue ArgNode = getValue(*i);
5025    Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
5026
5027    unsigned attrInd = i - CS.arg_begin() + 1;
5028    Entry.isSExt  = CS.paramHasAttr(attrInd, Attribute::SExt);
5029    Entry.isZExt  = CS.paramHasAttr(attrInd, Attribute::ZExt);
5030    Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
5031    Entry.isSRet  = CS.paramHasAttr(attrInd, Attribute::StructRet);
5032    Entry.isNest  = CS.paramHasAttr(attrInd, Attribute::Nest);
5033    Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
5034    Entry.Alignment = CS.getParamAlignment(attrInd);
5035    Args.push_back(Entry);
5036  }
5037
5038  if (LandingPad && MMI) {
5039    // Insert a label before the invoke call to mark the try range.  This can be
5040    // used to detect deletion of the invoke via the MachineModuleInfo.
5041    BeginLabel = MMI->NextLabelID();
5042
5043    // Both PendingLoads and PendingExports must be flushed here;
5044    // this call might not return.
5045    (void)getRoot();
5046    DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
5047                             getControlRoot(), BeginLabel));
5048  }
5049
5050  // Check if target-independent constraints permit a tail call here.
5051  // Target-dependent constraints are checked within TLI.LowerCallTo.
5052  if (isTailCall &&
5053      !isInTailCallPosition(CS.getInstruction(),
5054                            CS.getAttributes().getRetAttributes(),
5055                            TLI))
5056    isTailCall = false;
5057
5058  std::pair<SDValue,SDValue> Result =
5059    TLI.LowerCallTo(getRoot(), RetTy,
5060                    CS.paramHasAttr(0, Attribute::SExt),
5061                    CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
5062                    CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
5063                    CS.getCallingConv(),
5064                    isTailCall,
5065                    !CS.getInstruction()->use_empty(),
5066                    Callee, Args, DAG, getCurDebugLoc(), SDNodeOrder);
5067  assert((isTailCall || Result.second.getNode()) &&
5068         "Non-null chain expected with non-tail call!");
5069  assert((Result.second.getNode() || !Result.first.getNode()) &&
5070         "Null value expected with tail call!");
5071  if (Result.first.getNode()) {
5072    setValue(CS.getInstruction(), Result.first);
5073    if (DisableScheduling)
5074      DAG.AssignOrdering(Result.first.getNode(), SDNodeOrder);
5075  } else if (!CanLowerReturn && Result.second.getNode()) {
5076    // The instruction result is the result of loading from the
5077    // hidden sret parameter.
5078    SmallVector<EVT, 1> PVTs;
5079    const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5080
5081    ComputeValueVTs(TLI, PtrRetTy, PVTs);
5082    assert(PVTs.size() == 1 && "Pointers should fit in one register");
5083    EVT PtrVT = PVTs[0];
5084    unsigned NumValues = OutVTs.size();
5085    SmallVector<SDValue, 4> Values(NumValues);
5086    SmallVector<SDValue, 4> Chains(NumValues);
5087
5088    for (unsigned i = 0; i < NumValues; ++i) {
5089      SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5090                                DemoteStackSlot,
5091                                DAG.getConstant(Offsets[i], PtrVT));
5092      SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
5093                              Add, NULL, Offsets[i], false, 1);
5094      Values[i] = L;
5095      Chains[i] = L.getValue(1);
5096    }
5097
5098    SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5099                                MVT::Other, &Chains[0], NumValues);
5100    PendingLoads.push_back(Chain);
5101
5102    SDValue MV = DAG.getNode(ISD::MERGE_VALUES,
5103                             getCurDebugLoc(),
5104                             DAG.getVTList(&OutVTs[0], NumValues),
5105                             &Values[0], NumValues);
5106    setValue(CS.getInstruction(), MV);
5107
5108    if (DisableScheduling) {
5109      DAG.AssignOrdering(Chain.getNode(), SDNodeOrder);
5110      DAG.AssignOrdering(MV.getNode(), SDNodeOrder);
5111    }
5112  }
5113
5114  // As a special case, a null chain means that a tail call has been emitted and
5115  // the DAG root is already updated.
5116  if (Result.second.getNode()) {
5117    DAG.setRoot(Result.second);
5118    if (DisableScheduling)
5119      DAG.AssignOrdering(Result.second.getNode(), SDNodeOrder);
5120  } else {
5121    HasTailCall = true;
5122  }
5123
5124  if (LandingPad && MMI) {
5125    // Insert a label at the end of the invoke call to mark the try range.  This
5126    // can be used to detect deletion of the invoke via the MachineModuleInfo.
5127    EndLabel = MMI->NextLabelID();
5128    DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
5129                             getRoot(), EndLabel));
5130
5131    // Inform MachineModuleInfo of range.
5132    MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
5133  }
5134}
5135
5136/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5137/// value is equal or not-equal to zero.
5138static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
5139  for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
5140       UI != E; ++UI) {
5141    if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5142      if (IC->isEquality())
5143        if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5144          if (C->isNullValue())
5145            continue;
5146    // Unknown instruction.
5147    return false;
5148  }
5149  return true;
5150}
5151
5152static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
5153                             SelectionDAGBuilder &Builder) {
5154
5155  // Check to see if this load can be trivially constant folded, e.g. if the
5156  // input is from a string literal.
5157  if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5158    // Cast pointer to the type we really want to load.
5159    LoadInput = ConstantExpr::getBitCast(LoadInput,
5160                                         PointerType::getUnqual(LoadTy));
5161
5162    if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
5163      return Builder.getValue(LoadCst);
5164  }
5165
5166  // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
5167  // still constant memory, the input chain can be the entry node.
5168  SDValue Root;
5169  bool ConstantMemory = false;
5170
5171  // Do not serialize (non-volatile) loads of constant memory with anything.
5172  if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5173    Root = Builder.DAG.getEntryNode();
5174    ConstantMemory = true;
5175  } else {
5176    // Do not serialize non-volatile loads against each other.
5177    Root = Builder.DAG.getRoot();
5178  }
5179
5180  SDValue Ptr = Builder.getValue(PtrVal);
5181  SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
5182                                        Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
5183                                        false /*volatile*/, 1 /* align=1 */);
5184
5185  if (!ConstantMemory)
5186    Builder.PendingLoads.push_back(LoadVal.getValue(1));
5187  return LoadVal;
5188}
5189
5190
5191/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5192/// If so, return true and lower it, otherwise return false and it will be
5193/// lowered like a normal call.
5194bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
5195  // Verify that the prototype makes sense.  int memcmp(void*,void*,size_t)
5196  if (I.getNumOperands() != 4)
5197    return false;
5198
5199  Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
5200  if (!isa<PointerType>(LHS->getType()) || !isa<PointerType>(RHS->getType()) ||
5201      !isa<IntegerType>(I.getOperand(3)->getType()) ||
5202      !isa<IntegerType>(I.getType()))
5203    return false;
5204
5205  ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
5206
5207  // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
5208  // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
5209  if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5210    bool ActuallyDoIt = true;
5211    MVT LoadVT;
5212    const Type *LoadTy;
5213    switch (Size->getZExtValue()) {
5214    default:
5215      LoadVT = MVT::Other;
5216      LoadTy = 0;
5217      ActuallyDoIt = false;
5218      break;
5219    case 2:
5220      LoadVT = MVT::i16;
5221      LoadTy = Type::getInt16Ty(Size->getContext());
5222      break;
5223    case 4:
5224      LoadVT = MVT::i32;
5225      LoadTy = Type::getInt32Ty(Size->getContext());
5226      break;
5227    case 8:
5228      LoadVT = MVT::i64;
5229      LoadTy = Type::getInt64Ty(Size->getContext());
5230      break;
5231        /*
5232    case 16:
5233      LoadVT = MVT::v4i32;
5234      LoadTy = Type::getInt32Ty(Size->getContext());
5235      LoadTy = VectorType::get(LoadTy, 4);
5236      break;
5237         */
5238    }
5239
5240    // This turns into unaligned loads.  We only do this if the target natively
5241    // supports the MVT we'll be loading or if it is small enough (<= 4) that
5242    // we'll only produce a small number of byte loads.
5243
5244    // Require that we can find a legal MVT, and only do this if the target
5245    // supports unaligned loads of that type.  Expanding into byte loads would
5246    // bloat the code.
5247    if (ActuallyDoIt && Size->getZExtValue() > 4) {
5248      // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5249      // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5250      if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5251        ActuallyDoIt = false;
5252    }
5253
5254    if (ActuallyDoIt) {
5255      SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5256      SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5257
5258      SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5259                                 ISD::SETNE);
5260      EVT CallVT = TLI.getValueType(I.getType(), true);
5261      setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5262      return true;
5263    }
5264  }
5265
5266
5267  return false;
5268}
5269
5270
5271void SelectionDAGBuilder::visitCall(CallInst &I) {
5272  const char *RenameFn = 0;
5273  if (Function *F = I.getCalledFunction()) {
5274    if (F->isDeclaration()) {
5275      const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
5276      if (II) {
5277        if (unsigned IID = II->getIntrinsicID(F)) {
5278          RenameFn = visitIntrinsicCall(I, IID);
5279          if (!RenameFn)
5280            return;
5281        }
5282      }
5283      if (unsigned IID = F->getIntrinsicID()) {
5284        RenameFn = visitIntrinsicCall(I, IID);
5285        if (!RenameFn)
5286          return;
5287      }
5288    }
5289
5290    // Check for well-known libc/libm calls.  If the function is internal, it
5291    // can't be a library call.
5292    if (!F->hasLocalLinkage() && F->hasName()) {
5293      StringRef Name = F->getName();
5294      if (Name == "copysign" || Name == "copysignf") {
5295        if (I.getNumOperands() == 3 &&   // Basic sanity checks.
5296            I.getOperand(1)->getType()->isFloatingPoint() &&
5297            I.getType() == I.getOperand(1)->getType() &&
5298            I.getType() == I.getOperand(2)->getType()) {
5299          SDValue LHS = getValue(I.getOperand(1));
5300          SDValue RHS = getValue(I.getOperand(2));
5301          setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5302                                   LHS.getValueType(), LHS, RHS));
5303          return;
5304        }
5305      } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5306        if (I.getNumOperands() == 2 &&   // Basic sanity checks.
5307            I.getOperand(1)->getType()->isFloatingPoint() &&
5308            I.getType() == I.getOperand(1)->getType()) {
5309          SDValue Tmp = getValue(I.getOperand(1));
5310          setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
5311                                   Tmp.getValueType(), Tmp));
5312          return;
5313        }
5314      } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5315        if (I.getNumOperands() == 2 &&   // Basic sanity checks.
5316            I.getOperand(1)->getType()->isFloatingPoint() &&
5317            I.getType() == I.getOperand(1)->getType() &&
5318            I.onlyReadsMemory()) {
5319          SDValue Tmp = getValue(I.getOperand(1));
5320          setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5321                                   Tmp.getValueType(), Tmp));
5322          return;
5323        }
5324      } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5325        if (I.getNumOperands() == 2 &&   // Basic sanity checks.
5326            I.getOperand(1)->getType()->isFloatingPoint() &&
5327            I.getType() == I.getOperand(1)->getType() &&
5328            I.onlyReadsMemory()) {
5329          SDValue Tmp = getValue(I.getOperand(1));
5330          setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5331                                   Tmp.getValueType(), Tmp));
5332          return;
5333        }
5334      } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5335        if (I.getNumOperands() == 2 &&   // Basic sanity checks.
5336            I.getOperand(1)->getType()->isFloatingPoint() &&
5337            I.getType() == I.getOperand(1)->getType() &&
5338            I.onlyReadsMemory()) {
5339          SDValue Tmp = getValue(I.getOperand(1));
5340          setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5341                                   Tmp.getValueType(), Tmp));
5342          return;
5343        }
5344      } else if (Name == "memcmp") {
5345        if (visitMemCmpCall(I))
5346          return;
5347      }
5348    }
5349  } else if (isa<InlineAsm>(I.getOperand(0))) {
5350    visitInlineAsm(&I);
5351    return;
5352  }
5353
5354  SDValue Callee;
5355  if (!RenameFn)
5356    Callee = getValue(I.getOperand(0));
5357  else
5358    Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5359
5360  // Check if we can potentially perform a tail call. More detailed checking is
5361  // be done within LowerCallTo, after more information about the call is known.
5362  bool isTailCall = PerformTailCallOpt && I.isTailCall();
5363
5364  LowerCallTo(&I, Callee, isTailCall);
5365}
5366
5367/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
5368/// this value and returns the result as a ValueVT value.  This uses
5369/// Chain/Flag as the input and updates them for the output Chain/Flag.
5370/// If the Flag pointer is NULL, no flag is used.
5371SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
5372                                      unsigned Order, SDValue &Chain,
5373                                      SDValue *Flag) const {
5374  // Assemble the legal parts into the final values.
5375  SmallVector<SDValue, 4> Values(ValueVTs.size());
5376  SmallVector<SDValue, 8> Parts;
5377  for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
5378    // Copy the legal parts from the registers.
5379    EVT ValueVT = ValueVTs[Value];
5380    unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
5381    EVT RegisterVT = RegVTs[Value];
5382
5383    Parts.resize(NumRegs);
5384    for (unsigned i = 0; i != NumRegs; ++i) {
5385      SDValue P;
5386      if (Flag == 0) {
5387        P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
5388      } else {
5389        P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
5390        *Flag = P.getValue(2);
5391      }
5392
5393      Chain = P.getValue(1);
5394
5395      if (DisableScheduling)
5396        DAG.AssignOrdering(P.getNode(), Order);
5397
5398      // If the source register was virtual and if we know something about it,
5399      // add an assert node.
5400      if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
5401          RegisterVT.isInteger() && !RegisterVT.isVector()) {
5402        unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
5403        FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5404        if (FLI.LiveOutRegInfo.size() > SlotNo) {
5405          FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
5406
5407          unsigned RegSize = RegisterVT.getSizeInBits();
5408          unsigned NumSignBits = LOI.NumSignBits;
5409          unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
5410
5411          // FIXME: We capture more information than the dag can represent.  For
5412          // now, just use the tightest assertzext/assertsext possible.
5413          bool isSExt = true;
5414          EVT FromVT(MVT::Other);
5415          if (NumSignBits == RegSize)
5416            isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
5417          else if (NumZeroBits >= RegSize-1)
5418            isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
5419          else if (NumSignBits > RegSize-8)
5420            isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
5421          else if (NumZeroBits >= RegSize-8)
5422            isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
5423          else if (NumSignBits > RegSize-16)
5424            isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
5425          else if (NumZeroBits >= RegSize-16)
5426            isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
5427          else if (NumSignBits > RegSize-32)
5428            isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
5429          else if (NumZeroBits >= RegSize-32)
5430            isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
5431
5432          if (FromVT != MVT::Other) {
5433            P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
5434                            RegisterVT, P, DAG.getValueType(FromVT));
5435
5436            if (DisableScheduling)
5437              DAG.AssignOrdering(P.getNode(), Order);
5438          }
5439        }
5440      }
5441
5442      Parts[i] = P;
5443    }
5444
5445    Values[Value] = getCopyFromParts(DAG, dl, Order, Parts.begin(),
5446                                     NumRegs, RegisterVT, ValueVT);
5447    if (DisableScheduling)
5448      DAG.AssignOrdering(Values[Value].getNode(), Order);
5449    Part += NumRegs;
5450    Parts.clear();
5451  }
5452
5453  SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5454                            DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
5455                            &Values[0], ValueVTs.size());
5456  if (DisableScheduling)
5457    DAG.AssignOrdering(Res.getNode(), Order);
5458  return Res;
5459}
5460
5461/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
5462/// specified value into the registers specified by this object.  This uses
5463/// Chain/Flag as the input and updates them for the output Chain/Flag.
5464/// If the Flag pointer is NULL, no flag is used.
5465void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
5466                                 unsigned Order, SDValue &Chain,
5467                                 SDValue *Flag) const {
5468  // Get the list of the values's legal parts.
5469  unsigned NumRegs = Regs.size();
5470  SmallVector<SDValue, 8> Parts(NumRegs);
5471  for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
5472    EVT ValueVT = ValueVTs[Value];
5473    unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
5474    EVT RegisterVT = RegVTs[Value];
5475
5476    getCopyToParts(DAG, dl, Order,
5477                   Val.getValue(Val.getResNo() + Value),
5478                   &Parts[Part], NumParts, RegisterVT);
5479    Part += NumParts;
5480  }
5481
5482  // Copy the parts into the registers.
5483  SmallVector<SDValue, 8> Chains(NumRegs);
5484  for (unsigned i = 0; i != NumRegs; ++i) {
5485    SDValue Part;
5486    if (Flag == 0) {
5487      Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
5488    } else {
5489      Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
5490      *Flag = Part.getValue(1);
5491    }
5492
5493    Chains[i] = Part.getValue(0);
5494
5495    if (DisableScheduling)
5496      DAG.AssignOrdering(Part.getNode(), Order);
5497  }
5498
5499  if (NumRegs == 1 || Flag)
5500    // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
5501    // flagged to it. That is the CopyToReg nodes and the user are considered
5502    // a single scheduling unit. If we create a TokenFactor and return it as
5503    // chain, then the TokenFactor is both a predecessor (operand) of the
5504    // user as well as a successor (the TF operands are flagged to the user).
5505    // c1, f1 = CopyToReg
5506    // c2, f2 = CopyToReg
5507    // c3     = TokenFactor c1, c2
5508    // ...
5509    //        = op c3, ..., f2
5510    Chain = Chains[NumRegs-1];
5511  else
5512    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
5513
5514  if (DisableScheduling)
5515    DAG.AssignOrdering(Chain.getNode(), Order);
5516}
5517
5518/// AddInlineAsmOperands - Add this value to the specified inlineasm node
5519/// operand list.  This adds the code marker and includes the number of
5520/// values added into it.
5521void RegsForValue::AddInlineAsmOperands(unsigned Code,
5522                                        bool HasMatching,unsigned MatchingIdx,
5523                                        SelectionDAG &DAG, unsigned Order,
5524                                        std::vector<SDValue> &Ops) const {
5525  assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
5526  unsigned Flag = Code | (Regs.size() << 3);
5527  if (HasMatching)
5528    Flag |= 0x80000000 | (MatchingIdx << 16);
5529  SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
5530  Ops.push_back(Res);
5531
5532  if (DisableScheduling)
5533    DAG.AssignOrdering(Res.getNode(), Order);
5534
5535  for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
5536    unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
5537    EVT RegisterVT = RegVTs[Value];
5538    for (unsigned i = 0; i != NumRegs; ++i) {
5539      assert(Reg < Regs.size() && "Mismatch in # registers expected");
5540      SDValue Res = DAG.getRegister(Regs[Reg++], RegisterVT);
5541      Ops.push_back(Res);
5542
5543      if (DisableScheduling)
5544        DAG.AssignOrdering(Res.getNode(), Order);
5545    }
5546  }
5547}
5548
5549/// isAllocatableRegister - If the specified register is safe to allocate,
5550/// i.e. it isn't a stack pointer or some other special register, return the
5551/// register class for the register.  Otherwise, return null.
5552static const TargetRegisterClass *
5553isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5554                      const TargetLowering &TLI,
5555                      const TargetRegisterInfo *TRI) {
5556  EVT FoundVT = MVT::Other;
5557  const TargetRegisterClass *FoundRC = 0;
5558  for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5559       E = TRI->regclass_end(); RCI != E; ++RCI) {
5560    EVT ThisVT = MVT::Other;
5561
5562    const TargetRegisterClass *RC = *RCI;
5563    // If none of the the value types for this register class are valid, we
5564    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
5565    for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5566         I != E; ++I) {
5567      if (TLI.isTypeLegal(*I)) {
5568        // If we have already found this register in a different register class,
5569        // choose the one with the largest VT specified.  For example, on
5570        // PowerPC, we favor f64 register classes over f32.
5571        if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5572          ThisVT = *I;
5573          break;
5574        }
5575      }
5576    }
5577
5578    if (ThisVT == MVT::Other) continue;
5579
5580    // NOTE: This isn't ideal.  In particular, this might allocate the
5581    // frame pointer in functions that need it (due to them not being taken
5582    // out of allocation, because a variable sized allocation hasn't been seen
5583    // yet).  This is a slight code pessimization, but should still work.
5584    for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5585         E = RC->allocation_order_end(MF); I != E; ++I)
5586      if (*I == Reg) {
5587        // We found a matching register class.  Keep looking at others in case
5588        // we find one with larger registers that this physreg is also in.
5589        FoundRC = RC;
5590        FoundVT = ThisVT;
5591        break;
5592      }
5593  }
5594  return FoundRC;
5595}
5596
5597
5598namespace llvm {
5599/// AsmOperandInfo - This contains information for each constraint that we are
5600/// lowering.
5601class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
5602    public TargetLowering::AsmOperandInfo {
5603public:
5604  /// CallOperand - If this is the result output operand or a clobber
5605  /// this is null, otherwise it is the incoming operand to the CallInst.
5606  /// This gets modified as the asm is processed.
5607  SDValue CallOperand;
5608
5609  /// AssignedRegs - If this is a register or register class operand, this
5610  /// contains the set of register corresponding to the operand.
5611  RegsForValue AssignedRegs;
5612
5613  explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
5614    : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5615  }
5616
5617  /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5618  /// busy in OutputRegs/InputRegs.
5619  void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5620                         std::set<unsigned> &OutputRegs,
5621                         std::set<unsigned> &InputRegs,
5622                         const TargetRegisterInfo &TRI) const {
5623    if (isOutReg) {
5624      for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5625        MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5626    }
5627    if (isInReg) {
5628      for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5629        MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5630    }
5631  }
5632
5633  /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5634  /// corresponds to.  If there is no Value* for this operand, it returns
5635  /// MVT::Other.
5636  EVT getCallOperandValEVT(LLVMContext &Context,
5637                           const TargetLowering &TLI,
5638                           const TargetData *TD) const {
5639    if (CallOperandVal == 0) return MVT::Other;
5640
5641    if (isa<BasicBlock>(CallOperandVal))
5642      return TLI.getPointerTy();
5643
5644    const llvm::Type *OpTy = CallOperandVal->getType();
5645
5646    // If this is an indirect operand, the operand is a pointer to the
5647    // accessed type.
5648    if (isIndirect) {
5649      const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5650      if (!PtrTy)
5651        llvm_report_error("Indirect operand for inline asm not a pointer!");
5652      OpTy = PtrTy->getElementType();
5653    }
5654
5655    // If OpTy is not a single value, it may be a struct/union that we
5656    // can tile with integers.
5657    if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5658      unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5659      switch (BitSize) {
5660      default: break;
5661      case 1:
5662      case 8:
5663      case 16:
5664      case 32:
5665      case 64:
5666      case 128:
5667        OpTy = IntegerType::get(Context, BitSize);
5668        break;
5669      }
5670    }
5671
5672    return TLI.getValueType(OpTy, true);
5673  }
5674
5675private:
5676  /// MarkRegAndAliases - Mark the specified register and all aliases in the
5677  /// specified set.
5678  static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5679                                const TargetRegisterInfo &TRI) {
5680    assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5681    Regs.insert(Reg);
5682    if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5683      for (; *Aliases; ++Aliases)
5684        Regs.insert(*Aliases);
5685  }
5686};
5687} // end llvm namespace.
5688
5689
5690/// GetRegistersForValue - Assign registers (virtual or physical) for the
5691/// specified operand.  We prefer to assign virtual registers, to allow the
5692/// register allocator to handle the assignment process.  However, if the asm
5693/// uses features that we can't model on machineinstrs, we have SDISel do the
5694/// allocation.  This produces generally horrible, but correct, code.
5695///
5696///   OpInfo describes the operand.
5697///   Input and OutputRegs are the set of already allocated physical registers.
5698///
5699void SelectionDAGBuilder::
5700GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
5701                     std::set<unsigned> &OutputRegs,
5702                     std::set<unsigned> &InputRegs) {
5703  LLVMContext &Context = FuncInfo.Fn->getContext();
5704
5705  // Compute whether this value requires an input register, an output register,
5706  // or both.
5707  bool isOutReg = false;
5708  bool isInReg = false;
5709  switch (OpInfo.Type) {
5710  case InlineAsm::isOutput:
5711    isOutReg = true;
5712
5713    // If there is an input constraint that matches this, we need to reserve
5714    // the input register so no other inputs allocate to it.
5715    isInReg = OpInfo.hasMatchingInput();
5716    break;
5717  case InlineAsm::isInput:
5718    isInReg = true;
5719    isOutReg = false;
5720    break;
5721  case InlineAsm::isClobber:
5722    isOutReg = true;
5723    isInReg = true;
5724    break;
5725  }
5726
5727
5728  MachineFunction &MF = DAG.getMachineFunction();
5729  SmallVector<unsigned, 4> Regs;
5730
5731  // If this is a constraint for a single physreg, or a constraint for a
5732  // register class, find it.
5733  std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5734    TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5735                                     OpInfo.ConstraintVT);
5736
5737  unsigned NumRegs = 1;
5738  if (OpInfo.ConstraintVT != MVT::Other) {
5739    // If this is a FP input in an integer register (or visa versa) insert a bit
5740    // cast of the input value.  More generally, handle any case where the input
5741    // value disagrees with the register class we plan to stick this in.
5742    if (OpInfo.Type == InlineAsm::isInput &&
5743        PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5744      // Try to convert to the first EVT that the reg class contains.  If the
5745      // types are identical size, use a bitcast to convert (e.g. two differing
5746      // vector types).
5747      EVT RegVT = *PhysReg.second->vt_begin();
5748      if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5749        OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5750                                         RegVT, OpInfo.CallOperand);
5751        OpInfo.ConstraintVT = RegVT;
5752      } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5753        // If the input is a FP value and we want it in FP registers, do a
5754        // bitcast to the corresponding integer type.  This turns an f64 value
5755        // into i64, which can be passed with two i32 values on a 32-bit
5756        // machine.
5757        RegVT = EVT::getIntegerVT(Context,
5758                                  OpInfo.ConstraintVT.getSizeInBits());
5759        OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5760                                         RegVT, OpInfo.CallOperand);
5761        OpInfo.ConstraintVT = RegVT;
5762      }
5763
5764      if (DisableScheduling)
5765        DAG.AssignOrdering(OpInfo.CallOperand.getNode(), SDNodeOrder);
5766    }
5767
5768    NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5769  }
5770
5771  EVT RegVT;
5772  EVT ValueVT = OpInfo.ConstraintVT;
5773
5774  // If this is a constraint for a specific physical register, like {r17},
5775  // assign it now.
5776  if (unsigned AssignedReg = PhysReg.first) {
5777    const TargetRegisterClass *RC = PhysReg.second;
5778    if (OpInfo.ConstraintVT == MVT::Other)
5779      ValueVT = *RC->vt_begin();
5780
5781    // Get the actual register value type.  This is important, because the user
5782    // may have asked for (e.g.) the AX register in i32 type.  We need to
5783    // remember that AX is actually i16 to get the right extension.
5784    RegVT = *RC->vt_begin();
5785
5786    // This is a explicit reference to a physical register.
5787    Regs.push_back(AssignedReg);
5788
5789    // If this is an expanded reference, add the rest of the regs to Regs.
5790    if (NumRegs != 1) {
5791      TargetRegisterClass::iterator I = RC->begin();
5792      for (; *I != AssignedReg; ++I)
5793        assert(I != RC->end() && "Didn't find reg!");
5794
5795      // Already added the first reg.
5796      --NumRegs; ++I;
5797      for (; NumRegs; --NumRegs, ++I) {
5798        assert(I != RC->end() && "Ran out of registers to allocate!");
5799        Regs.push_back(*I);
5800      }
5801    }
5802
5803    OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5804    const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5805    OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5806    return;
5807  }
5808
5809  // Otherwise, if this was a reference to an LLVM register class, create vregs
5810  // for this reference.
5811  if (const TargetRegisterClass *RC = PhysReg.second) {
5812    RegVT = *RC->vt_begin();
5813    if (OpInfo.ConstraintVT == MVT::Other)
5814      ValueVT = RegVT;
5815
5816    // Create the appropriate number of virtual registers.
5817    MachineRegisterInfo &RegInfo = MF.getRegInfo();
5818    for (; NumRegs; --NumRegs)
5819      Regs.push_back(RegInfo.createVirtualRegister(RC));
5820
5821    OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5822    return;
5823  }
5824
5825  // This is a reference to a register class that doesn't directly correspond
5826  // to an LLVM register class.  Allocate NumRegs consecutive, available,
5827  // registers from the class.
5828  std::vector<unsigned> RegClassRegs
5829    = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5830                                            OpInfo.ConstraintVT);
5831
5832  const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5833  unsigned NumAllocated = 0;
5834  for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5835    unsigned Reg = RegClassRegs[i];
5836    // See if this register is available.
5837    if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
5838        (isInReg  && InputRegs.count(Reg))) {    // Already used.
5839      // Make sure we find consecutive registers.
5840      NumAllocated = 0;
5841      continue;
5842    }
5843
5844    // Check to see if this register is allocatable (i.e. don't give out the
5845    // stack pointer).
5846    const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5847    if (!RC) {        // Couldn't allocate this register.
5848      // Reset NumAllocated to make sure we return consecutive registers.
5849      NumAllocated = 0;
5850      continue;
5851    }
5852
5853    // Okay, this register is good, we can use it.
5854    ++NumAllocated;
5855
5856    // If we allocated enough consecutive registers, succeed.
5857    if (NumAllocated == NumRegs) {
5858      unsigned RegStart = (i-NumAllocated)+1;
5859      unsigned RegEnd   = i+1;
5860      // Mark all of the allocated registers used.
5861      for (unsigned i = RegStart; i != RegEnd; ++i)
5862        Regs.push_back(RegClassRegs[i]);
5863
5864      OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5865                                         OpInfo.ConstraintVT);
5866      OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5867      return;
5868    }
5869  }
5870
5871  // Otherwise, we couldn't allocate enough registers for this.
5872}
5873
5874/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5875/// processed uses a memory 'm' constraint.
5876static bool
5877hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5878                          const TargetLowering &TLI) {
5879  for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5880    InlineAsm::ConstraintInfo &CI = CInfos[i];
5881    for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5882      TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5883      if (CType == TargetLowering::C_Memory)
5884        return true;
5885    }
5886
5887    // Indirect operand accesses access memory.
5888    if (CI.isIndirect)
5889      return true;
5890  }
5891
5892  return false;
5893}
5894
5895/// visitInlineAsm - Handle a call to an InlineAsm object.
5896///
5897void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
5898  InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5899
5900  /// ConstraintOperands - Information about all of the constraints.
5901  std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5902
5903  std::set<unsigned> OutputRegs, InputRegs;
5904
5905  // Do a prepass over the constraints, canonicalizing them, and building up the
5906  // ConstraintOperands list.
5907  std::vector<InlineAsm::ConstraintInfo>
5908    ConstraintInfos = IA->ParseConstraints();
5909
5910  bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5911
5912  SDValue Chain, Flag;
5913
5914  // We won't need to flush pending loads if this asm doesn't touch
5915  // memory and is nonvolatile.
5916  if (hasMemory || IA->hasSideEffects())
5917    Chain = getRoot();
5918  else
5919    Chain = DAG.getRoot();
5920
5921  unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
5922  unsigned ResNo = 0;   // ResNo - The result number of the next output.
5923  for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5924    ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5925    SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5926
5927    EVT OpVT = MVT::Other;
5928
5929    // Compute the value type for each operand.
5930    switch (OpInfo.Type) {
5931    case InlineAsm::isOutput:
5932      // Indirect outputs just consume an argument.
5933      if (OpInfo.isIndirect) {
5934        OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5935        break;
5936      }
5937
5938      // The return value of the call is this value.  As such, there is no
5939      // corresponding argument.
5940      assert(!CS.getType()->isVoidTy() &&
5941             "Bad inline asm!");
5942      if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5943        OpVT = TLI.getValueType(STy->getElementType(ResNo));
5944      } else {
5945        assert(ResNo == 0 && "Asm only has one result!");
5946        OpVT = TLI.getValueType(CS.getType());
5947      }
5948      ++ResNo;
5949      break;
5950    case InlineAsm::isInput:
5951      OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5952      break;
5953    case InlineAsm::isClobber:
5954      // Nothing to do.
5955      break;
5956    }
5957
5958    // If this is an input or an indirect output, process the call argument.
5959    // BasicBlocks are labels, currently appearing only in asm's.
5960    if (OpInfo.CallOperandVal) {
5961      // Strip bitcasts, if any.  This mostly comes up for functions.
5962      OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5963
5964      if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5965        OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5966      } else {
5967        OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5968      }
5969
5970      OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5971    }
5972
5973    OpInfo.ConstraintVT = OpVT;
5974  }
5975
5976  // Second pass over the constraints: compute which constraint option to use
5977  // and assign registers to constraints that want a specific physreg.
5978  for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5979    SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5980
5981    // If this is an output operand with a matching input operand, look up the
5982    // matching input. If their types mismatch, e.g. one is an integer, the
5983    // other is floating point, or their sizes are different, flag it as an
5984    // error.
5985    if (OpInfo.hasMatchingInput()) {
5986      SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5987      if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5988        if ((OpInfo.ConstraintVT.isInteger() !=
5989             Input.ConstraintVT.isInteger()) ||
5990            (OpInfo.ConstraintVT.getSizeInBits() !=
5991             Input.ConstraintVT.getSizeInBits())) {
5992          llvm_report_error("Unsupported asm: input constraint"
5993                            " with a matching output constraint of incompatible"
5994                            " type!");
5995        }
5996        Input.ConstraintVT = OpInfo.ConstraintVT;
5997      }
5998    }
5999
6000    // Compute the constraint code and ConstraintType to use.
6001    TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
6002
6003    // If this is a memory input, and if the operand is not indirect, do what we
6004    // need to to provide an address for the memory input.
6005    if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6006        !OpInfo.isIndirect) {
6007      assert(OpInfo.Type == InlineAsm::isInput &&
6008             "Can only indirectify direct input operands!");
6009
6010      // Memory operands really want the address of the value.  If we don't have
6011      // an indirect input, put it in the constpool if we can, otherwise spill
6012      // it to a stack slot.
6013
6014      // If the operand is a float, integer, or vector constant, spill to a
6015      // constant pool entry to get its address.
6016      Value *OpVal = OpInfo.CallOperandVal;
6017      if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6018          isa<ConstantVector>(OpVal)) {
6019        OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6020                                                 TLI.getPointerTy());
6021      } else {
6022        // Otherwise, create a stack slot and emit a store to it before the
6023        // asm.
6024        const Type *Ty = OpVal->getType();
6025        uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
6026        unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
6027        MachineFunction &MF = DAG.getMachineFunction();
6028        int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6029        SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
6030        Chain = DAG.getStore(Chain, getCurDebugLoc(),
6031                             OpInfo.CallOperand, StackSlot, NULL, 0);
6032        OpInfo.CallOperand = StackSlot;
6033      }
6034
6035      // There is no longer a Value* corresponding to this operand.
6036      OpInfo.CallOperandVal = 0;
6037
6038      // It is now an indirect operand.
6039      OpInfo.isIndirect = true;
6040    }
6041
6042    // If this constraint is for a specific register, allocate it before
6043    // anything else.
6044    if (OpInfo.ConstraintType == TargetLowering::C_Register)
6045      GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
6046  }
6047
6048  ConstraintInfos.clear();
6049
6050  // Second pass - Loop over all of the operands, assigning virtual or physregs
6051  // to register class operands.
6052  for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6053    SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6054
6055    // C_Register operands have already been allocated, Other/Memory don't need
6056    // to be.
6057    if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6058      GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
6059  }
6060
6061  // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6062  std::vector<SDValue> AsmNodeOperands;
6063  AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
6064  AsmNodeOperands.push_back(
6065          DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6066                                      TLI.getPointerTy()));
6067
6068
6069  // Loop over all of the inputs, copying the operand values into the
6070  // appropriate registers and processing the output regs.
6071  RegsForValue RetValRegs;
6072
6073  // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6074  std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6075
6076  for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6077    SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6078
6079    switch (OpInfo.Type) {
6080    case InlineAsm::isOutput: {
6081      if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6082          OpInfo.ConstraintType != TargetLowering::C_Register) {
6083        // Memory output, or 'other' output (e.g. 'X' constraint).
6084        assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6085
6086        // Add information to the INLINEASM node to know about this output.
6087        unsigned ResOpType = 4/*MEM*/ | (1<<3);
6088        AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6089                                                        TLI.getPointerTy()));
6090        AsmNodeOperands.push_back(OpInfo.CallOperand);
6091        break;
6092      }
6093
6094      // Otherwise, this is a register or register class output.
6095
6096      // Copy the output from the appropriate register.  Find a register that
6097      // we can use.
6098      if (OpInfo.AssignedRegs.Regs.empty()) {
6099        llvm_report_error("Couldn't allocate output reg for"
6100                          " constraint '" + OpInfo.ConstraintCode + "'!");
6101      }
6102
6103      // If this is an indirect operand, store through the pointer after the
6104      // asm.
6105      if (OpInfo.isIndirect) {
6106        IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6107                                                      OpInfo.CallOperandVal));
6108      } else {
6109        // This is the result value of the call.
6110        assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6111        // Concatenate this output onto the outputs list.
6112        RetValRegs.append(OpInfo.AssignedRegs);
6113      }
6114
6115      // Add information to the INLINEASM node to know that this register is
6116      // set.
6117      OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
6118                                               6 /* EARLYCLOBBER REGDEF */ :
6119                                               2 /* REGDEF */ ,
6120                                               false,
6121                                               0,
6122                                               DAG, SDNodeOrder,
6123                                               AsmNodeOperands);
6124      break;
6125    }
6126    case InlineAsm::isInput: {
6127      SDValue InOperandVal = OpInfo.CallOperand;
6128
6129      if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
6130        // If this is required to match an output register we have already set,
6131        // just use its register.
6132        unsigned OperandNo = OpInfo.getMatchedOperand();
6133
6134        // Scan until we find the definition we already emitted of this operand.
6135        // When we find it, create a RegsForValue operand.
6136        unsigned CurOp = 2;  // The first operand.
6137        for (; OperandNo; --OperandNo) {
6138          // Advance to the next operand.
6139          unsigned OpFlag =
6140            cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6141          assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
6142                  (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
6143                  (OpFlag & 7) == 4 /*MEM*/) &&
6144                 "Skipped past definitions?");
6145          CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6146        }
6147
6148        unsigned OpFlag =
6149          cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6150        if ((OpFlag & 7) == 2 /*REGDEF*/
6151            || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
6152          // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6153          if (OpInfo.isIndirect) {
6154            llvm_report_error("Don't know how to handle tied indirect "
6155                              "register inputs yet!");
6156          }
6157          RegsForValue MatchedRegs;
6158          MatchedRegs.TLI = &TLI;
6159          MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6160          EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
6161          MatchedRegs.RegVTs.push_back(RegVT);
6162          MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6163          for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6164               i != e; ++i)
6165            MatchedRegs.Regs.push_back
6166              (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
6167
6168          // Use the produced MatchedRegs object to
6169          MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6170                                    SDNodeOrder, Chain, &Flag);
6171          MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
6172                                           true, OpInfo.getMatchedOperand(),
6173                                           DAG, SDNodeOrder, AsmNodeOperands);
6174          break;
6175        } else {
6176          assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
6177          assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
6178                 "Unexpected number of operands");
6179          // Add information to the INLINEASM node to know about this input.
6180          // See InlineAsm.h isUseOperandTiedToDef.
6181          OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
6182          AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6183                                                          TLI.getPointerTy()));
6184          AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6185          break;
6186        }
6187      }
6188
6189      if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6190        assert(!OpInfo.isIndirect &&
6191               "Don't know how to handle indirect other inputs yet!");
6192
6193        std::vector<SDValue> Ops;
6194        TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
6195                                         hasMemory, Ops, DAG);
6196        if (Ops.empty()) {
6197          llvm_report_error("Invalid operand for inline asm"
6198                            " constraint '" + OpInfo.ConstraintCode + "'!");
6199        }
6200
6201        // Add information to the INLINEASM node to know about this input.
6202        unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
6203        AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6204                                                        TLI.getPointerTy()));
6205        AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6206        break;
6207      } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6208        assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6209        assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6210               "Memory operands expect pointer values");
6211
6212        // Add information to the INLINEASM node to know about this input.
6213        unsigned ResOpType = 4/*MEM*/ | (1<<3);
6214        AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6215                                                        TLI.getPointerTy()));
6216        AsmNodeOperands.push_back(InOperandVal);
6217        break;
6218      }
6219
6220      assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6221              OpInfo.ConstraintType == TargetLowering::C_Register) &&
6222             "Unknown constraint type!");
6223      assert(!OpInfo.isIndirect &&
6224             "Don't know how to handle indirect register inputs yet!");
6225
6226      // Copy the input into the appropriate registers.
6227      if (OpInfo.AssignedRegs.Regs.empty()) {
6228        llvm_report_error("Couldn't allocate input reg for"
6229                          " constraint '"+ OpInfo.ConstraintCode +"'!");
6230      }
6231
6232      OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6233                                        SDNodeOrder, Chain, &Flag);
6234
6235      OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
6236                                               DAG, SDNodeOrder,
6237                                               AsmNodeOperands);
6238      break;
6239    }
6240    case InlineAsm::isClobber: {
6241      // Add the clobbered value to the operand list, so that the register
6242      // allocator is aware that the physreg got clobbered.
6243      if (!OpInfo.AssignedRegs.Regs.empty())
6244        OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
6245                                                 false, 0, DAG, SDNodeOrder,
6246                                                 AsmNodeOperands);
6247      break;
6248    }
6249    }
6250  }
6251
6252  // Finish up input operands.
6253  AsmNodeOperands[0] = Chain;
6254  if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6255
6256  Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
6257                      DAG.getVTList(MVT::Other, MVT::Flag),
6258                      &AsmNodeOperands[0], AsmNodeOperands.size());
6259  Flag = Chain.getValue(1);
6260
6261  // If this asm returns a register value, copy the result from that register
6262  // and set it as the value of the call.
6263  if (!RetValRegs.Regs.empty()) {
6264    SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
6265                                             SDNodeOrder, Chain, &Flag);
6266
6267    // FIXME: Why don't we do this for inline asms with MRVs?
6268    if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6269      EVT ResultType = TLI.getValueType(CS.getType());
6270
6271      // If any of the results of the inline asm is a vector, it may have the
6272      // wrong width/num elts.  This can happen for register classes that can
6273      // contain multiple different value types.  The preg or vreg allocated may
6274      // not have the same VT as was expected.  Convert it to the right type
6275      // with bit_convert.
6276      if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6277        Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
6278                          ResultType, Val);
6279
6280      } else if (ResultType != Val.getValueType() &&
6281                 ResultType.isInteger() && Val.getValueType().isInteger()) {
6282        // If a result value was tied to an input value, the computed result may
6283        // have a wider width than the expected result.  Extract the relevant
6284        // portion.
6285        Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
6286      }
6287
6288      assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6289    }
6290
6291    setValue(CS.getInstruction(), Val);
6292    // Don't need to use this as a chain in this case.
6293    if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6294      return;
6295  }
6296
6297  std::vector<std::pair<SDValue, Value*> > StoresToEmit;
6298
6299  // Process indirect outputs, first output all of the flagged copies out of
6300  // physregs.
6301  for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6302    RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6303    Value *Ptr = IndirectStoresToEmit[i].second;
6304    SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
6305                                             SDNodeOrder, Chain, &Flag);
6306    StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6307
6308  }
6309
6310  // Emit the non-flagged stores from the physregs.
6311  SmallVector<SDValue, 8> OutChains;
6312  for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6313    SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6314                               StoresToEmit[i].first,
6315                               getValue(StoresToEmit[i].second),
6316                               StoresToEmit[i].second, 0);
6317    OutChains.push_back(Val);
6318  }
6319
6320  if (!OutChains.empty())
6321    Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
6322                        &OutChains[0], OutChains.size());
6323
6324  DAG.setRoot(Chain);
6325}
6326
6327void SelectionDAGBuilder::visitVAStart(CallInst &I) {
6328  DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6329                          MVT::Other, getRoot(),
6330                          getValue(I.getOperand(1)),
6331                          DAG.getSrcValue(I.getOperand(1))));
6332}
6333
6334void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
6335  SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6336                           getRoot(), getValue(I.getOperand(0)),
6337                           DAG.getSrcValue(I.getOperand(0)));
6338  setValue(&I, V);
6339  DAG.setRoot(V.getValue(1));
6340}
6341
6342void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
6343  DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6344                          MVT::Other, getRoot(),
6345                          getValue(I.getOperand(1)),
6346                          DAG.getSrcValue(I.getOperand(1))));
6347}
6348
6349void SelectionDAGBuilder::visitVACopy(CallInst &I) {
6350  DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6351                          MVT::Other, getRoot(),
6352                          getValue(I.getOperand(1)),
6353                          getValue(I.getOperand(2)),
6354                          DAG.getSrcValue(I.getOperand(1)),
6355                          DAG.getSrcValue(I.getOperand(2))));
6356}
6357
6358/// TargetLowering::LowerCallTo - This is the default LowerCallTo
6359/// implementation, which just calls LowerCall.
6360/// FIXME: When all targets are
6361/// migrated to using LowerCall, this hook should be integrated into SDISel.
6362std::pair<SDValue, SDValue>
6363TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
6364                            bool RetSExt, bool RetZExt, bool isVarArg,
6365                            bool isInreg, unsigned NumFixedArgs,
6366                            CallingConv::ID CallConv, bool isTailCall,
6367                            bool isReturnValueUsed,
6368                            SDValue Callee,
6369                            ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl,
6370                            unsigned Order) {
6371  assert((!isTailCall || PerformTailCallOpt) &&
6372         "isTailCall set when tail-call optimizations are disabled!");
6373
6374  // Handle all of the outgoing arguments.
6375  SmallVector<ISD::OutputArg, 32> Outs;
6376  for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6377    SmallVector<EVT, 4> ValueVTs;
6378    ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6379    for (unsigned Value = 0, NumValues = ValueVTs.size();
6380         Value != NumValues; ++Value) {
6381      EVT VT = ValueVTs[Value];
6382      const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6383      SDValue Op = SDValue(Args[i].Node.getNode(),
6384                           Args[i].Node.getResNo() + Value);
6385      ISD::ArgFlagsTy Flags;
6386      unsigned OriginalAlignment =
6387        getTargetData()->getABITypeAlignment(ArgTy);
6388
6389      if (Args[i].isZExt)
6390        Flags.setZExt();
6391      if (Args[i].isSExt)
6392        Flags.setSExt();
6393      if (Args[i].isInReg)
6394        Flags.setInReg();
6395      if (Args[i].isSRet)
6396        Flags.setSRet();
6397      if (Args[i].isByVal) {
6398        Flags.setByVal();
6399        const PointerType *Ty = cast<PointerType>(Args[i].Ty);
6400        const Type *ElementTy = Ty->getElementType();
6401        unsigned FrameAlign = getByValTypeAlignment(ElementTy);
6402        unsigned FrameSize  = getTargetData()->getTypeAllocSize(ElementTy);
6403        // For ByVal, alignment should come from FE.  BE will guess if this
6404        // info is not there but there are cases it cannot get right.
6405        if (Args[i].Alignment)
6406          FrameAlign = Args[i].Alignment;
6407        Flags.setByValAlign(FrameAlign);
6408        Flags.setByValSize(FrameSize);
6409      }
6410      if (Args[i].isNest)
6411        Flags.setNest();
6412      Flags.setOrigAlign(OriginalAlignment);
6413
6414      EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6415      unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6416      SmallVector<SDValue, 4> Parts(NumParts);
6417      ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6418
6419      if (Args[i].isSExt)
6420        ExtendKind = ISD::SIGN_EXTEND;
6421      else if (Args[i].isZExt)
6422        ExtendKind = ISD::ZERO_EXTEND;
6423
6424      getCopyToParts(DAG, dl, Order, Op, &Parts[0], NumParts,
6425                     PartVT, ExtendKind);
6426
6427      for (unsigned j = 0; j != NumParts; ++j) {
6428        // if it isn't first piece, alignment must be 1
6429        ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
6430        if (NumParts > 1 && j == 0)
6431          MyFlags.Flags.setSplit();
6432        else if (j != 0)
6433          MyFlags.Flags.setOrigAlign(1);
6434
6435        Outs.push_back(MyFlags);
6436      }
6437    }
6438  }
6439
6440  // Handle the incoming return values from the call.
6441  SmallVector<ISD::InputArg, 32> Ins;
6442  SmallVector<EVT, 4> RetTys;
6443  ComputeValueVTs(*this, RetTy, RetTys);
6444  for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6445    EVT VT = RetTys[I];
6446    EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6447    unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6448    for (unsigned i = 0; i != NumRegs; ++i) {
6449      ISD::InputArg MyFlags;
6450      MyFlags.VT = RegisterVT;
6451      MyFlags.Used = isReturnValueUsed;
6452      if (RetSExt)
6453        MyFlags.Flags.setSExt();
6454      if (RetZExt)
6455        MyFlags.Flags.setZExt();
6456      if (isInreg)
6457        MyFlags.Flags.setInReg();
6458      Ins.push_back(MyFlags);
6459    }
6460  }
6461
6462  // Check if target-dependent constraints permit a tail call here.
6463  // Target-independent constraints should be checked by the caller.
6464  if (isTailCall &&
6465      !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
6466    isTailCall = false;
6467
6468  SmallVector<SDValue, 4> InVals;
6469  Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6470                    Outs, Ins, dl, DAG, InVals);
6471
6472  // Verify that the target's LowerCall behaved as expected.
6473  assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6474         "LowerCall didn't return a valid chain!");
6475  assert((!isTailCall || InVals.empty()) &&
6476         "LowerCall emitted a return value for a tail call!");
6477  assert((isTailCall || InVals.size() == Ins.size()) &&
6478         "LowerCall didn't emit the correct number of values!");
6479  DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6480          assert(InVals[i].getNode() &&
6481                 "LowerCall emitted a null value!");
6482          assert(Ins[i].VT == InVals[i].getValueType() &&
6483                 "LowerCall emitted a value with the wrong type!");
6484        });
6485
6486  if (DisableScheduling)
6487    DAG.AssignOrdering(Chain.getNode(), Order);
6488
6489  // For a tail call, the return value is merely live-out and there aren't
6490  // any nodes in the DAG representing it. Return a special value to
6491  // indicate that a tail call has been emitted and no more Instructions
6492  // should be processed in the current block.
6493  if (isTailCall) {
6494    DAG.setRoot(Chain);
6495    return std::make_pair(SDValue(), SDValue());
6496  }
6497
6498  // Collect the legal value parts into potentially illegal values
6499  // that correspond to the original function's return values.
6500  ISD::NodeType AssertOp = ISD::DELETED_NODE;
6501  if (RetSExt)
6502    AssertOp = ISD::AssertSext;
6503  else if (RetZExt)
6504    AssertOp = ISD::AssertZext;
6505  SmallVector<SDValue, 4> ReturnValues;
6506  unsigned CurReg = 0;
6507  for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6508    EVT VT = RetTys[I];
6509    EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6510    unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6511
6512    SDValue ReturnValue =
6513      getCopyFromParts(DAG, dl, Order, &InVals[CurReg], NumRegs,
6514                       RegisterVT, VT, AssertOp);
6515    ReturnValues.push_back(ReturnValue);
6516    if (DisableScheduling)
6517      DAG.AssignOrdering(ReturnValue.getNode(), Order);
6518    CurReg += NumRegs;
6519  }
6520
6521  // For a function returning void, there is no return value. We can't create
6522  // such a node, so we just return a null return value in that case. In
6523  // that case, nothing will actualy look at the value.
6524  if (ReturnValues.empty())
6525    return std::make_pair(SDValue(), Chain);
6526
6527  SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6528                            DAG.getVTList(&RetTys[0], RetTys.size()),
6529                            &ReturnValues[0], ReturnValues.size());
6530  if (DisableScheduling)
6531    DAG.AssignOrdering(Res.getNode(), Order);
6532  return std::make_pair(Res, Chain);
6533}
6534
6535void TargetLowering::LowerOperationWrapper(SDNode *N,
6536                                           SmallVectorImpl<SDValue> &Results,
6537                                           SelectionDAG &DAG) {
6538  SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6539  if (Res.getNode())
6540    Results.push_back(Res);
6541}
6542
6543SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6544  llvm_unreachable("LowerOperation not implemented for this target!");
6545  return SDValue();
6546}
6547
6548void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
6549  SDValue Op = getValue(V);
6550  assert((Op.getOpcode() != ISD::CopyFromReg ||
6551          cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6552         "Copy from a reg to the same reg!");
6553  assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6554
6555  RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6556  SDValue Chain = DAG.getEntryNode();
6557  RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0);
6558  PendingExports.push_back(Chain);
6559}
6560
6561#include "llvm/CodeGen/SelectionDAGISel.h"
6562
6563void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
6564  // If this is the entry block, emit arguments.
6565  Function &F = *LLVMBB->getParent();
6566  SelectionDAG &DAG = SDB->DAG;
6567  SDValue OldRoot = DAG.getRoot();
6568  DebugLoc dl = SDB->getCurDebugLoc();
6569  const TargetData *TD = TLI.getTargetData();
6570  SmallVector<ISD::InputArg, 16> Ins;
6571
6572  // Check whether the function can return without sret-demotion.
6573  SmallVector<EVT, 4> OutVTs;
6574  SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
6575  getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6576                OutVTs, OutsFlags, TLI);
6577  FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
6578
6579  FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
6580                                          OutVTs, OutsFlags, DAG);
6581  if (!FLI.CanLowerReturn) {
6582    // Put in an sret pointer parameter before all the other parameters.
6583    SmallVector<EVT, 1> ValueVTs;
6584    ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6585
6586    // NOTE: Assuming that a pointer will never break down to more than one VT
6587    // or one register.
6588    ISD::ArgFlagsTy Flags;
6589    Flags.setSRet();
6590    EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
6591    ISD::InputArg RetArg(Flags, RegisterVT, true);
6592    Ins.push_back(RetArg);
6593  }
6594
6595  // Set up the incoming argument description vector.
6596  unsigned Idx = 1;
6597  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
6598       I != E; ++I, ++Idx) {
6599    SmallVector<EVT, 4> ValueVTs;
6600    ComputeValueVTs(TLI, I->getType(), ValueVTs);
6601    bool isArgValueUsed = !I->use_empty();
6602    for (unsigned Value = 0, NumValues = ValueVTs.size();
6603         Value != NumValues; ++Value) {
6604      EVT VT = ValueVTs[Value];
6605      const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6606      ISD::ArgFlagsTy Flags;
6607      unsigned OriginalAlignment =
6608        TD->getABITypeAlignment(ArgTy);
6609
6610      if (F.paramHasAttr(Idx, Attribute::ZExt))
6611        Flags.setZExt();
6612      if (F.paramHasAttr(Idx, Attribute::SExt))
6613        Flags.setSExt();
6614      if (F.paramHasAttr(Idx, Attribute::InReg))
6615        Flags.setInReg();
6616      if (F.paramHasAttr(Idx, Attribute::StructRet))
6617        Flags.setSRet();
6618      if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6619        Flags.setByVal();
6620        const PointerType *Ty = cast<PointerType>(I->getType());
6621        const Type *ElementTy = Ty->getElementType();
6622        unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6623        unsigned FrameSize  = TD->getTypeAllocSize(ElementTy);
6624        // For ByVal, alignment should be passed from FE.  BE will guess if
6625        // this info is not there but there are cases it cannot get right.
6626        if (F.getParamAlignment(Idx))
6627          FrameAlign = F.getParamAlignment(Idx);
6628        Flags.setByValAlign(FrameAlign);
6629        Flags.setByValSize(FrameSize);
6630      }
6631      if (F.paramHasAttr(Idx, Attribute::Nest))
6632        Flags.setNest();
6633      Flags.setOrigAlign(OriginalAlignment);
6634
6635      EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6636      unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6637      for (unsigned i = 0; i != NumRegs; ++i) {
6638        ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6639        if (NumRegs > 1 && i == 0)
6640          MyFlags.Flags.setSplit();
6641        // if it isn't first piece, alignment must be 1
6642        else if (i > 0)
6643          MyFlags.Flags.setOrigAlign(1);
6644        Ins.push_back(MyFlags);
6645      }
6646    }
6647  }
6648
6649  // Call the target to set up the argument values.
6650  SmallVector<SDValue, 8> InVals;
6651  SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6652                                             F.isVarArg(), Ins,
6653                                             dl, DAG, InVals);
6654
6655  // Verify that the target's LowerFormalArguments behaved as expected.
6656  assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6657         "LowerFormalArguments didn't return a valid chain!");
6658  assert(InVals.size() == Ins.size() &&
6659         "LowerFormalArguments didn't emit the correct number of values!");
6660  DEBUG({
6661      for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6662        assert(InVals[i].getNode() &&
6663               "LowerFormalArguments emitted a null value!");
6664        assert(Ins[i].VT == InVals[i].getValueType() &&
6665               "LowerFormalArguments emitted a value with the wrong type!");
6666      }
6667    });
6668
6669  // Update the DAG with the new chain value resulting from argument lowering.
6670  DAG.setRoot(NewRoot);
6671
6672  // Set up the argument values.
6673  unsigned i = 0;
6674  Idx = 1;
6675  if (!FLI.CanLowerReturn) {
6676    // Create a virtual register for the sret pointer, and put in a copy
6677    // from the sret argument into it.
6678    SmallVector<EVT, 1> ValueVTs;
6679    ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6680    EVT VT = ValueVTs[0];
6681    EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6682    ISD::NodeType AssertOp = ISD::DELETED_NODE;
6683    SDValue ArgValue = getCopyFromParts(DAG, dl, 0, &InVals[0], 1,
6684                                        RegVT, VT, AssertOp);
6685
6686    MachineFunction& MF = SDB->DAG.getMachineFunction();
6687    MachineRegisterInfo& RegInfo = MF.getRegInfo();
6688    unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6689    FLI.DemoteRegister = SRetReg;
6690    NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6691                                    SRetReg, ArgValue);
6692    DAG.setRoot(NewRoot);
6693
6694    // i indexes lowered arguments.  Bump it past the hidden sret argument.
6695    // Idx indexes LLVM arguments.  Don't touch it.
6696    ++i;
6697  }
6698
6699  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6700      ++I, ++Idx) {
6701    SmallVector<SDValue, 4> ArgValues;
6702    SmallVector<EVT, 4> ValueVTs;
6703    ComputeValueVTs(TLI, I->getType(), ValueVTs);
6704    unsigned NumValues = ValueVTs.size();
6705    for (unsigned Value = 0; Value != NumValues; ++Value) {
6706      EVT VT = ValueVTs[Value];
6707      EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6708      unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6709
6710      if (!I->use_empty()) {
6711        ISD::NodeType AssertOp = ISD::DELETED_NODE;
6712        if (F.paramHasAttr(Idx, Attribute::SExt))
6713          AssertOp = ISD::AssertSext;
6714        else if (F.paramHasAttr(Idx, Attribute::ZExt))
6715          AssertOp = ISD::AssertZext;
6716
6717        ArgValues.push_back(getCopyFromParts(DAG, dl, 0, &InVals[i],
6718                                             NumParts, PartVT, VT,
6719                                             AssertOp));
6720      }
6721
6722      i += NumParts;
6723    }
6724
6725    if (!I->use_empty()) {
6726      SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6727                                       SDB->getCurDebugLoc());
6728      SDB->setValue(I, Res);
6729
6730      // If this argument is live outside of the entry block, insert a copy from
6731      // whereever we got it to the vreg that other BB's will reference it as.
6732      SDB->CopyToExportRegsIfNeeded(I);
6733    }
6734  }
6735
6736  assert(i == InVals.size() && "Argument register count mismatch!");
6737
6738  // Finally, if the target has anything special to do, allow it to do so.
6739  // FIXME: this should insert code into the DAG!
6740  EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
6741}
6742
6743/// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
6744/// ensure constants are generated when needed.  Remember the virtual registers
6745/// that need to be added to the Machine PHI nodes as input.  We cannot just
6746/// directly add them, because expansion might result in multiple MBB's for one
6747/// BB.  As such, the start of the BB might correspond to a different MBB than
6748/// the end.
6749///
6750void
6751SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6752  TerminatorInst *TI = LLVMBB->getTerminator();
6753
6754  SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6755
6756  // Check successor nodes' PHI nodes that expect a constant to be available
6757  // from this block.
6758  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6759    BasicBlock *SuccBB = TI->getSuccessor(succ);
6760    if (!isa<PHINode>(SuccBB->begin())) continue;
6761    MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6762
6763    // If this terminator has multiple identical successors (common for
6764    // switches), only handle each succ once.
6765    if (!SuccsHandled.insert(SuccMBB)) continue;
6766
6767    MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6768    PHINode *PN;
6769
6770    // At this point we know that there is a 1-1 correspondence between LLVM PHI
6771    // nodes and Machine PHI nodes, but the incoming operands have not been
6772    // emitted yet.
6773    for (BasicBlock::iterator I = SuccBB->begin();
6774         (PN = dyn_cast<PHINode>(I)); ++I) {
6775      // Ignore dead phi's.
6776      if (PN->use_empty()) continue;
6777
6778      unsigned Reg;
6779      Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6780
6781      if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6782        unsigned &RegOut = SDB->ConstantsOut[C];
6783        if (RegOut == 0) {
6784          RegOut = FuncInfo->CreateRegForValue(C);
6785          SDB->CopyValueToVirtualRegister(C, RegOut);
6786        }
6787        Reg = RegOut;
6788      } else {
6789        Reg = FuncInfo->ValueMap[PHIOp];
6790        if (Reg == 0) {
6791          assert(isa<AllocaInst>(PHIOp) &&
6792                 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6793                 "Didn't codegen value into a register!??");
6794          Reg = FuncInfo->CreateRegForValue(PHIOp);
6795          SDB->CopyValueToVirtualRegister(PHIOp, Reg);
6796        }
6797      }
6798
6799      // Remember that this register needs to added to the machine PHI node as
6800      // the input for this MBB.
6801      SmallVector<EVT, 4> ValueVTs;
6802      ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6803      for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6804        EVT VT = ValueVTs[vti];
6805        unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6806        for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6807          SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6808        Reg += NumRegisters;
6809      }
6810    }
6811  }
6812  SDB->ConstantsOut.clear();
6813}
6814
6815/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6816/// supports legal types, and it emits MachineInstrs directly instead of
6817/// creating SelectionDAG nodes.
6818///
6819bool
6820SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6821                                                      FastISel *F) {
6822  TerminatorInst *TI = LLVMBB->getTerminator();
6823
6824  SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6825  unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
6826
6827  // Check successor nodes' PHI nodes that expect a constant to be available
6828  // from this block.
6829  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6830    BasicBlock *SuccBB = TI->getSuccessor(succ);
6831    if (!isa<PHINode>(SuccBB->begin())) continue;
6832    MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6833
6834    // If this terminator has multiple identical successors (common for
6835    // switches), only handle each succ once.
6836    if (!SuccsHandled.insert(SuccMBB)) continue;
6837
6838    MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6839    PHINode *PN;
6840
6841    // At this point we know that there is a 1-1 correspondence between LLVM PHI
6842    // nodes and Machine PHI nodes, but the incoming operands have not been
6843    // emitted yet.
6844    for (BasicBlock::iterator I = SuccBB->begin();
6845         (PN = dyn_cast<PHINode>(I)); ++I) {
6846      // Ignore dead phi's.
6847      if (PN->use_empty()) continue;
6848
6849      // Only handle legal types. Two interesting things to note here. First,
6850      // by bailing out early, we may leave behind some dead instructions,
6851      // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6852      // own moves. Second, this check is necessary becuase FastISel doesn't
6853      // use CreateRegForValue to create registers, so it always creates
6854      // exactly one register for each non-void instruction.
6855      EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6856      if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6857        // Promote MVT::i1.
6858        if (VT == MVT::i1)
6859          VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6860        else {
6861          SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6862          return false;
6863        }
6864      }
6865
6866      Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6867
6868      unsigned Reg = F->getRegForValue(PHIOp);
6869      if (Reg == 0) {
6870        SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6871        return false;
6872      }
6873      SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6874    }
6875  }
6876
6877  return true;
6878}
6879