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