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