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