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