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