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