xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision df9ae70f49a506cddf6bbfdb472b0913567d8010)
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   case Intrinsic::experimental_deoptimize:
5465     LowerDeoptimizeCall(&I);
5466     return nullptr;
5467   }
5468 }
5469 
5470 std::pair<SDValue, SDValue>
5471 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5472                                     const BasicBlock *EHPadBB) {
5473   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5474   MCSymbol *BeginLabel = nullptr;
5475 
5476   if (EHPadBB) {
5477     // Insert a label before the invoke call to mark the try range.  This can be
5478     // used to detect deletion of the invoke via the MachineModuleInfo.
5479     BeginLabel = MMI.getContext().createTempSymbol();
5480 
5481     // For SjLj, keep track of which landing pads go with which invokes
5482     // so as to maintain the ordering of pads in the LSDA.
5483     unsigned CallSiteIndex = MMI.getCurrentCallSite();
5484     if (CallSiteIndex) {
5485       MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5486       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
5487 
5488       // Now that the call site is handled, stop tracking it.
5489       MMI.setCurrentCallSite(0);
5490     }
5491 
5492     // Both PendingLoads and PendingExports must be flushed here;
5493     // this call might not return.
5494     (void)getRoot();
5495     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5496 
5497     CLI.setChain(getRoot());
5498   }
5499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5500   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5501 
5502   assert((CLI.IsTailCall || Result.second.getNode()) &&
5503          "Non-null chain expected with non-tail call!");
5504   assert((Result.second.getNode() || !Result.first.getNode()) &&
5505          "Null value expected with tail call!");
5506 
5507   if (!Result.second.getNode()) {
5508     // As a special case, a null chain means that a tail call has been emitted
5509     // and the DAG root is already updated.
5510     HasTailCall = true;
5511 
5512     // Since there's no actual continuation from this block, nothing can be
5513     // relying on us setting vregs for them.
5514     PendingExports.clear();
5515   } else {
5516     DAG.setRoot(Result.second);
5517   }
5518 
5519   if (EHPadBB) {
5520     // Insert a label at the end of the invoke call to mark the try range.  This
5521     // can be used to detect deletion of the invoke via the MachineModuleInfo.
5522     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
5523     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5524 
5525     // Inform MachineModuleInfo of range.
5526     if (MMI.hasEHFunclets()) {
5527       assert(CLI.CS);
5528       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
5529       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS->getInstruction()),
5530                                 BeginLabel, EndLabel);
5531     } else {
5532       MMI.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
5533     }
5534   }
5535 
5536   return Result;
5537 }
5538 
5539 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5540                                       bool isTailCall,
5541                                       const BasicBlock *EHPadBB) {
5542   FunctionType *FTy = CS.getFunctionType();
5543   Type *RetTy = CS.getType();
5544 
5545   TargetLowering::ArgListTy Args;
5546   TargetLowering::ArgListEntry Entry;
5547   Args.reserve(CS.arg_size());
5548 
5549   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5550        i != e; ++i) {
5551     const Value *V = *i;
5552 
5553     // Skip empty types
5554     if (V->getType()->isEmptyTy())
5555       continue;
5556 
5557     SDValue ArgNode = getValue(V);
5558     Entry.Node = ArgNode; Entry.Ty = V->getType();
5559 
5560     // Skip the first return-type Attribute to get to params.
5561     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5562     Args.push_back(Entry);
5563 
5564     // If we have an explicit sret argument that is an Instruction, (i.e., it
5565     // might point to function-local memory), we can't meaningfully tail-call.
5566     if (Entry.isSRet && isa<Instruction>(V))
5567       isTailCall = false;
5568   }
5569 
5570   // Check if target-independent constraints permit a tail call here.
5571   // Target-dependent constraints are checked within TLI->LowerCallTo.
5572   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5573     isTailCall = false;
5574 
5575   TargetLowering::CallLoweringInfo CLI(DAG);
5576   CLI.setDebugLoc(getCurSDLoc())
5577       .setChain(getRoot())
5578       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5579       .setTailCall(isTailCall)
5580       .setConvergent(CS.isConvergent());
5581   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
5582 
5583   if (Result.first.getNode()) {
5584     const Instruction *Inst = CS.getInstruction();
5585     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
5586     setValue(Inst, Result.first);
5587   }
5588 }
5589 
5590 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5591 /// value is equal or not-equal to zero.
5592 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5593   for (const User *U : V->users()) {
5594     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5595       if (IC->isEquality())
5596         if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5597           if (C->isNullValue())
5598             continue;
5599     // Unknown instruction.
5600     return false;
5601   }
5602   return true;
5603 }
5604 
5605 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5606                              Type *LoadTy,
5607                              SelectionDAGBuilder &Builder) {
5608 
5609   // Check to see if this load can be trivially constant folded, e.g. if the
5610   // input is from a string literal.
5611   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5612     // Cast pointer to the type we really want to load.
5613     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5614                                          PointerType::getUnqual(LoadTy));
5615 
5616     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5617             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
5618       return Builder.getValue(LoadCst);
5619   }
5620 
5621   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
5622   // still constant memory, the input chain can be the entry node.
5623   SDValue Root;
5624   bool ConstantMemory = false;
5625 
5626   // Do not serialize (non-volatile) loads of constant memory with anything.
5627   if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5628     Root = Builder.DAG.getEntryNode();
5629     ConstantMemory = true;
5630   } else {
5631     // Do not serialize non-volatile loads against each other.
5632     Root = Builder.DAG.getRoot();
5633   }
5634 
5635   SDValue Ptr = Builder.getValue(PtrVal);
5636   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5637                                         Ptr, MachinePointerInfo(PtrVal),
5638                                         false /*volatile*/,
5639                                         false /*nontemporal*/,
5640                                         false /*isinvariant*/, 1 /* align=1 */);
5641 
5642   if (!ConstantMemory)
5643     Builder.PendingLoads.push_back(LoadVal.getValue(1));
5644   return LoadVal;
5645 }
5646 
5647 /// processIntegerCallValue - Record the value for an instruction that
5648 /// produces an integer result, converting the type where necessary.
5649 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5650                                                   SDValue Value,
5651                                                   bool IsSigned) {
5652   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5653                                                     I.getType(), true);
5654   if (IsSigned)
5655     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5656   else
5657     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5658   setValue(&I, Value);
5659 }
5660 
5661 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5662 /// If so, return true and lower it, otherwise return false and it will be
5663 /// lowered like a normal call.
5664 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5665   // Verify that the prototype makes sense.  int memcmp(void*,void*,size_t)
5666   if (I.getNumArgOperands() != 3)
5667     return false;
5668 
5669   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5670   if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5671       !I.getArgOperand(2)->getType()->isIntegerTy() ||
5672       !I.getType()->isIntegerTy())
5673     return false;
5674 
5675   const Value *Size = I.getArgOperand(2);
5676   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5677   if (CSize && CSize->getZExtValue() == 0) {
5678     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5679                                                           I.getType(), true);
5680     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
5681     return true;
5682   }
5683 
5684   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5685   std::pair<SDValue, SDValue> Res =
5686     TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5687                                 getValue(LHS), getValue(RHS), getValue(Size),
5688                                 MachinePointerInfo(LHS),
5689                                 MachinePointerInfo(RHS));
5690   if (Res.first.getNode()) {
5691     processIntegerCallValue(I, Res.first, true);
5692     PendingLoads.push_back(Res.second);
5693     return true;
5694   }
5695 
5696   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
5697   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
5698   if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5699     bool ActuallyDoIt = true;
5700     MVT LoadVT;
5701     Type *LoadTy;
5702     switch (CSize->getZExtValue()) {
5703     default:
5704       LoadVT = MVT::Other;
5705       LoadTy = nullptr;
5706       ActuallyDoIt = false;
5707       break;
5708     case 2:
5709       LoadVT = MVT::i16;
5710       LoadTy = Type::getInt16Ty(CSize->getContext());
5711       break;
5712     case 4:
5713       LoadVT = MVT::i32;
5714       LoadTy = Type::getInt32Ty(CSize->getContext());
5715       break;
5716     case 8:
5717       LoadVT = MVT::i64;
5718       LoadTy = Type::getInt64Ty(CSize->getContext());
5719       break;
5720         /*
5721     case 16:
5722       LoadVT = MVT::v4i32;
5723       LoadTy = Type::getInt32Ty(CSize->getContext());
5724       LoadTy = VectorType::get(LoadTy, 4);
5725       break;
5726          */
5727     }
5728 
5729     // This turns into unaligned loads.  We only do this if the target natively
5730     // supports the MVT we'll be loading or if it is small enough (<= 4) that
5731     // we'll only produce a small number of byte loads.
5732 
5733     // Require that we can find a legal MVT, and only do this if the target
5734     // supports unaligned loads of that type.  Expanding into byte loads would
5735     // bloat the code.
5736     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5737     if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5738       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5739       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5740       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5741       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5742       // TODO: Check alignment of src and dest ptrs.
5743       if (!TLI.isTypeLegal(LoadVT) ||
5744           !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5745           !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5746         ActuallyDoIt = false;
5747     }
5748 
5749     if (ActuallyDoIt) {
5750       SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5751       SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5752 
5753       SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5754                                  ISD::SETNE);
5755       processIntegerCallValue(I, Res, false);
5756       return true;
5757     }
5758   }
5759 
5760 
5761   return false;
5762 }
5763 
5764 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5765 /// form.  If so, return true and lower it, otherwise return false and it
5766 /// will be lowered like a normal call.
5767 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5768   // Verify that the prototype makes sense.  void *memchr(void *, int, size_t)
5769   if (I.getNumArgOperands() != 3)
5770     return false;
5771 
5772   const Value *Src = I.getArgOperand(0);
5773   const Value *Char = I.getArgOperand(1);
5774   const Value *Length = I.getArgOperand(2);
5775   if (!Src->getType()->isPointerTy() ||
5776       !Char->getType()->isIntegerTy() ||
5777       !Length->getType()->isIntegerTy() ||
5778       !I.getType()->isPointerTy())
5779     return false;
5780 
5781   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5782   std::pair<SDValue, SDValue> Res =
5783     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5784                                 getValue(Src), getValue(Char), getValue(Length),
5785                                 MachinePointerInfo(Src));
5786   if (Res.first.getNode()) {
5787     setValue(&I, Res.first);
5788     PendingLoads.push_back(Res.second);
5789     return true;
5790   }
5791 
5792   return false;
5793 }
5794 
5795 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5796 /// optimized form.  If so, return true and lower it, otherwise return false
5797 /// and it will be lowered like a normal call.
5798 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5799   // Verify that the prototype makes sense.  char *strcpy(char *, char *)
5800   if (I.getNumArgOperands() != 2)
5801     return false;
5802 
5803   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5804   if (!Arg0->getType()->isPointerTy() ||
5805       !Arg1->getType()->isPointerTy() ||
5806       !I.getType()->isPointerTy())
5807     return false;
5808 
5809   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5810   std::pair<SDValue, SDValue> Res =
5811     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5812                                 getValue(Arg0), getValue(Arg1),
5813                                 MachinePointerInfo(Arg0),
5814                                 MachinePointerInfo(Arg1), isStpcpy);
5815   if (Res.first.getNode()) {
5816     setValue(&I, Res.first);
5817     DAG.setRoot(Res.second);
5818     return true;
5819   }
5820 
5821   return false;
5822 }
5823 
5824 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5825 /// If so, return true and lower it, otherwise return false and it will be
5826 /// lowered like a normal call.
5827 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5828   // Verify that the prototype makes sense.  int strcmp(void*,void*)
5829   if (I.getNumArgOperands() != 2)
5830     return false;
5831 
5832   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5833   if (!Arg0->getType()->isPointerTy() ||
5834       !Arg1->getType()->isPointerTy() ||
5835       !I.getType()->isIntegerTy())
5836     return false;
5837 
5838   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5839   std::pair<SDValue, SDValue> Res =
5840     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5841                                 getValue(Arg0), getValue(Arg1),
5842                                 MachinePointerInfo(Arg0),
5843                                 MachinePointerInfo(Arg1));
5844   if (Res.first.getNode()) {
5845     processIntegerCallValue(I, Res.first, true);
5846     PendingLoads.push_back(Res.second);
5847     return true;
5848   }
5849 
5850   return false;
5851 }
5852 
5853 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5854 /// form.  If so, return true and lower it, otherwise return false and it
5855 /// will be lowered like a normal call.
5856 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5857   // Verify that the prototype makes sense.  size_t strlen(char *)
5858   if (I.getNumArgOperands() != 1)
5859     return false;
5860 
5861   const Value *Arg0 = I.getArgOperand(0);
5862   if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5863     return false;
5864 
5865   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5866   std::pair<SDValue, SDValue> Res =
5867     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5868                                 getValue(Arg0), MachinePointerInfo(Arg0));
5869   if (Res.first.getNode()) {
5870     processIntegerCallValue(I, Res.first, false);
5871     PendingLoads.push_back(Res.second);
5872     return true;
5873   }
5874 
5875   return false;
5876 }
5877 
5878 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5879 /// form.  If so, return true and lower it, otherwise return false and it
5880 /// will be lowered like a normal call.
5881 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5882   // Verify that the prototype makes sense.  size_t strnlen(char *, size_t)
5883   if (I.getNumArgOperands() != 2)
5884     return false;
5885 
5886   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5887   if (!Arg0->getType()->isPointerTy() ||
5888       !Arg1->getType()->isIntegerTy() ||
5889       !I.getType()->isIntegerTy())
5890     return false;
5891 
5892   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
5893   std::pair<SDValue, SDValue> Res =
5894     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5895                                  getValue(Arg0), getValue(Arg1),
5896                                  MachinePointerInfo(Arg0));
5897   if (Res.first.getNode()) {
5898     processIntegerCallValue(I, Res.first, false);
5899     PendingLoads.push_back(Res.second);
5900     return true;
5901   }
5902 
5903   return false;
5904 }
5905 
5906 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5907 /// operation (as expected), translate it to an SDNode with the specified opcode
5908 /// and return true.
5909 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5910                                               unsigned Opcode) {
5911   // Sanity check that it really is a unary floating-point call.
5912   if (I.getNumArgOperands() != 1 ||
5913       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5914       I.getType() != I.getArgOperand(0)->getType() ||
5915       !I.onlyReadsMemory())
5916     return false;
5917 
5918   SDValue Tmp = getValue(I.getArgOperand(0));
5919   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5920   return true;
5921 }
5922 
5923 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
5924 /// operation (as expected), translate it to an SDNode with the specified opcode
5925 /// and return true.
5926 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5927                                                unsigned Opcode) {
5928   // Sanity check that it really is a binary floating-point call.
5929   if (I.getNumArgOperands() != 2 ||
5930       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5931       I.getType() != I.getArgOperand(0)->getType() ||
5932       I.getType() != I.getArgOperand(1)->getType() ||
5933       !I.onlyReadsMemory())
5934     return false;
5935 
5936   SDValue Tmp0 = getValue(I.getArgOperand(0));
5937   SDValue Tmp1 = getValue(I.getArgOperand(1));
5938   EVT VT = Tmp0.getValueType();
5939   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5940   return true;
5941 }
5942 
5943 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5944   // Handle inline assembly differently.
5945   if (isa<InlineAsm>(I.getCalledValue())) {
5946     visitInlineAsm(&I);
5947     return;
5948   }
5949 
5950   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5951   ComputeUsesVAFloatArgument(I, &MMI);
5952 
5953   const char *RenameFn = nullptr;
5954   if (Function *F = I.getCalledFunction()) {
5955     if (F->isDeclaration()) {
5956       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5957         if (unsigned IID = II->getIntrinsicID(F)) {
5958           RenameFn = visitIntrinsicCall(I, IID);
5959           if (!RenameFn)
5960             return;
5961         }
5962       }
5963       if (Intrinsic::ID IID = F->getIntrinsicID()) {
5964         RenameFn = visitIntrinsicCall(I, IID);
5965         if (!RenameFn)
5966           return;
5967       }
5968     }
5969 
5970     // Check for well-known libc/libm calls.  If the function is internal, it
5971     // can't be a library call.
5972     LibFunc::Func Func;
5973     if (!F->hasLocalLinkage() && F->hasName() &&
5974         LibInfo->getLibFunc(F->getName(), Func) &&
5975         LibInfo->hasOptimizedCodeGen(Func)) {
5976       switch (Func) {
5977       default: break;
5978       case LibFunc::copysign:
5979       case LibFunc::copysignf:
5980       case LibFunc::copysignl:
5981         if (I.getNumArgOperands() == 2 &&   // Basic sanity checks.
5982             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5983             I.getType() == I.getArgOperand(0)->getType() &&
5984             I.getType() == I.getArgOperand(1)->getType() &&
5985             I.onlyReadsMemory()) {
5986           SDValue LHS = getValue(I.getArgOperand(0));
5987           SDValue RHS = getValue(I.getArgOperand(1));
5988           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5989                                    LHS.getValueType(), LHS, RHS));
5990           return;
5991         }
5992         break;
5993       case LibFunc::fabs:
5994       case LibFunc::fabsf:
5995       case LibFunc::fabsl:
5996         if (visitUnaryFloatCall(I, ISD::FABS))
5997           return;
5998         break;
5999       case LibFunc::fmin:
6000       case LibFunc::fminf:
6001       case LibFunc::fminl:
6002         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6003           return;
6004         break;
6005       case LibFunc::fmax:
6006       case LibFunc::fmaxf:
6007       case LibFunc::fmaxl:
6008         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6009           return;
6010         break;
6011       case LibFunc::sin:
6012       case LibFunc::sinf:
6013       case LibFunc::sinl:
6014         if (visitUnaryFloatCall(I, ISD::FSIN))
6015           return;
6016         break;
6017       case LibFunc::cos:
6018       case LibFunc::cosf:
6019       case LibFunc::cosl:
6020         if (visitUnaryFloatCall(I, ISD::FCOS))
6021           return;
6022         break;
6023       case LibFunc::sqrt:
6024       case LibFunc::sqrtf:
6025       case LibFunc::sqrtl:
6026       case LibFunc::sqrt_finite:
6027       case LibFunc::sqrtf_finite:
6028       case LibFunc::sqrtl_finite:
6029         if (visitUnaryFloatCall(I, ISD::FSQRT))
6030           return;
6031         break;
6032       case LibFunc::floor:
6033       case LibFunc::floorf:
6034       case LibFunc::floorl:
6035         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6036           return;
6037         break;
6038       case LibFunc::nearbyint:
6039       case LibFunc::nearbyintf:
6040       case LibFunc::nearbyintl:
6041         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6042           return;
6043         break;
6044       case LibFunc::ceil:
6045       case LibFunc::ceilf:
6046       case LibFunc::ceill:
6047         if (visitUnaryFloatCall(I, ISD::FCEIL))
6048           return;
6049         break;
6050       case LibFunc::rint:
6051       case LibFunc::rintf:
6052       case LibFunc::rintl:
6053         if (visitUnaryFloatCall(I, ISD::FRINT))
6054           return;
6055         break;
6056       case LibFunc::round:
6057       case LibFunc::roundf:
6058       case LibFunc::roundl:
6059         if (visitUnaryFloatCall(I, ISD::FROUND))
6060           return;
6061         break;
6062       case LibFunc::trunc:
6063       case LibFunc::truncf:
6064       case LibFunc::truncl:
6065         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6066           return;
6067         break;
6068       case LibFunc::log2:
6069       case LibFunc::log2f:
6070       case LibFunc::log2l:
6071         if (visitUnaryFloatCall(I, ISD::FLOG2))
6072           return;
6073         break;
6074       case LibFunc::exp2:
6075       case LibFunc::exp2f:
6076       case LibFunc::exp2l:
6077         if (visitUnaryFloatCall(I, ISD::FEXP2))
6078           return;
6079         break;
6080       case LibFunc::memcmp:
6081         if (visitMemCmpCall(I))
6082           return;
6083         break;
6084       case LibFunc::memchr:
6085         if (visitMemChrCall(I))
6086           return;
6087         break;
6088       case LibFunc::strcpy:
6089         if (visitStrCpyCall(I, false))
6090           return;
6091         break;
6092       case LibFunc::stpcpy:
6093         if (visitStrCpyCall(I, true))
6094           return;
6095         break;
6096       case LibFunc::strcmp:
6097         if (visitStrCmpCall(I))
6098           return;
6099         break;
6100       case LibFunc::strlen:
6101         if (visitStrLenCall(I))
6102           return;
6103         break;
6104       case LibFunc::strnlen:
6105         if (visitStrNLenCall(I))
6106           return;
6107         break;
6108       }
6109     }
6110   }
6111 
6112   SDValue Callee;
6113   if (!RenameFn)
6114     Callee = getValue(I.getCalledValue());
6115   else
6116     Callee = DAG.getExternalSymbol(
6117         RenameFn,
6118         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6119 
6120   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6121   // have to do anything here to lower funclet bundles.
6122   assert(!I.hasOperandBundlesOtherThan(
6123              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6124          "Cannot lower calls with arbitrary operand bundles!");
6125 
6126   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6127     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6128   else
6129     // Check if we can potentially perform a tail call. More detailed checking
6130     // is be done within LowerCallTo, after more information about the call is
6131     // known.
6132     LowerCallTo(&I, Callee, I.isTailCall());
6133 }
6134 
6135 namespace {
6136 
6137 /// AsmOperandInfo - This contains information for each constraint that we are
6138 /// lowering.
6139 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6140 public:
6141   /// CallOperand - If this is the result output operand or a clobber
6142   /// this is null, otherwise it is the incoming operand to the CallInst.
6143   /// This gets modified as the asm is processed.
6144   SDValue CallOperand;
6145 
6146   /// AssignedRegs - If this is a register or register class operand, this
6147   /// contains the set of register corresponding to the operand.
6148   RegsForValue AssignedRegs;
6149 
6150   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6151     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6152   }
6153 
6154   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6155   /// corresponds to.  If there is no Value* for this operand, it returns
6156   /// MVT::Other.
6157   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6158                            const DataLayout &DL) const {
6159     if (!CallOperandVal) return MVT::Other;
6160 
6161     if (isa<BasicBlock>(CallOperandVal))
6162       return TLI.getPointerTy(DL);
6163 
6164     llvm::Type *OpTy = CallOperandVal->getType();
6165 
6166     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6167     // If this is an indirect operand, the operand is a pointer to the
6168     // accessed type.
6169     if (isIndirect) {
6170       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6171       if (!PtrTy)
6172         report_fatal_error("Indirect operand for inline asm not a pointer!");
6173       OpTy = PtrTy->getElementType();
6174     }
6175 
6176     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6177     if (StructType *STy = dyn_cast<StructType>(OpTy))
6178       if (STy->getNumElements() == 1)
6179         OpTy = STy->getElementType(0);
6180 
6181     // If OpTy is not a single value, it may be a struct/union that we
6182     // can tile with integers.
6183     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6184       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6185       switch (BitSize) {
6186       default: break;
6187       case 1:
6188       case 8:
6189       case 16:
6190       case 32:
6191       case 64:
6192       case 128:
6193         OpTy = IntegerType::get(Context, BitSize);
6194         break;
6195       }
6196     }
6197 
6198     return TLI.getValueType(DL, OpTy, true);
6199   }
6200 };
6201 
6202 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6203 
6204 } // end anonymous namespace
6205 
6206 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6207 /// specified operand.  We prefer to assign virtual registers, to allow the
6208 /// register allocator to handle the assignment process.  However, if the asm
6209 /// uses features that we can't model on machineinstrs, we have SDISel do the
6210 /// allocation.  This produces generally horrible, but correct, code.
6211 ///
6212 ///   OpInfo describes the operand.
6213 ///
6214 static void GetRegistersForValue(SelectionDAG &DAG,
6215                                  const TargetLowering &TLI,
6216                                  SDLoc DL,
6217                                  SDISelAsmOperandInfo &OpInfo) {
6218   LLVMContext &Context = *DAG.getContext();
6219 
6220   MachineFunction &MF = DAG.getMachineFunction();
6221   SmallVector<unsigned, 4> Regs;
6222 
6223   // If this is a constraint for a single physreg, or a constraint for a
6224   // register class, find it.
6225   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
6226       TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
6227                                        OpInfo.ConstraintCode,
6228                                        OpInfo.ConstraintVT);
6229 
6230   unsigned NumRegs = 1;
6231   if (OpInfo.ConstraintVT != MVT::Other) {
6232     // If this is a FP input in an integer register (or visa versa) insert a bit
6233     // cast of the input value.  More generally, handle any case where the input
6234     // value disagrees with the register class we plan to stick this in.
6235     if (OpInfo.Type == InlineAsm::isInput &&
6236         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6237       // Try to convert to the first EVT that the reg class contains.  If the
6238       // types are identical size, use a bitcast to convert (e.g. two differing
6239       // vector types).
6240       MVT RegVT = *PhysReg.second->vt_begin();
6241       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6242         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6243                                          RegVT, OpInfo.CallOperand);
6244         OpInfo.ConstraintVT = RegVT;
6245       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6246         // If the input is a FP value and we want it in FP registers, do a
6247         // bitcast to the corresponding integer type.  This turns an f64 value
6248         // into i64, which can be passed with two i32 values on a 32-bit
6249         // machine.
6250         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6251         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6252                                          RegVT, OpInfo.CallOperand);
6253         OpInfo.ConstraintVT = RegVT;
6254       }
6255     }
6256 
6257     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6258   }
6259 
6260   MVT RegVT;
6261   EVT ValueVT = OpInfo.ConstraintVT;
6262 
6263   // If this is a constraint for a specific physical register, like {r17},
6264   // assign it now.
6265   if (unsigned AssignedReg = PhysReg.first) {
6266     const TargetRegisterClass *RC = PhysReg.second;
6267     if (OpInfo.ConstraintVT == MVT::Other)
6268       ValueVT = *RC->vt_begin();
6269 
6270     // Get the actual register value type.  This is important, because the user
6271     // may have asked for (e.g.) the AX register in i32 type.  We need to
6272     // remember that AX is actually i16 to get the right extension.
6273     RegVT = *RC->vt_begin();
6274 
6275     // This is a explicit reference to a physical register.
6276     Regs.push_back(AssignedReg);
6277 
6278     // If this is an expanded reference, add the rest of the regs to Regs.
6279     if (NumRegs != 1) {
6280       TargetRegisterClass::iterator I = RC->begin();
6281       for (; *I != AssignedReg; ++I)
6282         assert(I != RC->end() && "Didn't find reg!");
6283 
6284       // Already added the first reg.
6285       --NumRegs; ++I;
6286       for (; NumRegs; --NumRegs, ++I) {
6287         assert(I != RC->end() && "Ran out of registers to allocate!");
6288         Regs.push_back(*I);
6289       }
6290     }
6291 
6292     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6293     return;
6294   }
6295 
6296   // Otherwise, if this was a reference to an LLVM register class, create vregs
6297   // for this reference.
6298   if (const TargetRegisterClass *RC = PhysReg.second) {
6299     RegVT = *RC->vt_begin();
6300     if (OpInfo.ConstraintVT == MVT::Other)
6301       ValueVT = RegVT;
6302 
6303     // Create the appropriate number of virtual registers.
6304     MachineRegisterInfo &RegInfo = MF.getRegInfo();
6305     for (; NumRegs; --NumRegs)
6306       Regs.push_back(RegInfo.createVirtualRegister(RC));
6307 
6308     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6309     return;
6310   }
6311 
6312   // Otherwise, we couldn't allocate enough registers for this.
6313 }
6314 
6315 /// visitInlineAsm - Handle a call to an InlineAsm object.
6316 ///
6317 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6318   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6319 
6320   /// ConstraintOperands - Information about all of the constraints.
6321   SDISelAsmOperandInfoVector ConstraintOperands;
6322 
6323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6324   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
6325       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
6326 
6327   bool hasMemory = false;
6328 
6329   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
6330   unsigned ResNo = 0;   // ResNo - The result number of the next output.
6331   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6332     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6333     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6334 
6335     MVT OpVT = MVT::Other;
6336 
6337     // Compute the value type for each operand.
6338     switch (OpInfo.Type) {
6339     case InlineAsm::isOutput:
6340       // Indirect outputs just consume an argument.
6341       if (OpInfo.isIndirect) {
6342         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6343         break;
6344       }
6345 
6346       // The return value of the call is this value.  As such, there is no
6347       // corresponding argument.
6348       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6349       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6350         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
6351                                       STy->getElementType(ResNo));
6352       } else {
6353         assert(ResNo == 0 && "Asm only has one result!");
6354         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
6355       }
6356       ++ResNo;
6357       break;
6358     case InlineAsm::isInput:
6359       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6360       break;
6361     case InlineAsm::isClobber:
6362       // Nothing to do.
6363       break;
6364     }
6365 
6366     // If this is an input or an indirect output, process the call argument.
6367     // BasicBlocks are labels, currently appearing only in asm's.
6368     if (OpInfo.CallOperandVal) {
6369       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6370         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6371       } else {
6372         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6373       }
6374 
6375       OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
6376                                          DAG.getDataLayout()).getSimpleVT();
6377     }
6378 
6379     OpInfo.ConstraintVT = OpVT;
6380 
6381     // Indirect operand accesses access memory.
6382     if (OpInfo.isIndirect)
6383       hasMemory = true;
6384     else {
6385       for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6386         TargetLowering::ConstraintType
6387           CType = TLI.getConstraintType(OpInfo.Codes[j]);
6388         if (CType == TargetLowering::C_Memory) {
6389           hasMemory = true;
6390           break;
6391         }
6392       }
6393     }
6394   }
6395 
6396   SDValue Chain, Flag;
6397 
6398   // We won't need to flush pending loads if this asm doesn't touch
6399   // memory and is nonvolatile.
6400   if (hasMemory || IA->hasSideEffects())
6401     Chain = getRoot();
6402   else
6403     Chain = DAG.getRoot();
6404 
6405   // Second pass over the constraints: compute which constraint option to use
6406   // and assign registers to constraints that want a specific physreg.
6407   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6408     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6409 
6410     // If this is an output operand with a matching input operand, look up the
6411     // matching input. If their types mismatch, e.g. one is an integer, the
6412     // other is floating point, or their sizes are different, flag it as an
6413     // error.
6414     if (OpInfo.hasMatchingInput()) {
6415       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6416 
6417       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6418         const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6419         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6420             TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6421                                              OpInfo.ConstraintVT);
6422         std::pair<unsigned, const TargetRegisterClass *> InputRC =
6423             TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6424                                              Input.ConstraintVT);
6425         if ((OpInfo.ConstraintVT.isInteger() !=
6426              Input.ConstraintVT.isInteger()) ||
6427             (MatchRC.second != InputRC.second)) {
6428           report_fatal_error("Unsupported asm: input constraint"
6429                              " with a matching output constraint of"
6430                              " incompatible type!");
6431         }
6432         Input.ConstraintVT = OpInfo.ConstraintVT;
6433       }
6434     }
6435 
6436     // Compute the constraint code and ConstraintType to use.
6437     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6438 
6439     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6440         OpInfo.Type == InlineAsm::isClobber)
6441       continue;
6442 
6443     // If this is a memory input, and if the operand is not indirect, do what we
6444     // need to to provide an address for the memory input.
6445     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6446         !OpInfo.isIndirect) {
6447       assert((OpInfo.isMultipleAlternative ||
6448               (OpInfo.Type == InlineAsm::isInput)) &&
6449              "Can only indirectify direct input operands!");
6450 
6451       // Memory operands really want the address of the value.  If we don't have
6452       // an indirect input, put it in the constpool if we can, otherwise spill
6453       // it to a stack slot.
6454       // TODO: This isn't quite right. We need to handle these according to
6455       // the addressing mode that the constraint wants. Also, this may take
6456       // an additional register for the computation and we don't want that
6457       // either.
6458 
6459       // If the operand is a float, integer, or vector constant, spill to a
6460       // constant pool entry to get its address.
6461       const Value *OpVal = OpInfo.CallOperandVal;
6462       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6463           isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6464         OpInfo.CallOperand = DAG.getConstantPool(
6465             cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6466       } else {
6467         // Otherwise, create a stack slot and emit a store to it before the
6468         // asm.
6469         Type *Ty = OpVal->getType();
6470         auto &DL = DAG.getDataLayout();
6471         uint64_t TySize = DL.getTypeAllocSize(Ty);
6472         unsigned Align = DL.getPrefTypeAlignment(Ty);
6473         MachineFunction &MF = DAG.getMachineFunction();
6474         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6475         SDValue StackSlot =
6476             DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout()));
6477         Chain = DAG.getStore(
6478             Chain, getCurSDLoc(), OpInfo.CallOperand, StackSlot,
6479             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
6480             false, false, 0);
6481         OpInfo.CallOperand = StackSlot;
6482       }
6483 
6484       // There is no longer a Value* corresponding to this operand.
6485       OpInfo.CallOperandVal = nullptr;
6486 
6487       // It is now an indirect operand.
6488       OpInfo.isIndirect = true;
6489     }
6490 
6491     // If this constraint is for a specific register, allocate it before
6492     // anything else.
6493     if (OpInfo.ConstraintType == TargetLowering::C_Register)
6494       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6495   }
6496 
6497   // Second pass - Loop over all of the operands, assigning virtual or physregs
6498   // to register class operands.
6499   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6500     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6501 
6502     // C_Register operands have already been allocated, Other/Memory don't need
6503     // to be.
6504     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6505       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6506   }
6507 
6508   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6509   std::vector<SDValue> AsmNodeOperands;
6510   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
6511   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
6512       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
6513 
6514   // If we have a !srcloc metadata node associated with it, we want to attach
6515   // this to the ultimately generated inline asm machineinstr.  To do this, we
6516   // pass in the third operand as this (potentially null) inline asm MDNode.
6517   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6518   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6519 
6520   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6521   // bits as operand 3.
6522   unsigned ExtraInfo = 0;
6523   if (IA->hasSideEffects())
6524     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6525   if (IA->isAlignStack())
6526     ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6527   // Set the asm dialect.
6528   ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6529 
6530   // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6531   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6532     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6533 
6534     // Compute the constraint code and ConstraintType to use.
6535     TLI.ComputeConstraintToUse(OpInfo, SDValue());
6536 
6537     // Ideally, we would only check against memory constraints.  However, the
6538     // meaning of an other constraint can be target-specific and we can't easily
6539     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
6540     // for other constriants as well.
6541     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6542         OpInfo.ConstraintType == TargetLowering::C_Other) {
6543       if (OpInfo.Type == InlineAsm::isInput)
6544         ExtraInfo |= InlineAsm::Extra_MayLoad;
6545       else if (OpInfo.Type == InlineAsm::isOutput)
6546         ExtraInfo |= InlineAsm::Extra_MayStore;
6547       else if (OpInfo.Type == InlineAsm::isClobber)
6548         ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6549     }
6550   }
6551 
6552   AsmNodeOperands.push_back(DAG.getTargetConstant(
6553       ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6554 
6555   // Loop over all of the inputs, copying the operand values into the
6556   // appropriate registers and processing the output regs.
6557   RegsForValue RetValRegs;
6558 
6559   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6560   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6561 
6562   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6563     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6564 
6565     switch (OpInfo.Type) {
6566     case InlineAsm::isOutput: {
6567       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6568           OpInfo.ConstraintType != TargetLowering::C_Register) {
6569         // Memory output, or 'other' output (e.g. 'X' constraint).
6570         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6571 
6572         unsigned ConstraintID =
6573             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6574         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6575                "Failed to convert memory constraint code to constraint id.");
6576 
6577         // Add information to the INLINEASM node to know about this output.
6578         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6579         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
6580         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
6581                                                         MVT::i32));
6582         AsmNodeOperands.push_back(OpInfo.CallOperand);
6583         break;
6584       }
6585 
6586       // Otherwise, this is a register or register class output.
6587 
6588       // Copy the output from the appropriate register.  Find a register that
6589       // we can use.
6590       if (OpInfo.AssignedRegs.Regs.empty()) {
6591         LLVMContext &Ctx = *DAG.getContext();
6592         Ctx.emitError(CS.getInstruction(),
6593                       "couldn't allocate output register for constraint '" +
6594                           Twine(OpInfo.ConstraintCode) + "'");
6595         return;
6596       }
6597 
6598       // If this is an indirect operand, store through the pointer after the
6599       // asm.
6600       if (OpInfo.isIndirect) {
6601         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6602                                                       OpInfo.CallOperandVal));
6603       } else {
6604         // This is the result value of the call.
6605         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6606         // Concatenate this output onto the outputs list.
6607         RetValRegs.append(OpInfo.AssignedRegs);
6608       }
6609 
6610       // Add information to the INLINEASM node to know that this register is
6611       // set.
6612       OpInfo.AssignedRegs
6613           .AddInlineAsmOperands(OpInfo.isEarlyClobber
6614                                     ? InlineAsm::Kind_RegDefEarlyClobber
6615                                     : InlineAsm::Kind_RegDef,
6616                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
6617       break;
6618     }
6619     case InlineAsm::isInput: {
6620       SDValue InOperandVal = OpInfo.CallOperand;
6621 
6622       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
6623         // If this is required to match an output register we have already set,
6624         // just use its register.
6625         unsigned OperandNo = OpInfo.getMatchedOperand();
6626 
6627         // Scan until we find the definition we already emitted of this operand.
6628         // When we find it, create a RegsForValue operand.
6629         unsigned CurOp = InlineAsm::Op_FirstOperand;
6630         for (; OperandNo; --OperandNo) {
6631           // Advance to the next operand.
6632           unsigned OpFlag =
6633             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6634           assert((InlineAsm::isRegDefKind(OpFlag) ||
6635                   InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6636                   InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6637           CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6638         }
6639 
6640         unsigned OpFlag =
6641           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6642         if (InlineAsm::isRegDefKind(OpFlag) ||
6643             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6644           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6645           if (OpInfo.isIndirect) {
6646             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6647             LLVMContext &Ctx = *DAG.getContext();
6648             Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6649                                                " don't know how to handle tied "
6650                                                "indirect register inputs");
6651             return;
6652           }
6653 
6654           RegsForValue MatchedRegs;
6655           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6656           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6657           MatchedRegs.RegVTs.push_back(RegVT);
6658           MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6659           for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6660                i != e; ++i) {
6661             if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6662               MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6663             else {
6664               LLVMContext &Ctx = *DAG.getContext();
6665               Ctx.emitError(CS.getInstruction(),
6666                             "inline asm error: This value"
6667                             " type register class is not natively supported!");
6668               return;
6669             }
6670           }
6671           SDLoc dl = getCurSDLoc();
6672           // Use the produced MatchedRegs object to
6673           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6674                                     Chain, &Flag, CS.getInstruction());
6675           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6676                                            true, OpInfo.getMatchedOperand(), dl,
6677                                            DAG, AsmNodeOperands);
6678           break;
6679         }
6680 
6681         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6682         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6683                "Unexpected number of operands");
6684         // Add information to the INLINEASM node to know about this input.
6685         // See InlineAsm.h isUseOperandTiedToDef.
6686         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
6687         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6688                                                     OpInfo.getMatchedOperand());
6689         AsmNodeOperands.push_back(DAG.getTargetConstant(
6690             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6691         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6692         break;
6693       }
6694 
6695       // Treat indirect 'X' constraint as memory.
6696       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6697           OpInfo.isIndirect)
6698         OpInfo.ConstraintType = TargetLowering::C_Memory;
6699 
6700       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6701         std::vector<SDValue> Ops;
6702         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6703                                           Ops, DAG);
6704         if (Ops.empty()) {
6705           LLVMContext &Ctx = *DAG.getContext();
6706           Ctx.emitError(CS.getInstruction(),
6707                         "invalid operand for inline asm constraint '" +
6708                             Twine(OpInfo.ConstraintCode) + "'");
6709           return;
6710         }
6711 
6712         // Add information to the INLINEASM node to know about this input.
6713         unsigned ResOpType =
6714           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6715         AsmNodeOperands.push_back(DAG.getTargetConstant(
6716             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6717         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6718         break;
6719       }
6720 
6721       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6722         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6723         assert(InOperandVal.getValueType() ==
6724                    TLI.getPointerTy(DAG.getDataLayout()) &&
6725                "Memory operands expect pointer values");
6726 
6727         unsigned ConstraintID =
6728             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6729         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6730                "Failed to convert memory constraint code to constraint id.");
6731 
6732         // Add information to the INLINEASM node to know about this input.
6733         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6734         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
6735         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6736                                                         getCurSDLoc(),
6737                                                         MVT::i32));
6738         AsmNodeOperands.push_back(InOperandVal);
6739         break;
6740       }
6741 
6742       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6743               OpInfo.ConstraintType == TargetLowering::C_Register) &&
6744              "Unknown constraint type!");
6745 
6746       // TODO: Support this.
6747       if (OpInfo.isIndirect) {
6748         LLVMContext &Ctx = *DAG.getContext();
6749         Ctx.emitError(CS.getInstruction(),
6750                       "Don't know how to handle indirect register inputs yet "
6751                       "for constraint '" +
6752                           Twine(OpInfo.ConstraintCode) + "'");
6753         return;
6754       }
6755 
6756       // Copy the input into the appropriate registers.
6757       if (OpInfo.AssignedRegs.Regs.empty()) {
6758         LLVMContext &Ctx = *DAG.getContext();
6759         Ctx.emitError(CS.getInstruction(),
6760                       "couldn't allocate input reg for constraint '" +
6761                           Twine(OpInfo.ConstraintCode) + "'");
6762         return;
6763       }
6764 
6765       SDLoc dl = getCurSDLoc();
6766 
6767       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6768                                         Chain, &Flag, CS.getInstruction());
6769 
6770       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6771                                                dl, DAG, AsmNodeOperands);
6772       break;
6773     }
6774     case InlineAsm::isClobber: {
6775       // Add the clobbered value to the operand list, so that the register
6776       // allocator is aware that the physreg got clobbered.
6777       if (!OpInfo.AssignedRegs.Regs.empty())
6778         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6779                                                  false, 0, getCurSDLoc(), DAG,
6780                                                  AsmNodeOperands);
6781       break;
6782     }
6783     }
6784   }
6785 
6786   // Finish up input operands.  Set the input chain and add the flag last.
6787   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6788   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6789 
6790   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6791                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6792   Flag = Chain.getValue(1);
6793 
6794   // If this asm returns a register value, copy the result from that register
6795   // and set it as the value of the call.
6796   if (!RetValRegs.Regs.empty()) {
6797     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6798                                              Chain, &Flag, CS.getInstruction());
6799 
6800     // FIXME: Why don't we do this for inline asms with MRVs?
6801     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6802       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
6803 
6804       // If any of the results of the inline asm is a vector, it may have the
6805       // wrong width/num elts.  This can happen for register classes that can
6806       // contain multiple different value types.  The preg or vreg allocated may
6807       // not have the same VT as was expected.  Convert it to the right type
6808       // with bit_convert.
6809       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6810         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6811                           ResultType, Val);
6812 
6813       } else if (ResultType != Val.getValueType() &&
6814                  ResultType.isInteger() && Val.getValueType().isInteger()) {
6815         // If a result value was tied to an input value, the computed result may
6816         // have a wider width than the expected result.  Extract the relevant
6817         // portion.
6818         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6819       }
6820 
6821       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6822     }
6823 
6824     setValue(CS.getInstruction(), Val);
6825     // Don't need to use this as a chain in this case.
6826     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6827       return;
6828   }
6829 
6830   std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6831 
6832   // Process indirect outputs, first output all of the flagged copies out of
6833   // physregs.
6834   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6835     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6836     const Value *Ptr = IndirectStoresToEmit[i].second;
6837     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6838                                              Chain, &Flag, IA);
6839     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6840   }
6841 
6842   // Emit the non-flagged stores from the physregs.
6843   SmallVector<SDValue, 8> OutChains;
6844   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6845     SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6846                                StoresToEmit[i].first,
6847                                getValue(StoresToEmit[i].second),
6848                                MachinePointerInfo(StoresToEmit[i].second),
6849                                false, false, 0);
6850     OutChains.push_back(Val);
6851   }
6852 
6853   if (!OutChains.empty())
6854     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6855 
6856   DAG.setRoot(Chain);
6857 }
6858 
6859 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6860   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6861                           MVT::Other, getRoot(),
6862                           getValue(I.getArgOperand(0)),
6863                           DAG.getSrcValue(I.getArgOperand(0))));
6864 }
6865 
6866 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6868   const DataLayout &DL = DAG.getDataLayout();
6869   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6870                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
6871                            DAG.getSrcValue(I.getOperand(0)),
6872                            DL.getABITypeAlignment(I.getType()));
6873   setValue(&I, V);
6874   DAG.setRoot(V.getValue(1));
6875 }
6876 
6877 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6878   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6879                           MVT::Other, getRoot(),
6880                           getValue(I.getArgOperand(0)),
6881                           DAG.getSrcValue(I.getArgOperand(0))));
6882 }
6883 
6884 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6885   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6886                           MVT::Other, getRoot(),
6887                           getValue(I.getArgOperand(0)),
6888                           getValue(I.getArgOperand(1)),
6889                           DAG.getSrcValue(I.getArgOperand(0)),
6890                           DAG.getSrcValue(I.getArgOperand(1))));
6891 }
6892 
6893 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
6894                                                     const Instruction &I,
6895                                                     SDValue Op) {
6896   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
6897   if (!Range)
6898     return Op;
6899 
6900   Constant *Lo = cast<ConstantAsMetadata>(Range->getOperand(0))->getValue();
6901   if (!Lo->isNullValue())
6902     return Op;
6903 
6904   Constant *Hi = cast<ConstantAsMetadata>(Range->getOperand(1))->getValue();
6905   unsigned Bits = cast<ConstantInt>(Hi)->getValue().logBase2();
6906 
6907   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6908 
6909   SDLoc SL = getCurSDLoc();
6910 
6911   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(),
6912                              Op, DAG.getValueType(SmallVT));
6913   unsigned NumVals = Op.getNode()->getNumValues();
6914   if (NumVals == 1)
6915     return ZExt;
6916 
6917   SmallVector<SDValue, 4> Ops;
6918 
6919   Ops.push_back(ZExt);
6920   for (unsigned I = 1; I != NumVals; ++I)
6921     Ops.push_back(Op.getValue(I));
6922 
6923   return DAG.getMergeValues(Ops, SL);
6924 }
6925 
6926 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
6927 /// the call being lowered.
6928 ///
6929 /// This is a helper for lowering intrinsics that follow a target calling
6930 /// convention or require stack pointer adjustment. Only a subset of the
6931 /// intrinsic's operands need to participate in the calling convention.
6932 void SelectionDAGBuilder::populateCallLoweringInfo(
6933     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
6934     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
6935     bool IsPatchPoint) {
6936   TargetLowering::ArgListTy Args;
6937   Args.reserve(NumArgs);
6938 
6939   // Populate the argument list.
6940   // Attributes for args start at offset 1, after the return attribute.
6941   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6942        ArgI != ArgE; ++ArgI) {
6943     const Value *V = CS->getOperand(ArgI);
6944 
6945     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6946 
6947     TargetLowering::ArgListEntry Entry;
6948     Entry.Node = getValue(V);
6949     Entry.Ty = V->getType();
6950     Entry.setAttributes(&CS, AttrI);
6951     Args.push_back(Entry);
6952   }
6953 
6954   CLI.setDebugLoc(getCurSDLoc())
6955       .setChain(getRoot())
6956       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args),
6957                  NumArgs)
6958       .setDiscardResult(CS->use_empty())
6959       .setIsPatchPoint(IsPatchPoint);
6960 }
6961 
6962 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6963 /// or patchpoint target node's operand list.
6964 ///
6965 /// Constants are converted to TargetConstants purely as an optimization to
6966 /// avoid constant materialization and register allocation.
6967 ///
6968 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6969 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6970 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6971 /// address materialization and register allocation, but may also be required
6972 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6973 /// alloca in the entry block, then the runtime may assume that the alloca's
6974 /// StackMap location can be read immediately after compilation and that the
6975 /// location is valid at any point during execution (this is similar to the
6976 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6977 /// only available in a register, then the runtime would need to trap when
6978 /// execution reaches the StackMap in order to read the alloca's location.
6979 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
6980                                 SDLoc DL, SmallVectorImpl<SDValue> &Ops,
6981                                 SelectionDAGBuilder &Builder) {
6982   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6983     SDValue OpVal = Builder.getValue(CS.getArgument(i));
6984     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6985       Ops.push_back(
6986         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
6987       Ops.push_back(
6988         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
6989     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6990       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6991       Ops.push_back(Builder.DAG.getTargetFrameIndex(
6992           FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout())));
6993     } else
6994       Ops.push_back(OpVal);
6995   }
6996 }
6997 
6998 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6999 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7000   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7001   //                                  [live variables...])
7002 
7003   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7004 
7005   SDValue Chain, InFlag, Callee, NullPtr;
7006   SmallVector<SDValue, 32> Ops;
7007 
7008   SDLoc DL = getCurSDLoc();
7009   Callee = getValue(CI.getCalledValue());
7010   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7011 
7012   // The stackmap intrinsic only records the live variables (the arguemnts
7013   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7014   // intrinsic, this won't be lowered to a function call. This means we don't
7015   // have to worry about calling conventions and target specific lowering code.
7016   // Instead we perform the call lowering right here.
7017   //
7018   // chain, flag = CALLSEQ_START(chain, 0)
7019   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7020   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7021   //
7022   Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
7023   InFlag = Chain.getValue(1);
7024 
7025   // Add the <id> and <numBytes> constants.
7026   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7027   Ops.push_back(DAG.getTargetConstant(
7028                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7029   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7030   Ops.push_back(DAG.getTargetConstant(
7031                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7032                   MVT::i32));
7033 
7034   // Push live variables for the stack map.
7035   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7036 
7037   // We are not pushing any register mask info here on the operands list,
7038   // because the stackmap doesn't clobber anything.
7039 
7040   // Push the chain and the glue flag.
7041   Ops.push_back(Chain);
7042   Ops.push_back(InFlag);
7043 
7044   // Create the STACKMAP node.
7045   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7046   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7047   Chain = SDValue(SM, 0);
7048   InFlag = Chain.getValue(1);
7049 
7050   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7051 
7052   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7053 
7054   // Set the root to the target-lowered call chain.
7055   DAG.setRoot(Chain);
7056 
7057   // Inform the Frame Information that we have a stackmap in this function.
7058   FuncInfo.MF->getFrameInfo()->setHasStackMap();
7059 }
7060 
7061 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7062 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7063                                           const BasicBlock *EHPadBB) {
7064   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7065   //                                                 i32 <numBytes>,
7066   //                                                 i8* <target>,
7067   //                                                 i32 <numArgs>,
7068   //                                                 [Args...],
7069   //                                                 [live variables...])
7070 
7071   CallingConv::ID CC = CS.getCallingConv();
7072   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7073   bool HasDef = !CS->getType()->isVoidTy();
7074   SDLoc dl = getCurSDLoc();
7075   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7076 
7077   // Handle immediate and symbolic callees.
7078   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7079     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7080                                    /*isTarget=*/true);
7081   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7082     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7083                                          SDLoc(SymbolicCallee),
7084                                          SymbolicCallee->getValueType(0));
7085 
7086   // Get the real number of arguments participating in the call <numArgs>
7087   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7088   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7089 
7090   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7091   // Intrinsics include all meta-operands up to but not including CC.
7092   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7093   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7094          "Not enough arguments provided to the patchpoint intrinsic");
7095 
7096   // For AnyRegCC the arguments are lowered later on manually.
7097   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7098   Type *ReturnTy =
7099     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7100 
7101   TargetLowering::CallLoweringInfo CLI(DAG);
7102   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7103                            true);
7104   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7105 
7106   SDNode *CallEnd = Result.second.getNode();
7107   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7108     CallEnd = CallEnd->getOperand(0).getNode();
7109 
7110   /// Get a call instruction from the call sequence chain.
7111   /// Tail calls are not allowed.
7112   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7113          "Expected a callseq node.");
7114   SDNode *Call = CallEnd->getOperand(0).getNode();
7115   bool HasGlue = Call->getGluedNode();
7116 
7117   // Replace the target specific call node with the patchable intrinsic.
7118   SmallVector<SDValue, 8> Ops;
7119 
7120   // Add the <id> and <numBytes> constants.
7121   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7122   Ops.push_back(DAG.getTargetConstant(
7123                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7124   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7125   Ops.push_back(DAG.getTargetConstant(
7126                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7127                   MVT::i32));
7128 
7129   // Add the callee.
7130   Ops.push_back(Callee);
7131 
7132   // Adjust <numArgs> to account for any arguments that have been passed on the
7133   // stack instead.
7134   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7135   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7136   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7137   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7138 
7139   // Add the calling convention
7140   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7141 
7142   // Add the arguments we omitted previously. The register allocator should
7143   // place these in any free register.
7144   if (IsAnyRegCC)
7145     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7146       Ops.push_back(getValue(CS.getArgument(i)));
7147 
7148   // Push the arguments from the call instruction up to the register mask.
7149   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7150   Ops.append(Call->op_begin() + 2, e);
7151 
7152   // Push live variables for the stack map.
7153   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
7154 
7155   // Push the register mask info.
7156   if (HasGlue)
7157     Ops.push_back(*(Call->op_end()-2));
7158   else
7159     Ops.push_back(*(Call->op_end()-1));
7160 
7161   // Push the chain (this is originally the first operand of the call, but
7162   // becomes now the last or second to last operand).
7163   Ops.push_back(*(Call->op_begin()));
7164 
7165   // Push the glue flag (last operand).
7166   if (HasGlue)
7167     Ops.push_back(*(Call->op_end()-1));
7168 
7169   SDVTList NodeTys;
7170   if (IsAnyRegCC && HasDef) {
7171     // Create the return types based on the intrinsic definition
7172     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7173     SmallVector<EVT, 3> ValueVTs;
7174     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7175     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7176 
7177     // There is always a chain and a glue type at the end
7178     ValueVTs.push_back(MVT::Other);
7179     ValueVTs.push_back(MVT::Glue);
7180     NodeTys = DAG.getVTList(ValueVTs);
7181   } else
7182     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7183 
7184   // Replace the target specific call node with a PATCHPOINT node.
7185   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7186                                          dl, NodeTys, Ops);
7187 
7188   // Update the NodeMap.
7189   if (HasDef) {
7190     if (IsAnyRegCC)
7191       setValue(CS.getInstruction(), SDValue(MN, 0));
7192     else
7193       setValue(CS.getInstruction(), Result.first);
7194   }
7195 
7196   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7197   // call sequence. Furthermore the location of the chain and glue can change
7198   // when the AnyReg calling convention is used and the intrinsic returns a
7199   // value.
7200   if (IsAnyRegCC && HasDef) {
7201     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7202     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7203     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7204   } else
7205     DAG.ReplaceAllUsesWith(Call, MN);
7206   DAG.DeleteNode(Call);
7207 
7208   // Inform the Frame Information that we have a patchpoint in this function.
7209   FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
7210 }
7211 
7212 /// Returns an AttributeSet representing the attributes applied to the return
7213 /// value of the given call.
7214 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7215   SmallVector<Attribute::AttrKind, 2> Attrs;
7216   if (CLI.RetSExt)
7217     Attrs.push_back(Attribute::SExt);
7218   if (CLI.RetZExt)
7219     Attrs.push_back(Attribute::ZExt);
7220   if (CLI.IsInReg)
7221     Attrs.push_back(Attribute::InReg);
7222 
7223   return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7224                            Attrs);
7225 }
7226 
7227 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7228 /// implementation, which just calls LowerCall.
7229 /// FIXME: When all targets are
7230 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7231 std::pair<SDValue, SDValue>
7232 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7233   // Handle the incoming return values from the call.
7234   CLI.Ins.clear();
7235   Type *OrigRetTy = CLI.RetTy;
7236   SmallVector<EVT, 4> RetTys;
7237   SmallVector<uint64_t, 4> Offsets;
7238   auto &DL = CLI.DAG.getDataLayout();
7239   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
7240 
7241   SmallVector<ISD::OutputArg, 4> Outs;
7242   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
7243 
7244   bool CanLowerReturn =
7245       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7246                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7247 
7248   SDValue DemoteStackSlot;
7249   int DemoteStackIdx = -100;
7250   if (!CanLowerReturn) {
7251     // FIXME: equivalent assert?
7252     // assert(!CS.hasInAllocaArgument() &&
7253     //        "sret demotion is incompatible with inalloca");
7254     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
7255     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
7256     MachineFunction &MF = CLI.DAG.getMachineFunction();
7257     DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7258     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7259 
7260     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL));
7261     ArgListEntry Entry;
7262     Entry.Node = DemoteStackSlot;
7263     Entry.Ty = StackSlotPtrType;
7264     Entry.isSExt = false;
7265     Entry.isZExt = false;
7266     Entry.isInReg = false;
7267     Entry.isSRet = true;
7268     Entry.isNest = false;
7269     Entry.isByVal = false;
7270     Entry.isReturned = false;
7271     Entry.Alignment = Align;
7272     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7273     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7274 
7275     // sret demotion isn't compatible with tail-calls, since the sret argument
7276     // points into the callers stack frame.
7277     CLI.IsTailCall = false;
7278   } else {
7279     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7280       EVT VT = RetTys[I];
7281       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7282       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7283       for (unsigned i = 0; i != NumRegs; ++i) {
7284         ISD::InputArg MyFlags;
7285         MyFlags.VT = RegisterVT;
7286         MyFlags.ArgVT = VT;
7287         MyFlags.Used = CLI.IsReturnValueUsed;
7288         if (CLI.RetSExt)
7289           MyFlags.Flags.setSExt();
7290         if (CLI.RetZExt)
7291           MyFlags.Flags.setZExt();
7292         if (CLI.IsInReg)
7293           MyFlags.Flags.setInReg();
7294         CLI.Ins.push_back(MyFlags);
7295       }
7296     }
7297   }
7298 
7299   // Handle all of the outgoing arguments.
7300   CLI.Outs.clear();
7301   CLI.OutVals.clear();
7302   ArgListTy &Args = CLI.getArgs();
7303   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7304     SmallVector<EVT, 4> ValueVTs;
7305     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
7306     Type *FinalType = Args[i].Ty;
7307     if (Args[i].isByVal)
7308       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7309     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7310         FinalType, CLI.CallConv, CLI.IsVarArg);
7311     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7312          ++Value) {
7313       EVT VT = ValueVTs[Value];
7314       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7315       SDValue Op = SDValue(Args[i].Node.getNode(),
7316                            Args[i].Node.getResNo() + Value);
7317       ISD::ArgFlagsTy Flags;
7318       unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7319 
7320       if (Args[i].isZExt)
7321         Flags.setZExt();
7322       if (Args[i].isSExt)
7323         Flags.setSExt();
7324       if (Args[i].isInReg)
7325         Flags.setInReg();
7326       if (Args[i].isSRet)
7327         Flags.setSRet();
7328       if (Args[i].isByVal)
7329         Flags.setByVal();
7330       if (Args[i].isInAlloca) {
7331         Flags.setInAlloca();
7332         // Set the byval flag for CCAssignFn callbacks that don't know about
7333         // inalloca.  This way we can know how many bytes we should've allocated
7334         // and how many bytes a callee cleanup function will pop.  If we port
7335         // inalloca to more targets, we'll have to add custom inalloca handling
7336         // in the various CC lowering callbacks.
7337         Flags.setByVal();
7338       }
7339       if (Args[i].isByVal || Args[i].isInAlloca) {
7340         PointerType *Ty = cast<PointerType>(Args[i].Ty);
7341         Type *ElementTy = Ty->getElementType();
7342         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7343         // For ByVal, alignment should come from FE.  BE will guess if this
7344         // info is not there but there are cases it cannot get right.
7345         unsigned FrameAlign;
7346         if (Args[i].Alignment)
7347           FrameAlign = Args[i].Alignment;
7348         else
7349           FrameAlign = getByValTypeAlignment(ElementTy, DL);
7350         Flags.setByValAlign(FrameAlign);
7351       }
7352       if (Args[i].isNest)
7353         Flags.setNest();
7354       if (NeedsRegBlock)
7355         Flags.setInConsecutiveRegs();
7356       Flags.setOrigAlign(OriginalAlignment);
7357 
7358       MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7359       unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7360       SmallVector<SDValue, 4> Parts(NumParts);
7361       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7362 
7363       if (Args[i].isSExt)
7364         ExtendKind = ISD::SIGN_EXTEND;
7365       else if (Args[i].isZExt)
7366         ExtendKind = ISD::ZERO_EXTEND;
7367 
7368       // Conservatively only handle 'returned' on non-vectors for now
7369       if (Args[i].isReturned && !Op.getValueType().isVector()) {
7370         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7371                "unexpected use of 'returned'");
7372         // Before passing 'returned' to the target lowering code, ensure that
7373         // either the register MVT and the actual EVT are the same size or that
7374         // the return value and argument are extended in the same way; in these
7375         // cases it's safe to pass the argument register value unchanged as the
7376         // return register value (although it's at the target's option whether
7377         // to do so)
7378         // TODO: allow code generation to take advantage of partially preserved
7379         // registers rather than clobbering the entire register when the
7380         // parameter extension method is not compatible with the return
7381         // extension method
7382         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7383             (ExtendKind != ISD::ANY_EXTEND &&
7384              CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7385         Flags.setReturned();
7386       }
7387 
7388       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7389                      CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
7390 
7391       for (unsigned j = 0; j != NumParts; ++j) {
7392         // if it isn't first piece, alignment must be 1
7393         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7394                                i < CLI.NumFixedArgs,
7395                                i, j*Parts[j].getValueType().getStoreSize());
7396         if (NumParts > 1 && j == 0)
7397           MyFlags.Flags.setSplit();
7398         else if (j != 0) {
7399           MyFlags.Flags.setOrigAlign(1);
7400           if (j == NumParts - 1)
7401             MyFlags.Flags.setSplitEnd();
7402         }
7403 
7404         CLI.Outs.push_back(MyFlags);
7405         CLI.OutVals.push_back(Parts[j]);
7406       }
7407 
7408       if (NeedsRegBlock && Value == NumValues - 1)
7409         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
7410     }
7411   }
7412 
7413   SmallVector<SDValue, 4> InVals;
7414   CLI.Chain = LowerCall(CLI, InVals);
7415 
7416   // Verify that the target's LowerCall behaved as expected.
7417   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7418          "LowerCall didn't return a valid chain!");
7419   assert((!CLI.IsTailCall || InVals.empty()) &&
7420          "LowerCall emitted a return value for a tail call!");
7421   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7422          "LowerCall didn't emit the correct number of values!");
7423 
7424   // For a tail call, the return value is merely live-out and there aren't
7425   // any nodes in the DAG representing it. Return a special value to
7426   // indicate that a tail call has been emitted and no more Instructions
7427   // should be processed in the current block.
7428   if (CLI.IsTailCall) {
7429     CLI.DAG.setRoot(CLI.Chain);
7430     return std::make_pair(SDValue(), SDValue());
7431   }
7432 
7433   DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7434           assert(InVals[i].getNode() &&
7435                  "LowerCall emitted a null value!");
7436           assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7437                  "LowerCall emitted a value with the wrong type!");
7438         });
7439 
7440   SmallVector<SDValue, 4> ReturnValues;
7441   if (!CanLowerReturn) {
7442     // The instruction result is the result of loading from the
7443     // hidden sret parameter.
7444     SmallVector<EVT, 1> PVTs;
7445     Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
7446 
7447     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
7448     assert(PVTs.size() == 1 && "Pointers should fit in one register");
7449     EVT PtrVT = PVTs[0];
7450 
7451     unsigned NumValues = RetTys.size();
7452     ReturnValues.resize(NumValues);
7453     SmallVector<SDValue, 4> Chains(NumValues);
7454 
7455     // An aggregate return value cannot wrap around the address space, so
7456     // offsets to its parts don't wrap either.
7457     SDNodeFlags Flags;
7458     Flags.setNoUnsignedWrap(true);
7459 
7460     for (unsigned i = 0; i < NumValues; ++i) {
7461       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7462                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
7463                                                         PtrVT), &Flags);
7464       SDValue L = CLI.DAG.getLoad(
7465           RetTys[i], CLI.DL, CLI.Chain, Add,
7466           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
7467                                             DemoteStackIdx, Offsets[i]),
7468           false, false, false, 1);
7469       ReturnValues[i] = L;
7470       Chains[i] = L.getValue(1);
7471     }
7472 
7473     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7474   } else {
7475     // Collect the legal value parts into potentially illegal values
7476     // that correspond to the original function's return values.
7477     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7478     if (CLI.RetSExt)
7479       AssertOp = ISD::AssertSext;
7480     else if (CLI.RetZExt)
7481       AssertOp = ISD::AssertZext;
7482     unsigned CurReg = 0;
7483     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7484       EVT VT = RetTys[I];
7485       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7486       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7487 
7488       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7489                                               NumRegs, RegisterVT, VT, nullptr,
7490                                               AssertOp));
7491       CurReg += NumRegs;
7492     }
7493 
7494     // For a function returning void, there is no return value. We can't create
7495     // such a node, so we just return a null return value in that case. In
7496     // that case, nothing will actually look at the value.
7497     if (ReturnValues.empty())
7498       return std::make_pair(SDValue(), CLI.Chain);
7499   }
7500 
7501   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7502                                 CLI.DAG.getVTList(RetTys), ReturnValues);
7503   return std::make_pair(Res, CLI.Chain);
7504 }
7505 
7506 void TargetLowering::LowerOperationWrapper(SDNode *N,
7507                                            SmallVectorImpl<SDValue> &Results,
7508                                            SelectionDAG &DAG) const {
7509   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
7510     Results.push_back(Res);
7511 }
7512 
7513 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7514   llvm_unreachable("LowerOperation not implemented for this target!");
7515 }
7516 
7517 void
7518 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7519   SDValue Op = getNonRegisterValue(V);
7520   assert((Op.getOpcode() != ISD::CopyFromReg ||
7521           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7522          "Copy from a reg to the same reg!");
7523   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7524 
7525   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7526   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
7527                    V->getType());
7528   SDValue Chain = DAG.getEntryNode();
7529 
7530   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7531                               FuncInfo.PreferredExtendType.end())
7532                                  ? ISD::ANY_EXTEND
7533                                  : FuncInfo.PreferredExtendType[V];
7534   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7535   PendingExports.push_back(Chain);
7536 }
7537 
7538 #include "llvm/CodeGen/SelectionDAGISel.h"
7539 
7540 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7541 /// entry block, return true.  This includes arguments used by switches, since
7542 /// the switch may expand into multiple basic blocks.
7543 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7544   // With FastISel active, we may be splitting blocks, so force creation
7545   // of virtual registers for all non-dead arguments.
7546   if (FastISel)
7547     return A->use_empty();
7548 
7549   const BasicBlock &Entry = A->getParent()->front();
7550   for (const User *U : A->users())
7551     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
7552       return false;  // Use not in entry block.
7553 
7554   return true;
7555 }
7556 
7557 void SelectionDAGISel::LowerArguments(const Function &F) {
7558   SelectionDAG &DAG = SDB->DAG;
7559   SDLoc dl = SDB->getCurSDLoc();
7560   const DataLayout &DL = DAG.getDataLayout();
7561   SmallVector<ISD::InputArg, 16> Ins;
7562 
7563   if (!FuncInfo->CanLowerReturn) {
7564     // Put in an sret pointer parameter before all the other parameters.
7565     SmallVector<EVT, 1> ValueVTs;
7566     ComputeValueVTs(*TLI, DAG.getDataLayout(),
7567                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
7568 
7569     // NOTE: Assuming that a pointer will never break down to more than one VT
7570     // or one register.
7571     ISD::ArgFlagsTy Flags;
7572     Flags.setSRet();
7573     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7574     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
7575                          ISD::InputArg::NoArgIndex, 0);
7576     Ins.push_back(RetArg);
7577   }
7578 
7579   // Set up the incoming argument description vector.
7580   unsigned Idx = 1;
7581   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7582        I != E; ++I, ++Idx) {
7583     SmallVector<EVT, 4> ValueVTs;
7584     ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7585     bool isArgValueUsed = !I->use_empty();
7586     unsigned PartBase = 0;
7587     Type *FinalType = I->getType();
7588     if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7589       FinalType = cast<PointerType>(FinalType)->getElementType();
7590     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7591         FinalType, F.getCallingConv(), F.isVarArg());
7592     for (unsigned Value = 0, NumValues = ValueVTs.size();
7593          Value != NumValues; ++Value) {
7594       EVT VT = ValueVTs[Value];
7595       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7596       ISD::ArgFlagsTy Flags;
7597       unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7598 
7599       if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7600         Flags.setZExt();
7601       if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7602         Flags.setSExt();
7603       if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7604         Flags.setInReg();
7605       if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7606         Flags.setSRet();
7607       if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7608         Flags.setByVal();
7609       if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7610         Flags.setInAlloca();
7611         // Set the byval flag for CCAssignFn callbacks that don't know about
7612         // inalloca.  This way we can know how many bytes we should've allocated
7613         // and how many bytes a callee cleanup function will pop.  If we port
7614         // inalloca to more targets, we'll have to add custom inalloca handling
7615         // in the various CC lowering callbacks.
7616         Flags.setByVal();
7617       }
7618       if (F.getCallingConv() == CallingConv::X86_INTR) {
7619         // IA Interrupt passes frame (1st parameter) by value in the stack.
7620         if (Idx == 1)
7621           Flags.setByVal();
7622       }
7623       if (Flags.isByVal() || Flags.isInAlloca()) {
7624         PointerType *Ty = cast<PointerType>(I->getType());
7625         Type *ElementTy = Ty->getElementType();
7626         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7627         // For ByVal, alignment should be passed from FE.  BE will guess if
7628         // this info is not there but there are cases it cannot get right.
7629         unsigned FrameAlign;
7630         if (F.getParamAlignment(Idx))
7631           FrameAlign = F.getParamAlignment(Idx);
7632         else
7633           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
7634         Flags.setByValAlign(FrameAlign);
7635       }
7636       if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7637         Flags.setNest();
7638       if (NeedsRegBlock)
7639         Flags.setInConsecutiveRegs();
7640       Flags.setOrigAlign(OriginalAlignment);
7641 
7642       MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7643       unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7644       for (unsigned i = 0; i != NumRegs; ++i) {
7645         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7646                               Idx-1, PartBase+i*RegisterVT.getStoreSize());
7647         if (NumRegs > 1 && i == 0)
7648           MyFlags.Flags.setSplit();
7649         // if it isn't first piece, alignment must be 1
7650         else if (i > 0) {
7651           MyFlags.Flags.setOrigAlign(1);
7652           if (i == NumRegs - 1)
7653             MyFlags.Flags.setSplitEnd();
7654         }
7655         Ins.push_back(MyFlags);
7656       }
7657       if (NeedsRegBlock && Value == NumValues - 1)
7658         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
7659       PartBase += VT.getStoreSize();
7660     }
7661   }
7662 
7663   // Call the target to set up the argument values.
7664   SmallVector<SDValue, 8> InVals;
7665   SDValue NewRoot = TLI->LowerFormalArguments(
7666       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7667 
7668   // Verify that the target's LowerFormalArguments behaved as expected.
7669   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7670          "LowerFormalArguments didn't return a valid chain!");
7671   assert(InVals.size() == Ins.size() &&
7672          "LowerFormalArguments didn't emit the correct number of values!");
7673   DEBUG({
7674       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7675         assert(InVals[i].getNode() &&
7676                "LowerFormalArguments emitted a null value!");
7677         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7678                "LowerFormalArguments emitted a value with the wrong type!");
7679       }
7680     });
7681 
7682   // Update the DAG with the new chain value resulting from argument lowering.
7683   DAG.setRoot(NewRoot);
7684 
7685   // Set up the argument values.
7686   unsigned i = 0;
7687   Idx = 1;
7688   if (!FuncInfo->CanLowerReturn) {
7689     // Create a virtual register for the sret pointer, and put in a copy
7690     // from the sret argument into it.
7691     SmallVector<EVT, 1> ValueVTs;
7692     ComputeValueVTs(*TLI, DAG.getDataLayout(),
7693                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
7694     MVT VT = ValueVTs[0].getSimpleVT();
7695     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7696     ISD::NodeType AssertOp = ISD::DELETED_NODE;
7697     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7698                                         RegVT, VT, nullptr, AssertOp);
7699 
7700     MachineFunction& MF = SDB->DAG.getMachineFunction();
7701     MachineRegisterInfo& RegInfo = MF.getRegInfo();
7702     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7703     FuncInfo->DemoteRegister = SRetReg;
7704     NewRoot =
7705         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7706     DAG.setRoot(NewRoot);
7707 
7708     // i indexes lowered arguments.  Bump it past the hidden sret argument.
7709     // Idx indexes LLVM arguments.  Don't touch it.
7710     ++i;
7711   }
7712 
7713   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7714       ++I, ++Idx) {
7715     SmallVector<SDValue, 4> ArgValues;
7716     SmallVector<EVT, 4> ValueVTs;
7717     ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7718     unsigned NumValues = ValueVTs.size();
7719 
7720     // If this argument is unused then remember its value. It is used to generate
7721     // debugging information.
7722     if (I->use_empty() && NumValues) {
7723       SDB->setUnusedArgValue(&*I, InVals[i]);
7724 
7725       // Also remember any frame index for use in FastISel.
7726       if (FrameIndexSDNode *FI =
7727           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7728         FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7729     }
7730 
7731     for (unsigned Val = 0; Val != NumValues; ++Val) {
7732       EVT VT = ValueVTs[Val];
7733       MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7734       unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7735 
7736       if (!I->use_empty()) {
7737         ISD::NodeType AssertOp = ISD::DELETED_NODE;
7738         if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7739           AssertOp = ISD::AssertSext;
7740         else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7741           AssertOp = ISD::AssertZext;
7742 
7743         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7744                                              NumParts, PartVT, VT,
7745                                              nullptr, AssertOp));
7746       }
7747 
7748       i += NumParts;
7749     }
7750 
7751     // We don't need to do anything else for unused arguments.
7752     if (ArgValues.empty())
7753       continue;
7754 
7755     // Note down frame index.
7756     if (FrameIndexSDNode *FI =
7757         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7758       FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7759 
7760     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7761                                      SDB->getCurSDLoc());
7762 
7763     SDB->setValue(&*I, Res);
7764     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7765       if (LoadSDNode *LNode =
7766           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7767         if (FrameIndexSDNode *FI =
7768             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7769         FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex());
7770     }
7771 
7772     // If this argument is live outside of the entry block, insert a copy from
7773     // wherever we got it to the vreg that other BB's will reference it as.
7774     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7775       // If we can, though, try to skip creating an unnecessary vreg.
7776       // FIXME: This isn't very clean... it would be nice to make this more
7777       // general.  It's also subtly incompatible with the hacks FastISel
7778       // uses with vregs.
7779       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7780       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7781         FuncInfo->ValueMap[&*I] = Reg;
7782         continue;
7783       }
7784     }
7785     if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) {
7786       FuncInfo->InitializeRegForValue(&*I);
7787       SDB->CopyToExportRegsIfNeeded(&*I);
7788     }
7789   }
7790 
7791   assert(i == InVals.size() && "Argument register count mismatch!");
7792 
7793   // Finally, if the target has anything special to do, allow it to do so.
7794   EmitFunctionEntryCode();
7795 }
7796 
7797 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
7798 /// ensure constants are generated when needed.  Remember the virtual registers
7799 /// that need to be added to the Machine PHI nodes as input.  We cannot just
7800 /// directly add them, because expansion might result in multiple MBB's for one
7801 /// BB.  As such, the start of the BB might correspond to a different MBB than
7802 /// the end.
7803 ///
7804 void
7805 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7806   const TerminatorInst *TI = LLVMBB->getTerminator();
7807 
7808   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7809 
7810   // Check PHI nodes in successors that expect a value to be available from this
7811   // block.
7812   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7813     const BasicBlock *SuccBB = TI->getSuccessor(succ);
7814     if (!isa<PHINode>(SuccBB->begin())) continue;
7815     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7816 
7817     // If this terminator has multiple identical successors (common for
7818     // switches), only handle each succ once.
7819     if (!SuccsHandled.insert(SuccMBB).second)
7820       continue;
7821 
7822     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7823 
7824     // At this point we know that there is a 1-1 correspondence between LLVM PHI
7825     // nodes and Machine PHI nodes, but the incoming operands have not been
7826     // emitted yet.
7827     for (BasicBlock::const_iterator I = SuccBB->begin();
7828          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7829       // Ignore dead phi's.
7830       if (PN->use_empty()) continue;
7831 
7832       // Skip empty types
7833       if (PN->getType()->isEmptyTy())
7834         continue;
7835 
7836       unsigned Reg;
7837       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7838 
7839       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7840         unsigned &RegOut = ConstantsOut[C];
7841         if (RegOut == 0) {
7842           RegOut = FuncInfo.CreateRegs(C->getType());
7843           CopyValueToVirtualRegister(C, RegOut);
7844         }
7845         Reg = RegOut;
7846       } else {
7847         DenseMap<const Value *, unsigned>::iterator I =
7848           FuncInfo.ValueMap.find(PHIOp);
7849         if (I != FuncInfo.ValueMap.end())
7850           Reg = I->second;
7851         else {
7852           assert(isa<AllocaInst>(PHIOp) &&
7853                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7854                  "Didn't codegen value into a register!??");
7855           Reg = FuncInfo.CreateRegs(PHIOp->getType());
7856           CopyValueToVirtualRegister(PHIOp, Reg);
7857         }
7858       }
7859 
7860       // Remember that this register needs to added to the machine PHI node as
7861       // the input for this MBB.
7862       SmallVector<EVT, 4> ValueVTs;
7863       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7864       ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
7865       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7866         EVT VT = ValueVTs[vti];
7867         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7868         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7869           FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7870         Reg += NumRegisters;
7871       }
7872     }
7873   }
7874 
7875   ConstantsOut.clear();
7876 }
7877 
7878 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7879 /// is 0.
7880 MachineBasicBlock *
7881 SelectionDAGBuilder::StackProtectorDescriptor::
7882 AddSuccessorMBB(const BasicBlock *BB,
7883                 MachineBasicBlock *ParentMBB,
7884                 bool IsLikely,
7885                 MachineBasicBlock *SuccMBB) {
7886   // If SuccBB has not been created yet, create it.
7887   if (!SuccMBB) {
7888     MachineFunction *MF = ParentMBB->getParent();
7889     MachineFunction::iterator BBI(ParentMBB);
7890     SuccMBB = MF->CreateMachineBasicBlock(BB);
7891     MF->insert(++BBI, SuccMBB);
7892   }
7893   // Add it as a successor of ParentMBB.
7894   ParentMBB->addSuccessor(
7895       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
7896   return SuccMBB;
7897 }
7898 
7899 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
7900   MachineFunction::iterator I(MBB);
7901   if (++I == FuncInfo.MF->end())
7902     return nullptr;
7903   return &*I;
7904 }
7905 
7906 /// During lowering new call nodes can be created (such as memset, etc.).
7907 /// Those will become new roots of the current DAG, but complications arise
7908 /// when they are tail calls. In such cases, the call lowering will update
7909 /// the root, but the builder still needs to know that a tail call has been
7910 /// lowered in order to avoid generating an additional return.
7911 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
7912   // If the node is null, we do have a tail call.
7913   if (MaybeTC.getNode() != nullptr)
7914     DAG.setRoot(MaybeTC);
7915   else
7916     HasTailCall = true;
7917 }
7918 
7919 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
7920                                   unsigned *TotalCases, unsigned First,
7921                                   unsigned Last) {
7922   assert(Last >= First);
7923   assert(TotalCases[Last] >= TotalCases[First]);
7924 
7925   APInt LowCase = Clusters[First].Low->getValue();
7926   APInt HighCase = Clusters[Last].High->getValue();
7927   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
7928 
7929   // FIXME: A range of consecutive cases has 100% density, but only requires one
7930   // comparison to lower. We should discriminate against such consecutive ranges
7931   // in jump tables.
7932 
7933   uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
7934   uint64_t Range = Diff + 1;
7935 
7936   uint64_t NumCases =
7937       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
7938 
7939   assert(NumCases < UINT64_MAX / 100);
7940   assert(Range >= NumCases);
7941 
7942   return NumCases * 100 >= Range * MinJumpTableDensity;
7943 }
7944 
7945 static inline bool areJTsAllowed(const TargetLowering &TLI) {
7946   return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
7947          TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
7948 }
7949 
7950 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters,
7951                                          unsigned First, unsigned Last,
7952                                          const SwitchInst *SI,
7953                                          MachineBasicBlock *DefaultMBB,
7954                                          CaseCluster &JTCluster) {
7955   assert(First <= Last);
7956 
7957   auto Prob = BranchProbability::getZero();
7958   unsigned NumCmps = 0;
7959   std::vector<MachineBasicBlock*> Table;
7960   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
7961 
7962   // Initialize probabilities in JTProbs.
7963   for (unsigned I = First; I <= Last; ++I)
7964     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
7965 
7966   for (unsigned I = First; I <= Last; ++I) {
7967     assert(Clusters[I].Kind == CC_Range);
7968     Prob += Clusters[I].Prob;
7969     APInt Low = Clusters[I].Low->getValue();
7970     APInt High = Clusters[I].High->getValue();
7971     NumCmps += (Low == High) ? 1 : 2;
7972     if (I != First) {
7973       // Fill the gap between this and the previous cluster.
7974       APInt PreviousHigh = Clusters[I - 1].High->getValue();
7975       assert(PreviousHigh.slt(Low));
7976       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
7977       for (uint64_t J = 0; J < Gap; J++)
7978         Table.push_back(DefaultMBB);
7979     }
7980     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
7981     for (uint64_t J = 0; J < ClusterSize; ++J)
7982       Table.push_back(Clusters[I].MBB);
7983     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
7984   }
7985 
7986   unsigned NumDests = JTProbs.size();
7987   if (isSuitableForBitTests(NumDests, NumCmps,
7988                             Clusters[First].Low->getValue(),
7989                             Clusters[Last].High->getValue())) {
7990     // Clusters[First..Last] should be lowered as bit tests instead.
7991     return false;
7992   }
7993 
7994   // Create the MBB that will load from and jump through the table.
7995   // Note: We create it here, but it's not inserted into the function yet.
7996   MachineFunction *CurMF = FuncInfo.MF;
7997   MachineBasicBlock *JumpTableMBB =
7998       CurMF->CreateMachineBasicBlock(SI->getParent());
7999 
8000   // Add successors. Note: use table order for determinism.
8001   SmallPtrSet<MachineBasicBlock *, 8> Done;
8002   for (MachineBasicBlock *Succ : Table) {
8003     if (Done.count(Succ))
8004       continue;
8005     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
8006     Done.insert(Succ);
8007   }
8008   JumpTableMBB->normalizeSuccProbs();
8009 
8010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8011   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
8012                      ->createJumpTableIndex(Table);
8013 
8014   // Set up the jump table info.
8015   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
8016   JumpTableHeader JTH(Clusters[First].Low->getValue(),
8017                       Clusters[Last].High->getValue(), SI->getCondition(),
8018                       nullptr, false);
8019   JTCases.emplace_back(std::move(JTH), std::move(JT));
8020 
8021   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
8022                                      JTCases.size() - 1, Prob);
8023   return true;
8024 }
8025 
8026 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
8027                                          const SwitchInst *SI,
8028                                          MachineBasicBlock *DefaultMBB) {
8029 #ifndef NDEBUG
8030   // Clusters must be non-empty, sorted, and only contain Range clusters.
8031   assert(!Clusters.empty());
8032   for (CaseCluster &C : Clusters)
8033     assert(C.Kind == CC_Range);
8034   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
8035     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
8036 #endif
8037 
8038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8039   if (!areJTsAllowed(TLI))
8040     return;
8041 
8042   const int64_t N = Clusters.size();
8043   const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries();
8044 
8045   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
8046   SmallVector<unsigned, 8> TotalCases(N);
8047 
8048   for (unsigned i = 0; i < N; ++i) {
8049     APInt Hi = Clusters[i].High->getValue();
8050     APInt Lo = Clusters[i].Low->getValue();
8051     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
8052     if (i != 0)
8053       TotalCases[i] += TotalCases[i - 1];
8054   }
8055 
8056   if (N >= MinJumpTableSize && isDense(Clusters, &TotalCases[0], 0, N - 1)) {
8057     // Cheap case: the whole range might be suitable for jump table.
8058     CaseCluster JTCluster;
8059     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
8060       Clusters[0] = JTCluster;
8061       Clusters.resize(1);
8062       return;
8063     }
8064   }
8065 
8066   // The algorithm below is not suitable for -O0.
8067   if (TM.getOptLevel() == CodeGenOpt::None)
8068     return;
8069 
8070   // Split Clusters into minimum number of dense partitions. The algorithm uses
8071   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
8072   // for the Case Statement'" (1994), but builds the MinPartitions array in
8073   // reverse order to make it easier to reconstruct the partitions in ascending
8074   // order. In the choice between two optimal partitionings, it picks the one
8075   // which yields more jump tables.
8076 
8077   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
8078   SmallVector<unsigned, 8> MinPartitions(N);
8079   // LastElement[i] is the last element of the partition starting at i.
8080   SmallVector<unsigned, 8> LastElement(N);
8081   // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1].
8082   SmallVector<unsigned, 8> NumTables(N);
8083 
8084   // Base case: There is only one way to partition Clusters[N-1].
8085   MinPartitions[N - 1] = 1;
8086   LastElement[N - 1] = N - 1;
8087   assert(MinJumpTableSize > 1);
8088   NumTables[N - 1] = 0;
8089 
8090   // Note: loop indexes are signed to avoid underflow.
8091   for (int64_t i = N - 2; i >= 0; i--) {
8092     // Find optimal partitioning of Clusters[i..N-1].
8093     // Baseline: Put Clusters[i] into a partition on its own.
8094     MinPartitions[i] = MinPartitions[i + 1] + 1;
8095     LastElement[i] = i;
8096     NumTables[i] = NumTables[i + 1];
8097 
8098     // Search for a solution that results in fewer partitions.
8099     for (int64_t j = N - 1; j > i; j--) {
8100       // Try building a partition from Clusters[i..j].
8101       if (isDense(Clusters, &TotalCases[0], i, j)) {
8102         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8103         bool IsTable = j - i + 1 >= MinJumpTableSize;
8104         unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]);
8105 
8106         // If this j leads to fewer partitions, or same number of partitions
8107         // with more lookup tables, it is a better partitioning.
8108         if (NumPartitions < MinPartitions[i] ||
8109             (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) {
8110           MinPartitions[i] = NumPartitions;
8111           LastElement[i] = j;
8112           NumTables[i] = Tables;
8113         }
8114       }
8115     }
8116   }
8117 
8118   // Iterate over the partitions, replacing some with jump tables in-place.
8119   unsigned DstIndex = 0;
8120   for (unsigned First = 0, Last; First < N; First = Last + 1) {
8121     Last = LastElement[First];
8122     assert(Last >= First);
8123     assert(DstIndex <= First);
8124     unsigned NumClusters = Last - First + 1;
8125 
8126     CaseCluster JTCluster;
8127     if (NumClusters >= MinJumpTableSize &&
8128         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
8129       Clusters[DstIndex++] = JTCluster;
8130     } else {
8131       for (unsigned I = First; I <= Last; ++I)
8132         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
8133     }
8134   }
8135   Clusters.resize(DstIndex);
8136 }
8137 
8138 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
8139   // FIXME: Using the pointer type doesn't seem ideal.
8140   uint64_t BW = DAG.getDataLayout().getPointerSizeInBits();
8141   uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
8142   return Range <= BW;
8143 }
8144 
8145 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
8146                                                 unsigned NumCmps,
8147                                                 const APInt &Low,
8148                                                 const APInt &High) {
8149   // FIXME: I don't think NumCmps is the correct metric: a single case and a
8150   // range of cases both require only one branch to lower. Just looking at the
8151   // number of clusters and destinations should be enough to decide whether to
8152   // build bit tests.
8153 
8154   // To lower a range with bit tests, the range must fit the bitwidth of a
8155   // machine word.
8156   if (!rangeFitsInWord(Low, High))
8157     return false;
8158 
8159   // Decide whether it's profitable to lower this range with bit tests. Each
8160   // destination requires a bit test and branch, and there is an overall range
8161   // check branch. For a small number of clusters, separate comparisons might be
8162   // cheaper, and for many destinations, splitting the range might be better.
8163   return (NumDests == 1 && NumCmps >= 3) ||
8164          (NumDests == 2 && NumCmps >= 5) ||
8165          (NumDests == 3 && NumCmps >= 6);
8166 }
8167 
8168 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
8169                                         unsigned First, unsigned Last,
8170                                         const SwitchInst *SI,
8171                                         CaseCluster &BTCluster) {
8172   assert(First <= Last);
8173   if (First == Last)
8174     return false;
8175 
8176   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8177   unsigned NumCmps = 0;
8178   for (int64_t I = First; I <= Last; ++I) {
8179     assert(Clusters[I].Kind == CC_Range);
8180     Dests.set(Clusters[I].MBB->getNumber());
8181     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
8182   }
8183   unsigned NumDests = Dests.count();
8184 
8185   APInt Low = Clusters[First].Low->getValue();
8186   APInt High = Clusters[Last].High->getValue();
8187   assert(Low.slt(High));
8188 
8189   if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
8190     return false;
8191 
8192   APInt LowBound;
8193   APInt CmpRange;
8194 
8195   const int BitWidth = DAG.getTargetLoweringInfo()
8196                            .getPointerTy(DAG.getDataLayout())
8197                            .getSizeInBits();
8198   assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!");
8199 
8200   // Check if the clusters cover a contiguous range such that no value in the
8201   // range will jump to the default statement.
8202   bool ContiguousRange = true;
8203   for (int64_t I = First + 1; I <= Last; ++I) {
8204     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
8205       ContiguousRange = false;
8206       break;
8207     }
8208   }
8209 
8210   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
8211     // Optimize the case where all the case values fit in a word without having
8212     // to subtract minValue. In this case, we can optimize away the subtraction.
8213     LowBound = APInt::getNullValue(Low.getBitWidth());
8214     CmpRange = High;
8215     ContiguousRange = false;
8216   } else {
8217     LowBound = Low;
8218     CmpRange = High - Low;
8219   }
8220 
8221   CaseBitsVector CBV;
8222   auto TotalProb = BranchProbability::getZero();
8223   for (unsigned i = First; i <= Last; ++i) {
8224     // Find the CaseBits for this destination.
8225     unsigned j;
8226     for (j = 0; j < CBV.size(); ++j)
8227       if (CBV[j].BB == Clusters[i].MBB)
8228         break;
8229     if (j == CBV.size())
8230       CBV.push_back(
8231           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
8232     CaseBits *CB = &CBV[j];
8233 
8234     // Update Mask, Bits and ExtraProb.
8235     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
8236     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
8237     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
8238     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
8239     CB->Bits += Hi - Lo + 1;
8240     CB->ExtraProb += Clusters[i].Prob;
8241     TotalProb += Clusters[i].Prob;
8242   }
8243 
8244   BitTestInfo BTI;
8245   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
8246     // Sort by probability first, number of bits second.
8247     if (a.ExtraProb != b.ExtraProb)
8248       return a.ExtraProb > b.ExtraProb;
8249     return a.Bits > b.Bits;
8250   });
8251 
8252   for (auto &CB : CBV) {
8253     MachineBasicBlock *BitTestBB =
8254         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
8255     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
8256   }
8257   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
8258                             SI->getCondition(), -1U, MVT::Other, false,
8259                             ContiguousRange, nullptr, nullptr, std::move(BTI),
8260                             TotalProb);
8261 
8262   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
8263                                     BitTestCases.size() - 1, TotalProb);
8264   return true;
8265 }
8266 
8267 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
8268                                               const SwitchInst *SI) {
8269 // Partition Clusters into as few subsets as possible, where each subset has a
8270 // range that fits in a machine word and has <= 3 unique destinations.
8271 
8272 #ifndef NDEBUG
8273   // Clusters must be sorted and contain Range or JumpTable clusters.
8274   assert(!Clusters.empty());
8275   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
8276   for (const CaseCluster &C : Clusters)
8277     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
8278   for (unsigned i = 1; i < Clusters.size(); ++i)
8279     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
8280 #endif
8281 
8282   // The algorithm below is not suitable for -O0.
8283   if (TM.getOptLevel() == CodeGenOpt::None)
8284     return;
8285 
8286   // If target does not have legal shift left, do not emit bit tests at all.
8287   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8288   EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
8289   if (!TLI.isOperationLegal(ISD::SHL, PTy))
8290     return;
8291 
8292   int BitWidth = PTy.getSizeInBits();
8293   const int64_t N = Clusters.size();
8294 
8295   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
8296   SmallVector<unsigned, 8> MinPartitions(N);
8297   // LastElement[i] is the last element of the partition starting at i.
8298   SmallVector<unsigned, 8> LastElement(N);
8299 
8300   // FIXME: This might not be the best algorithm for finding bit test clusters.
8301 
8302   // Base case: There is only one way to partition Clusters[N-1].
8303   MinPartitions[N - 1] = 1;
8304   LastElement[N - 1] = N - 1;
8305 
8306   // Note: loop indexes are signed to avoid underflow.
8307   for (int64_t i = N - 2; i >= 0; --i) {
8308     // Find optimal partitioning of Clusters[i..N-1].
8309     // Baseline: Put Clusters[i] into a partition on its own.
8310     MinPartitions[i] = MinPartitions[i + 1] + 1;
8311     LastElement[i] = i;
8312 
8313     // Search for a solution that results in fewer partitions.
8314     // Note: the search is limited by BitWidth, reducing time complexity.
8315     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
8316       // Try building a partition from Clusters[i..j].
8317 
8318       // Check the range.
8319       if (!rangeFitsInWord(Clusters[i].Low->getValue(),
8320                            Clusters[j].High->getValue()))
8321         continue;
8322 
8323       // Check nbr of destinations and cluster types.
8324       // FIXME: This works, but doesn't seem very efficient.
8325       bool RangesOnly = true;
8326       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8327       for (int64_t k = i; k <= j; k++) {
8328         if (Clusters[k].Kind != CC_Range) {
8329           RangesOnly = false;
8330           break;
8331         }
8332         Dests.set(Clusters[k].MBB->getNumber());
8333       }
8334       if (!RangesOnly || Dests.count() > 3)
8335         break;
8336 
8337       // Check if it's a better partition.
8338       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8339       if (NumPartitions < MinPartitions[i]) {
8340         // Found a better partition.
8341         MinPartitions[i] = NumPartitions;
8342         LastElement[i] = j;
8343       }
8344     }
8345   }
8346 
8347   // Iterate over the partitions, replacing with bit-test clusters in-place.
8348   unsigned DstIndex = 0;
8349   for (unsigned First = 0, Last; First < N; First = Last + 1) {
8350     Last = LastElement[First];
8351     assert(First <= Last);
8352     assert(DstIndex <= First);
8353 
8354     CaseCluster BitTestCluster;
8355     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
8356       Clusters[DstIndex++] = BitTestCluster;
8357     } else {
8358       size_t NumClusters = Last - First + 1;
8359       std::memmove(&Clusters[DstIndex], &Clusters[First],
8360                    sizeof(Clusters[0]) * NumClusters);
8361       DstIndex += NumClusters;
8362     }
8363   }
8364   Clusters.resize(DstIndex);
8365 }
8366 
8367 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
8368                                         MachineBasicBlock *SwitchMBB,
8369                                         MachineBasicBlock *DefaultMBB) {
8370   MachineFunction *CurMF = FuncInfo.MF;
8371   MachineBasicBlock *NextMBB = nullptr;
8372   MachineFunction::iterator BBI(W.MBB);
8373   if (++BBI != FuncInfo.MF->end())
8374     NextMBB = &*BBI;
8375 
8376   unsigned Size = W.LastCluster - W.FirstCluster + 1;
8377 
8378   BranchProbabilityInfo *BPI = FuncInfo.BPI;
8379 
8380   if (Size == 2 && W.MBB == SwitchMBB) {
8381     // If any two of the cases has the same destination, and if one value
8382     // is the same as the other, but has one bit unset that the other has set,
8383     // use bit manipulation to do two compares at once.  For example:
8384     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
8385     // TODO: This could be extended to merge any 2 cases in switches with 3
8386     // cases.
8387     // TODO: Handle cases where W.CaseBB != SwitchBB.
8388     CaseCluster &Small = *W.FirstCluster;
8389     CaseCluster &Big = *W.LastCluster;
8390 
8391     if (Small.Low == Small.High && Big.Low == Big.High &&
8392         Small.MBB == Big.MBB) {
8393       const APInt &SmallValue = Small.Low->getValue();
8394       const APInt &BigValue = Big.Low->getValue();
8395 
8396       // Check that there is only one bit different.
8397       APInt CommonBit = BigValue ^ SmallValue;
8398       if (CommonBit.isPowerOf2()) {
8399         SDValue CondLHS = getValue(Cond);
8400         EVT VT = CondLHS.getValueType();
8401         SDLoc DL = getCurSDLoc();
8402 
8403         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
8404                                  DAG.getConstant(CommonBit, DL, VT));
8405         SDValue Cond = DAG.getSetCC(
8406             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
8407             ISD::SETEQ);
8408 
8409         // Update successor info.
8410         // Both Small and Big will jump to Small.BB, so we sum up the
8411         // probabilities.
8412         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
8413         if (BPI)
8414           addSuccessorWithProb(
8415               SwitchMBB, DefaultMBB,
8416               // The default destination is the first successor in IR.
8417               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
8418         else
8419           addSuccessorWithProb(SwitchMBB, DefaultMBB);
8420 
8421         // Insert the true branch.
8422         SDValue BrCond =
8423             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
8424                         DAG.getBasicBlock(Small.MBB));
8425         // Insert the false branch.
8426         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
8427                              DAG.getBasicBlock(DefaultMBB));
8428 
8429         DAG.setRoot(BrCond);
8430         return;
8431       }
8432     }
8433   }
8434 
8435   if (TM.getOptLevel() != CodeGenOpt::None) {
8436     // Order cases by probability so the most likely case will be checked first.
8437     std::sort(W.FirstCluster, W.LastCluster + 1,
8438               [](const CaseCluster &a, const CaseCluster &b) {
8439       return a.Prob > b.Prob;
8440     });
8441 
8442     // Rearrange the case blocks so that the last one falls through if possible
8443     // without without changing the order of probabilities.
8444     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
8445       --I;
8446       if (I->Prob > W.LastCluster->Prob)
8447         break;
8448       if (I->Kind == CC_Range && I->MBB == NextMBB) {
8449         std::swap(*I, *W.LastCluster);
8450         break;
8451       }
8452     }
8453   }
8454 
8455   // Compute total probability.
8456   BranchProbability DefaultProb = W.DefaultProb;
8457   BranchProbability UnhandledProbs = DefaultProb;
8458   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
8459     UnhandledProbs += I->Prob;
8460 
8461   MachineBasicBlock *CurMBB = W.MBB;
8462   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
8463     MachineBasicBlock *Fallthrough;
8464     if (I == W.LastCluster) {
8465       // For the last cluster, fall through to the default destination.
8466       Fallthrough = DefaultMBB;
8467     } else {
8468       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
8469       CurMF->insert(BBI, Fallthrough);
8470       // Put Cond in a virtual register to make it available from the new blocks.
8471       ExportFromCurrentBlock(Cond);
8472     }
8473     UnhandledProbs -= I->Prob;
8474 
8475     switch (I->Kind) {
8476       case CC_JumpTable: {
8477         // FIXME: Optimize away range check based on pivot comparisons.
8478         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
8479         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
8480 
8481         // The jump block hasn't been inserted yet; insert it here.
8482         MachineBasicBlock *JumpMBB = JT->MBB;
8483         CurMF->insert(BBI, JumpMBB);
8484 
8485         auto JumpProb = I->Prob;
8486         auto FallthroughProb = UnhandledProbs;
8487 
8488         // If the default statement is a target of the jump table, we evenly
8489         // distribute the default probability to successors of CurMBB. Also
8490         // update the probability on the edge from JumpMBB to Fallthrough.
8491         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
8492                                               SE = JumpMBB->succ_end();
8493              SI != SE; ++SI) {
8494           if (*SI == DefaultMBB) {
8495             JumpProb += DefaultProb / 2;
8496             FallthroughProb -= DefaultProb / 2;
8497             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
8498             JumpMBB->normalizeSuccProbs();
8499             break;
8500           }
8501         }
8502 
8503         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
8504         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
8505         CurMBB->normalizeSuccProbs();
8506 
8507         // The jump table header will be inserted in our current block, do the
8508         // range check, and fall through to our fallthrough block.
8509         JTH->HeaderBB = CurMBB;
8510         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
8511 
8512         // If we're in the right place, emit the jump table header right now.
8513         if (CurMBB == SwitchMBB) {
8514           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
8515           JTH->Emitted = true;
8516         }
8517         break;
8518       }
8519       case CC_BitTests: {
8520         // FIXME: Optimize away range check based on pivot comparisons.
8521         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
8522 
8523         // The bit test blocks haven't been inserted yet; insert them here.
8524         for (BitTestCase &BTC : BTB->Cases)
8525           CurMF->insert(BBI, BTC.ThisBB);
8526 
8527         // Fill in fields of the BitTestBlock.
8528         BTB->Parent = CurMBB;
8529         BTB->Default = Fallthrough;
8530 
8531         BTB->DefaultProb = UnhandledProbs;
8532         // If the cases in bit test don't form a contiguous range, we evenly
8533         // distribute the probability on the edge to Fallthrough to two
8534         // successors of CurMBB.
8535         if (!BTB->ContiguousRange) {
8536           BTB->Prob += DefaultProb / 2;
8537           BTB->DefaultProb -= DefaultProb / 2;
8538         }
8539 
8540         // If we're in the right place, emit the bit test header right now.
8541         if (CurMBB == SwitchMBB) {
8542           visitBitTestHeader(*BTB, SwitchMBB);
8543           BTB->Emitted = true;
8544         }
8545         break;
8546       }
8547       case CC_Range: {
8548         const Value *RHS, *LHS, *MHS;
8549         ISD::CondCode CC;
8550         if (I->Low == I->High) {
8551           // Check Cond == I->Low.
8552           CC = ISD::SETEQ;
8553           LHS = Cond;
8554           RHS=I->Low;
8555           MHS = nullptr;
8556         } else {
8557           // Check I->Low <= Cond <= I->High.
8558           CC = ISD::SETLE;
8559           LHS = I->Low;
8560           MHS = Cond;
8561           RHS = I->High;
8562         }
8563 
8564         // The false probability is the sum of all unhandled cases.
8565         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob,
8566                      UnhandledProbs);
8567 
8568         if (CurMBB == SwitchMBB)
8569           visitSwitchCase(CB, SwitchMBB);
8570         else
8571           SwitchCases.push_back(CB);
8572 
8573         break;
8574       }
8575     }
8576     CurMBB = Fallthrough;
8577   }
8578 }
8579 
8580 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
8581                                               CaseClusterIt First,
8582                                               CaseClusterIt Last) {
8583   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
8584     if (X.Prob != CC.Prob)
8585       return X.Prob > CC.Prob;
8586 
8587     // Ties are broken by comparing the case value.
8588     return X.Low->getValue().slt(CC.Low->getValue());
8589   });
8590 }
8591 
8592 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
8593                                         const SwitchWorkListItem &W,
8594                                         Value *Cond,
8595                                         MachineBasicBlock *SwitchMBB) {
8596   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
8597          "Clusters not sorted?");
8598 
8599   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
8600 
8601   // Balance the tree based on branch probabilities to create a near-optimal (in
8602   // terms of search time given key frequency) binary search tree. See e.g. Kurt
8603   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
8604   CaseClusterIt LastLeft = W.FirstCluster;
8605   CaseClusterIt FirstRight = W.LastCluster;
8606   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
8607   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
8608 
8609   // Move LastLeft and FirstRight towards each other from opposite directions to
8610   // find a partitioning of the clusters which balances the probability on both
8611   // sides. If LeftProb and RightProb are equal, alternate which side is
8612   // taken to ensure 0-probability nodes are distributed evenly.
8613   unsigned I = 0;
8614   while (LastLeft + 1 < FirstRight) {
8615     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
8616       LeftProb += (++LastLeft)->Prob;
8617     else
8618       RightProb += (--FirstRight)->Prob;
8619     I++;
8620   }
8621 
8622   for (;;) {
8623     // Our binary search tree differs from a typical BST in that ours can have up
8624     // to three values in each leaf. The pivot selection above doesn't take that
8625     // into account, which means the tree might require more nodes and be less
8626     // efficient. We compensate for this here.
8627 
8628     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
8629     unsigned NumRight = W.LastCluster - FirstRight + 1;
8630 
8631     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
8632       // If one side has less than 3 clusters, and the other has more than 3,
8633       // consider taking a cluster from the other side.
8634 
8635       if (NumLeft < NumRight) {
8636         // Consider moving the first cluster on the right to the left side.
8637         CaseCluster &CC = *FirstRight;
8638         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8639         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8640         if (LeftSideRank <= RightSideRank) {
8641           // Moving the cluster to the left does not demote it.
8642           ++LastLeft;
8643           ++FirstRight;
8644           continue;
8645         }
8646       } else {
8647         assert(NumRight < NumLeft);
8648         // Consider moving the last element on the left to the right side.
8649         CaseCluster &CC = *LastLeft;
8650         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8651         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8652         if (RightSideRank <= LeftSideRank) {
8653           // Moving the cluster to the right does not demot it.
8654           --LastLeft;
8655           --FirstRight;
8656           continue;
8657         }
8658       }
8659     }
8660     break;
8661   }
8662 
8663   assert(LastLeft + 1 == FirstRight);
8664   assert(LastLeft >= W.FirstCluster);
8665   assert(FirstRight <= W.LastCluster);
8666 
8667   // Use the first element on the right as pivot since we will make less-than
8668   // comparisons against it.
8669   CaseClusterIt PivotCluster = FirstRight;
8670   assert(PivotCluster > W.FirstCluster);
8671   assert(PivotCluster <= W.LastCluster);
8672 
8673   CaseClusterIt FirstLeft = W.FirstCluster;
8674   CaseClusterIt LastRight = W.LastCluster;
8675 
8676   const ConstantInt *Pivot = PivotCluster->Low;
8677 
8678   // New blocks will be inserted immediately after the current one.
8679   MachineFunction::iterator BBI(W.MBB);
8680   ++BBI;
8681 
8682   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
8683   // we can branch to its destination directly if it's squeezed exactly in
8684   // between the known lower bound and Pivot - 1.
8685   MachineBasicBlock *LeftMBB;
8686   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
8687       FirstLeft->Low == W.GE &&
8688       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
8689     LeftMBB = FirstLeft->MBB;
8690   } else {
8691     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8692     FuncInfo.MF->insert(BBI, LeftMBB);
8693     WorkList.push_back(
8694         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
8695     // Put Cond in a virtual register to make it available from the new blocks.
8696     ExportFromCurrentBlock(Cond);
8697   }
8698 
8699   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
8700   // single cluster, RHS.Low == Pivot, and we can branch to its destination
8701   // directly if RHS.High equals the current upper bound.
8702   MachineBasicBlock *RightMBB;
8703   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
8704       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
8705     RightMBB = FirstRight->MBB;
8706   } else {
8707     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8708     FuncInfo.MF->insert(BBI, RightMBB);
8709     WorkList.push_back(
8710         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
8711     // Put Cond in a virtual register to make it available from the new blocks.
8712     ExportFromCurrentBlock(Cond);
8713   }
8714 
8715   // Create the CaseBlock record that will be used to lower the branch.
8716   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
8717                LeftProb, RightProb);
8718 
8719   if (W.MBB == SwitchMBB)
8720     visitSwitchCase(CB, SwitchMBB);
8721   else
8722     SwitchCases.push_back(CB);
8723 }
8724 
8725 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
8726   // Extract cases from the switch.
8727   BranchProbabilityInfo *BPI = FuncInfo.BPI;
8728   CaseClusterVector Clusters;
8729   Clusters.reserve(SI.getNumCases());
8730   for (auto I : SI.cases()) {
8731     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
8732     const ConstantInt *CaseVal = I.getCaseValue();
8733     BranchProbability Prob =
8734         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
8735             : BranchProbability(1, SI.getNumCases() + 1);
8736     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
8737   }
8738 
8739   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
8740 
8741   // Cluster adjacent cases with the same destination. We do this at all
8742   // optimization levels because it's cheap to do and will make codegen faster
8743   // if there are many clusters.
8744   sortAndRangeify(Clusters);
8745 
8746   if (TM.getOptLevel() != CodeGenOpt::None) {
8747     // Replace an unreachable default with the most popular destination.
8748     // FIXME: Exploit unreachable default more aggressively.
8749     bool UnreachableDefault =
8750         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
8751     if (UnreachableDefault && !Clusters.empty()) {
8752       DenseMap<const BasicBlock *, unsigned> Popularity;
8753       unsigned MaxPop = 0;
8754       const BasicBlock *MaxBB = nullptr;
8755       for (auto I : SI.cases()) {
8756         const BasicBlock *BB = I.getCaseSuccessor();
8757         if (++Popularity[BB] > MaxPop) {
8758           MaxPop = Popularity[BB];
8759           MaxBB = BB;
8760         }
8761       }
8762       // Set new default.
8763       assert(MaxPop > 0 && MaxBB);
8764       DefaultMBB = FuncInfo.MBBMap[MaxBB];
8765 
8766       // Remove cases that were pointing to the destination that is now the
8767       // default.
8768       CaseClusterVector New;
8769       New.reserve(Clusters.size());
8770       for (CaseCluster &CC : Clusters) {
8771         if (CC.MBB != DefaultMBB)
8772           New.push_back(CC);
8773       }
8774       Clusters = std::move(New);
8775     }
8776   }
8777 
8778   // If there is only the default destination, jump there directly.
8779   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
8780   if (Clusters.empty()) {
8781     SwitchMBB->addSuccessor(DefaultMBB);
8782     if (DefaultMBB != NextBlock(SwitchMBB)) {
8783       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
8784                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
8785     }
8786     return;
8787   }
8788 
8789   findJumpTables(Clusters, &SI, DefaultMBB);
8790   findBitTestClusters(Clusters, &SI);
8791 
8792   DEBUG({
8793     dbgs() << "Case clusters: ";
8794     for (const CaseCluster &C : Clusters) {
8795       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
8796       if (C.Kind == CC_BitTests) dbgs() << "BT:";
8797 
8798       C.Low->getValue().print(dbgs(), true);
8799       if (C.Low != C.High) {
8800         dbgs() << '-';
8801         C.High->getValue().print(dbgs(), true);
8802       }
8803       dbgs() << ' ';
8804     }
8805     dbgs() << '\n';
8806   });
8807 
8808   assert(!Clusters.empty());
8809   SwitchWorkList WorkList;
8810   CaseClusterIt First = Clusters.begin();
8811   CaseClusterIt Last = Clusters.end() - 1;
8812   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
8813   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
8814 
8815   while (!WorkList.empty()) {
8816     SwitchWorkListItem W = WorkList.back();
8817     WorkList.pop_back();
8818     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
8819 
8820     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) {
8821       // For optimized builds, lower large range as a balanced binary tree.
8822       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
8823       continue;
8824     }
8825 
8826     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
8827   }
8828 }
8829