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