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