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