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