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