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