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