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