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