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