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