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