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