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, getCurSDLoc(), 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, getCurSDLoc(), 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, getCurSDLoc());
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 = CB.DL;
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     // Static allocas are handled more efficiently in the variable frame index
5106     // side table.
5107     if (const auto *AI =
5108             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets()))
5109       if (AI->isStaticAlloca() && FuncInfo.StaticAllocaMap.count(AI))
5110         return nullptr;
5111 
5112     // Byval arguments with frame indices were already handled after argument
5113     // lowering and before isel.
5114     if (const auto *Arg =
5115             dyn_cast<Argument>(Address->stripInBoundsConstantOffsets()))
5116       if (FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
5117         return nullptr;
5118 
5119     SDValue &N = NodeMap[Address];
5120     if (!N.getNode() && isa<Argument>(Address))
5121       // Check unused arguments map.
5122       N = UnusedArgNodeMap[Address];
5123     SDDbgValue *SDV;
5124     if (N.getNode()) {
5125       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5126         Address = BCI->getOperand(0);
5127       // Parameters are handled specially.
5128       bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5129       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5130       if (isParameter && FINode) {
5131         // Byval parameter. We have a frame index at this point.
5132         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5133                                         FINode->getIndex(), dl, SDNodeOrder);
5134       } else if (isa<Argument>(Address)) {
5135         // Address is an argument, so try to emit its dbg value using
5136         // virtual register info from the FuncInfo.ValueMap.
5137         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5138         return nullptr;
5139       } else {
5140         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5141                               true, dl, SDNodeOrder);
5142       }
5143       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5144     } else {
5145       // If Address is an argument then try to emit its dbg value using
5146       // virtual register info from the FuncInfo.ValueMap.
5147       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5148                                     N)) {
5149         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5150       }
5151     }
5152     return nullptr;
5153   }
5154   case Intrinsic::dbg_value: {
5155     const DbgValueInst &DI = cast<DbgValueInst>(I);
5156     assert(DI.getVariable() && "Missing variable");
5157 
5158     DILocalVariable *Variable = DI.getVariable();
5159     DIExpression *Expression = DI.getExpression();
5160     const Value *V = DI.getValue();
5161     if (!V)
5162       return nullptr;
5163 
5164     SDDbgValue *SDV;
5165     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5166       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5167       DAG.AddDbgValue(SDV, nullptr, false);
5168       return nullptr;
5169     }
5170 
5171     // Do not use getValue() in here; we don't want to generate code at
5172     // this point if it hasn't been done yet.
5173     SDValue N = NodeMap[V];
5174     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5175       N = UnusedArgNodeMap[V];
5176     if (N.getNode()) {
5177       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5178         return nullptr;
5179       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5180       DAG.AddDbgValue(SDV, N.getNode(), false);
5181       return nullptr;
5182     }
5183 
5184     if (!V->use_empty() ) {
5185       // Do not call getValue(V) yet, as we don't want to generate code.
5186       // Remember it for later.
5187       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
5188       DanglingDebugInfoMap[V] = DDI;
5189       return nullptr;
5190     }
5191 
5192     DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5193     DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5194     return nullptr;
5195   }
5196 
5197   case Intrinsic::eh_typeid_for: {
5198     // Find the type id for the given typeinfo.
5199     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5200     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5201     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5202     setValue(&I, Res);
5203     return nullptr;
5204   }
5205 
5206   case Intrinsic::eh_return_i32:
5207   case Intrinsic::eh_return_i64:
5208     DAG.getMachineFunction().setCallsEHReturn(true);
5209     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5210                             MVT::Other,
5211                             getControlRoot(),
5212                             getValue(I.getArgOperand(0)),
5213                             getValue(I.getArgOperand(1))));
5214     return nullptr;
5215   case Intrinsic::eh_unwind_init:
5216     DAG.getMachineFunction().setCallsUnwindInit(true);
5217     return nullptr;
5218   case Intrinsic::eh_dwarf_cfa: {
5219     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5220                              TLI.getPointerTy(DAG.getDataLayout()),
5221                              getValue(I.getArgOperand(0))));
5222     return nullptr;
5223   }
5224   case Intrinsic::eh_sjlj_callsite: {
5225     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5226     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5227     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5228     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5229 
5230     MMI.setCurrentCallSite(CI->getZExtValue());
5231     return nullptr;
5232   }
5233   case Intrinsic::eh_sjlj_functioncontext: {
5234     // Get and store the index of the function context.
5235     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5236     AllocaInst *FnCtx =
5237       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5238     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5239     MFI.setFunctionContextIndex(FI);
5240     return nullptr;
5241   }
5242   case Intrinsic::eh_sjlj_setjmp: {
5243     SDValue Ops[2];
5244     Ops[0] = getRoot();
5245     Ops[1] = getValue(I.getArgOperand(0));
5246     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5247                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5248     setValue(&I, Op.getValue(0));
5249     DAG.setRoot(Op.getValue(1));
5250     return nullptr;
5251   }
5252   case Intrinsic::eh_sjlj_longjmp: {
5253     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5254                             getRoot(), getValue(I.getArgOperand(0))));
5255     return nullptr;
5256   }
5257   case Intrinsic::eh_sjlj_setup_dispatch: {
5258     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5259                             getRoot()));
5260     return nullptr;
5261   }
5262 
5263   case Intrinsic::masked_gather:
5264     visitMaskedGather(I);
5265     return nullptr;
5266   case Intrinsic::masked_load:
5267     visitMaskedLoad(I);
5268     return nullptr;
5269   case Intrinsic::masked_scatter:
5270     visitMaskedScatter(I);
5271     return nullptr;
5272   case Intrinsic::masked_store:
5273     visitMaskedStore(I);
5274     return nullptr;
5275   case Intrinsic::masked_expandload:
5276     visitMaskedLoad(I, true /* IsExpanding */);
5277     return nullptr;
5278   case Intrinsic::masked_compressstore:
5279     visitMaskedStore(I, true /* IsCompressing */);
5280     return nullptr;
5281   case Intrinsic::x86_mmx_pslli_w:
5282   case Intrinsic::x86_mmx_pslli_d:
5283   case Intrinsic::x86_mmx_pslli_q:
5284   case Intrinsic::x86_mmx_psrli_w:
5285   case Intrinsic::x86_mmx_psrli_d:
5286   case Intrinsic::x86_mmx_psrli_q:
5287   case Intrinsic::x86_mmx_psrai_w:
5288   case Intrinsic::x86_mmx_psrai_d: {
5289     SDValue ShAmt = getValue(I.getArgOperand(1));
5290     if (isa<ConstantSDNode>(ShAmt)) {
5291       visitTargetIntrinsic(I, Intrinsic);
5292       return nullptr;
5293     }
5294     unsigned NewIntrinsic = 0;
5295     EVT ShAmtVT = MVT::v2i32;
5296     switch (Intrinsic) {
5297     case Intrinsic::x86_mmx_pslli_w:
5298       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5299       break;
5300     case Intrinsic::x86_mmx_pslli_d:
5301       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5302       break;
5303     case Intrinsic::x86_mmx_pslli_q:
5304       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5305       break;
5306     case Intrinsic::x86_mmx_psrli_w:
5307       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5308       break;
5309     case Intrinsic::x86_mmx_psrli_d:
5310       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5311       break;
5312     case Intrinsic::x86_mmx_psrli_q:
5313       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5314       break;
5315     case Intrinsic::x86_mmx_psrai_w:
5316       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5317       break;
5318     case Intrinsic::x86_mmx_psrai_d:
5319       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5320       break;
5321     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5322     }
5323 
5324     // The vector shift intrinsics with scalars uses 32b shift amounts but
5325     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5326     // to be zero.
5327     // We must do this early because v2i32 is not a legal type.
5328     SDValue ShOps[2];
5329     ShOps[0] = ShAmt;
5330     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5331     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5332     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5333     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5334     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5335                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5336                        getValue(I.getArgOperand(0)), ShAmt);
5337     setValue(&I, Res);
5338     return nullptr;
5339   }
5340   case Intrinsic::powi:
5341     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5342                             getValue(I.getArgOperand(1)), DAG));
5343     return nullptr;
5344   case Intrinsic::log:
5345     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5346     return nullptr;
5347   case Intrinsic::log2:
5348     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5349     return nullptr;
5350   case Intrinsic::log10:
5351     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5352     return nullptr;
5353   case Intrinsic::exp:
5354     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5355     return nullptr;
5356   case Intrinsic::exp2:
5357     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5358     return nullptr;
5359   case Intrinsic::pow:
5360     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5361                            getValue(I.getArgOperand(1)), DAG, TLI));
5362     return nullptr;
5363   case Intrinsic::sqrt:
5364   case Intrinsic::fabs:
5365   case Intrinsic::sin:
5366   case Intrinsic::cos:
5367   case Intrinsic::floor:
5368   case Intrinsic::ceil:
5369   case Intrinsic::trunc:
5370   case Intrinsic::rint:
5371   case Intrinsic::nearbyint:
5372   case Intrinsic::round:
5373   case Intrinsic::canonicalize: {
5374     unsigned Opcode;
5375     switch (Intrinsic) {
5376     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5377     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5378     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5379     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5380     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5381     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5382     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5383     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5384     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5385     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5386     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5387     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5388     }
5389 
5390     setValue(&I, DAG.getNode(Opcode, sdl,
5391                              getValue(I.getArgOperand(0)).getValueType(),
5392                              getValue(I.getArgOperand(0))));
5393     return nullptr;
5394   }
5395   case Intrinsic::minnum: {
5396     auto VT = getValue(I.getArgOperand(0)).getValueType();
5397     unsigned Opc =
5398         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5399             ? ISD::FMINNAN
5400             : ISD::FMINNUM;
5401     setValue(&I, DAG.getNode(Opc, sdl, VT,
5402                              getValue(I.getArgOperand(0)),
5403                              getValue(I.getArgOperand(1))));
5404     return nullptr;
5405   }
5406   case Intrinsic::maxnum: {
5407     auto VT = getValue(I.getArgOperand(0)).getValueType();
5408     unsigned Opc =
5409         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5410             ? ISD::FMAXNAN
5411             : ISD::FMAXNUM;
5412     setValue(&I, DAG.getNode(Opc, sdl, VT,
5413                              getValue(I.getArgOperand(0)),
5414                              getValue(I.getArgOperand(1))));
5415     return nullptr;
5416   }
5417   case Intrinsic::copysign:
5418     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5419                              getValue(I.getArgOperand(0)).getValueType(),
5420                              getValue(I.getArgOperand(0)),
5421                              getValue(I.getArgOperand(1))));
5422     return nullptr;
5423   case Intrinsic::fma:
5424     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5425                              getValue(I.getArgOperand(0)).getValueType(),
5426                              getValue(I.getArgOperand(0)),
5427                              getValue(I.getArgOperand(1)),
5428                              getValue(I.getArgOperand(2))));
5429     return nullptr;
5430   case Intrinsic::experimental_constrained_fadd:
5431   case Intrinsic::experimental_constrained_fsub:
5432   case Intrinsic::experimental_constrained_fmul:
5433   case Intrinsic::experimental_constrained_fdiv:
5434   case Intrinsic::experimental_constrained_frem:
5435   case Intrinsic::experimental_constrained_fma:
5436   case Intrinsic::experimental_constrained_sqrt:
5437   case Intrinsic::experimental_constrained_pow:
5438   case Intrinsic::experimental_constrained_powi:
5439   case Intrinsic::experimental_constrained_sin:
5440   case Intrinsic::experimental_constrained_cos:
5441   case Intrinsic::experimental_constrained_exp:
5442   case Intrinsic::experimental_constrained_exp2:
5443   case Intrinsic::experimental_constrained_log:
5444   case Intrinsic::experimental_constrained_log10:
5445   case Intrinsic::experimental_constrained_log2:
5446   case Intrinsic::experimental_constrained_rint:
5447   case Intrinsic::experimental_constrained_nearbyint:
5448     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5449     return nullptr;
5450   case Intrinsic::fmuladd: {
5451     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5452     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5453         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5454       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5455                                getValue(I.getArgOperand(0)).getValueType(),
5456                                getValue(I.getArgOperand(0)),
5457                                getValue(I.getArgOperand(1)),
5458                                getValue(I.getArgOperand(2))));
5459     } else {
5460       // TODO: Intrinsic calls should have fast-math-flags.
5461       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5462                                 getValue(I.getArgOperand(0)).getValueType(),
5463                                 getValue(I.getArgOperand(0)),
5464                                 getValue(I.getArgOperand(1)));
5465       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5466                                 getValue(I.getArgOperand(0)).getValueType(),
5467                                 Mul,
5468                                 getValue(I.getArgOperand(2)));
5469       setValue(&I, Add);
5470     }
5471     return nullptr;
5472   }
5473   case Intrinsic::convert_to_fp16:
5474     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5475                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5476                                          getValue(I.getArgOperand(0)),
5477                                          DAG.getTargetConstant(0, sdl,
5478                                                                MVT::i32))));
5479     return nullptr;
5480   case Intrinsic::convert_from_fp16:
5481     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5482                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5483                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5484                                          getValue(I.getArgOperand(0)))));
5485     return nullptr;
5486   case Intrinsic::pcmarker: {
5487     SDValue Tmp = getValue(I.getArgOperand(0));
5488     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5489     return nullptr;
5490   }
5491   case Intrinsic::readcyclecounter: {
5492     SDValue Op = getRoot();
5493     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5494                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5495     setValue(&I, Res);
5496     DAG.setRoot(Res.getValue(1));
5497     return nullptr;
5498   }
5499   case Intrinsic::bitreverse:
5500     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5501                              getValue(I.getArgOperand(0)).getValueType(),
5502                              getValue(I.getArgOperand(0))));
5503     return nullptr;
5504   case Intrinsic::bswap:
5505     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5506                              getValue(I.getArgOperand(0)).getValueType(),
5507                              getValue(I.getArgOperand(0))));
5508     return nullptr;
5509   case Intrinsic::cttz: {
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::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5514                              sdl, Ty, Arg));
5515     return nullptr;
5516   }
5517   case Intrinsic::ctlz: {
5518     SDValue Arg = getValue(I.getArgOperand(0));
5519     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5520     EVT Ty = Arg.getValueType();
5521     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5522                              sdl, Ty, Arg));
5523     return nullptr;
5524   }
5525   case Intrinsic::ctpop: {
5526     SDValue Arg = getValue(I.getArgOperand(0));
5527     EVT Ty = Arg.getValueType();
5528     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5529     return nullptr;
5530   }
5531   case Intrinsic::stacksave: {
5532     SDValue Op = getRoot();
5533     Res = DAG.getNode(
5534         ISD::STACKSAVE, sdl,
5535         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5536     setValue(&I, Res);
5537     DAG.setRoot(Res.getValue(1));
5538     return nullptr;
5539   }
5540   case Intrinsic::stackrestore: {
5541     Res = getValue(I.getArgOperand(0));
5542     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5543     return nullptr;
5544   }
5545   case Intrinsic::get_dynamic_area_offset: {
5546     SDValue Op = getRoot();
5547     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5548     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5549     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5550     // target.
5551     if (PtrTy != ResTy)
5552       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5553                          " intrinsic!");
5554     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5555                       Op);
5556     DAG.setRoot(Op);
5557     setValue(&I, Res);
5558     return nullptr;
5559   }
5560   case Intrinsic::stackguard: {
5561     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5562     MachineFunction &MF = DAG.getMachineFunction();
5563     const Module &M = *MF.getFunction()->getParent();
5564     SDValue Chain = getRoot();
5565     if (TLI.useLoadStackGuardNode()) {
5566       Res = getLoadStackGuard(DAG, sdl, Chain);
5567     } else {
5568       const Value *Global = TLI.getSDagStackGuard(M);
5569       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5570       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5571                         MachinePointerInfo(Global, 0), Align,
5572                         MachineMemOperand::MOVolatile);
5573     }
5574     DAG.setRoot(Chain);
5575     setValue(&I, Res);
5576     return nullptr;
5577   }
5578   case Intrinsic::stackprotector: {
5579     // Emit code into the DAG to store the stack guard onto the stack.
5580     MachineFunction &MF = DAG.getMachineFunction();
5581     MachineFrameInfo &MFI = MF.getFrameInfo();
5582     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5583     SDValue Src, Chain = getRoot();
5584 
5585     if (TLI.useLoadStackGuardNode())
5586       Src = getLoadStackGuard(DAG, sdl, Chain);
5587     else
5588       Src = getValue(I.getArgOperand(0));   // The guard's value.
5589 
5590     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5591 
5592     int FI = FuncInfo.StaticAllocaMap[Slot];
5593     MFI.setStackProtectorIndex(FI);
5594 
5595     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5596 
5597     // Store the stack protector onto the stack.
5598     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5599                                                  DAG.getMachineFunction(), FI),
5600                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5601     setValue(&I, Res);
5602     DAG.setRoot(Res);
5603     return nullptr;
5604   }
5605   case Intrinsic::objectsize: {
5606     // If we don't know by now, we're never going to know.
5607     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5608 
5609     assert(CI && "Non-constant type in __builtin_object_size?");
5610 
5611     SDValue Arg = getValue(I.getCalledValue());
5612     EVT Ty = Arg.getValueType();
5613 
5614     if (CI->isZero())
5615       Res = DAG.getConstant(-1ULL, sdl, Ty);
5616     else
5617       Res = DAG.getConstant(0, sdl, Ty);
5618 
5619     setValue(&I, Res);
5620     return nullptr;
5621   }
5622   case Intrinsic::annotation:
5623   case Intrinsic::ptr_annotation:
5624   case Intrinsic::invariant_group_barrier:
5625     // Drop the intrinsic, but forward the value
5626     setValue(&I, getValue(I.getOperand(0)));
5627     return nullptr;
5628   case Intrinsic::assume:
5629   case Intrinsic::var_annotation:
5630     // Discard annotate attributes and assumptions
5631     return nullptr;
5632 
5633   case Intrinsic::init_trampoline: {
5634     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5635 
5636     SDValue Ops[6];
5637     Ops[0] = getRoot();
5638     Ops[1] = getValue(I.getArgOperand(0));
5639     Ops[2] = getValue(I.getArgOperand(1));
5640     Ops[3] = getValue(I.getArgOperand(2));
5641     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5642     Ops[5] = DAG.getSrcValue(F);
5643 
5644     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5645 
5646     DAG.setRoot(Res);
5647     return nullptr;
5648   }
5649   case Intrinsic::adjust_trampoline: {
5650     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5651                              TLI.getPointerTy(DAG.getDataLayout()),
5652                              getValue(I.getArgOperand(0))));
5653     return nullptr;
5654   }
5655   case Intrinsic::gcroot: {
5656     MachineFunction &MF = DAG.getMachineFunction();
5657     const Function *F = MF.getFunction();
5658     (void)F;
5659     assert(F->hasGC() &&
5660            "only valid in functions with gc specified, enforced by Verifier");
5661     assert(GFI && "implied by previous");
5662     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5663     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5664 
5665     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5666     GFI->addStackRoot(FI->getIndex(), TypeMap);
5667     return nullptr;
5668   }
5669   case Intrinsic::gcread:
5670   case Intrinsic::gcwrite:
5671     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5672   case Intrinsic::flt_rounds:
5673     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5674     return nullptr;
5675 
5676   case Intrinsic::expect: {
5677     // Just replace __builtin_expect(exp, c) with EXP.
5678     setValue(&I, getValue(I.getArgOperand(0)));
5679     return nullptr;
5680   }
5681 
5682   case Intrinsic::debugtrap:
5683   case Intrinsic::trap: {
5684     StringRef TrapFuncName =
5685         I.getAttributes()
5686             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5687             .getValueAsString();
5688     if (TrapFuncName.empty()) {
5689       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5690         ISD::TRAP : ISD::DEBUGTRAP;
5691       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5692       return nullptr;
5693     }
5694     TargetLowering::ArgListTy Args;
5695 
5696     TargetLowering::CallLoweringInfo CLI(DAG);
5697     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5698         CallingConv::C, I.getType(),
5699         DAG.getExternalSymbol(TrapFuncName.data(),
5700                               TLI.getPointerTy(DAG.getDataLayout())),
5701         std::move(Args));
5702 
5703     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5704     DAG.setRoot(Result.second);
5705     return nullptr;
5706   }
5707 
5708   case Intrinsic::uadd_with_overflow:
5709   case Intrinsic::sadd_with_overflow:
5710   case Intrinsic::usub_with_overflow:
5711   case Intrinsic::ssub_with_overflow:
5712   case Intrinsic::umul_with_overflow:
5713   case Intrinsic::smul_with_overflow: {
5714     ISD::NodeType Op;
5715     switch (Intrinsic) {
5716     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5717     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5718     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5719     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5720     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5721     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5722     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5723     }
5724     SDValue Op1 = getValue(I.getArgOperand(0));
5725     SDValue Op2 = getValue(I.getArgOperand(1));
5726 
5727     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5728     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5729     return nullptr;
5730   }
5731   case Intrinsic::prefetch: {
5732     SDValue Ops[5];
5733     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5734     Ops[0] = getRoot();
5735     Ops[1] = getValue(I.getArgOperand(0));
5736     Ops[2] = getValue(I.getArgOperand(1));
5737     Ops[3] = getValue(I.getArgOperand(2));
5738     Ops[4] = getValue(I.getArgOperand(3));
5739     DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5740                                         DAG.getVTList(MVT::Other), Ops,
5741                                         EVT::getIntegerVT(*Context, 8),
5742                                         MachinePointerInfo(I.getArgOperand(0)),
5743                                         0, /* align */
5744                                         false, /* volatile */
5745                                         rw==0, /* read */
5746                                         rw==1)); /* write */
5747     return nullptr;
5748   }
5749   case Intrinsic::lifetime_start:
5750   case Intrinsic::lifetime_end: {
5751     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5752     // Stack coloring is not enabled in O0, discard region information.
5753     if (TM.getOptLevel() == CodeGenOpt::None)
5754       return nullptr;
5755 
5756     SmallVector<Value *, 4> Allocas;
5757     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5758 
5759     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5760            E = Allocas.end(); Object != E; ++Object) {
5761       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5762 
5763       // Could not find an Alloca.
5764       if (!LifetimeObject)
5765         continue;
5766 
5767       // First check that the Alloca is static, otherwise it won't have a
5768       // valid frame index.
5769       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5770       if (SI == FuncInfo.StaticAllocaMap.end())
5771         return nullptr;
5772 
5773       int FI = SI->second;
5774 
5775       SDValue Ops[2];
5776       Ops[0] = getRoot();
5777       Ops[1] =
5778           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
5779       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5780 
5781       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5782       DAG.setRoot(Res);
5783     }
5784     return nullptr;
5785   }
5786   case Intrinsic::invariant_start:
5787     // Discard region information.
5788     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5789     return nullptr;
5790   case Intrinsic::invariant_end:
5791     // Discard region information.
5792     return nullptr;
5793   case Intrinsic::clear_cache:
5794     return TLI.getClearCacheBuiltinName();
5795   case Intrinsic::donothing:
5796     // ignore
5797     return nullptr;
5798   case Intrinsic::experimental_stackmap: {
5799     visitStackmap(I);
5800     return nullptr;
5801   }
5802   case Intrinsic::experimental_patchpoint_void:
5803   case Intrinsic::experimental_patchpoint_i64: {
5804     visitPatchpoint(&I);
5805     return nullptr;
5806   }
5807   case Intrinsic::experimental_gc_statepoint: {
5808     LowerStatepoint(ImmutableStatepoint(&I));
5809     return nullptr;
5810   }
5811   case Intrinsic::experimental_gc_result: {
5812     visitGCResult(cast<GCResultInst>(I));
5813     return nullptr;
5814   }
5815   case Intrinsic::experimental_gc_relocate: {
5816     visitGCRelocate(cast<GCRelocateInst>(I));
5817     return nullptr;
5818   }
5819   case Intrinsic::instrprof_increment:
5820     llvm_unreachable("instrprof failed to lower an increment");
5821   case Intrinsic::instrprof_value_profile:
5822     llvm_unreachable("instrprof failed to lower a value profiling call");
5823   case Intrinsic::localescape: {
5824     MachineFunction &MF = DAG.getMachineFunction();
5825     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5826 
5827     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5828     // is the same on all targets.
5829     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5830       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5831       if (isa<ConstantPointerNull>(Arg))
5832         continue; // Skip null pointers. They represent a hole in index space.
5833       AllocaInst *Slot = cast<AllocaInst>(Arg);
5834       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5835              "can only escape static allocas");
5836       int FI = FuncInfo.StaticAllocaMap[Slot];
5837       MCSymbol *FrameAllocSym =
5838           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5839               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
5840       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5841               TII->get(TargetOpcode::LOCAL_ESCAPE))
5842           .addSym(FrameAllocSym)
5843           .addFrameIndex(FI);
5844     }
5845 
5846     return nullptr;
5847   }
5848 
5849   case Intrinsic::localrecover: {
5850     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5851     MachineFunction &MF = DAG.getMachineFunction();
5852     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5853 
5854     // Get the symbol that defines the frame offset.
5855     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5856     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5857     unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
5858     MCSymbol *FrameAllocSym =
5859         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5860             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
5861 
5862     // Create a MCSymbol for the label to avoid any target lowering
5863     // that would make this PC relative.
5864     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
5865     SDValue OffsetVal =
5866         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
5867 
5868     // Add the offset to the FP.
5869     Value *FP = I.getArgOperand(1);
5870     SDValue FPVal = getValue(FP);
5871     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5872     setValue(&I, Add);
5873 
5874     return nullptr;
5875   }
5876 
5877   case Intrinsic::eh_exceptionpointer:
5878   case Intrinsic::eh_exceptioncode: {
5879     // Get the exception pointer vreg, copy from it, and resize it to fit.
5880     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
5881     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
5882     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5883     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
5884     SDValue N =
5885         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5886     if (Intrinsic == Intrinsic::eh_exceptioncode)
5887       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5888     setValue(&I, N);
5889     return nullptr;
5890   }
5891   case Intrinsic::xray_customevent: {
5892     // Here we want to make sure that the intrinsic behaves as if it has a
5893     // specific calling convention, and only for x86_64.
5894     // FIXME: Support other platforms later.
5895     const auto &Triple = DAG.getTarget().getTargetTriple();
5896     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
5897       return nullptr;
5898 
5899     SDLoc DL = getCurSDLoc();
5900     SmallVector<SDValue, 8> Ops;
5901 
5902     // We want to say that we always want the arguments in registers.
5903     SDValue LogEntryVal = getValue(I.getArgOperand(0));
5904     SDValue StrSizeVal = getValue(I.getArgOperand(1));
5905     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5906     SDValue Chain = getRoot();
5907     Ops.push_back(LogEntryVal);
5908     Ops.push_back(StrSizeVal);
5909     Ops.push_back(Chain);
5910 
5911     // We need to enforce the calling convention for the callsite, so that
5912     // argument ordering is enforced correctly, and that register allocation can
5913     // see that some registers may be assumed clobbered and have to preserve
5914     // them across calls to the intrinsic.
5915     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
5916                                            DL, NodeTys, Ops);
5917     SDValue patchableNode = SDValue(MN, 0);
5918     DAG.setRoot(patchableNode);
5919     setValue(&I, patchableNode);
5920     return nullptr;
5921   }
5922   case Intrinsic::experimental_deoptimize:
5923     LowerDeoptimizeCall(&I);
5924     return nullptr;
5925 
5926   case Intrinsic::experimental_vector_reduce_fadd:
5927   case Intrinsic::experimental_vector_reduce_fmul:
5928   case Intrinsic::experimental_vector_reduce_add:
5929   case Intrinsic::experimental_vector_reduce_mul:
5930   case Intrinsic::experimental_vector_reduce_and:
5931   case Intrinsic::experimental_vector_reduce_or:
5932   case Intrinsic::experimental_vector_reduce_xor:
5933   case Intrinsic::experimental_vector_reduce_smax:
5934   case Intrinsic::experimental_vector_reduce_smin:
5935   case Intrinsic::experimental_vector_reduce_umax:
5936   case Intrinsic::experimental_vector_reduce_umin:
5937   case Intrinsic::experimental_vector_reduce_fmax:
5938   case Intrinsic::experimental_vector_reduce_fmin: {
5939     visitVectorReduce(I, Intrinsic);
5940     return nullptr;
5941   }
5942 
5943   }
5944 }
5945 
5946 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
5947     const ConstrainedFPIntrinsic &FPI) {
5948   SDLoc sdl = getCurSDLoc();
5949   unsigned Opcode;
5950   switch (FPI.getIntrinsicID()) {
5951   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5952   case Intrinsic::experimental_constrained_fadd:
5953     Opcode = ISD::STRICT_FADD;
5954     break;
5955   case Intrinsic::experimental_constrained_fsub:
5956     Opcode = ISD::STRICT_FSUB;
5957     break;
5958   case Intrinsic::experimental_constrained_fmul:
5959     Opcode = ISD::STRICT_FMUL;
5960     break;
5961   case Intrinsic::experimental_constrained_fdiv:
5962     Opcode = ISD::STRICT_FDIV;
5963     break;
5964   case Intrinsic::experimental_constrained_frem:
5965     Opcode = ISD::STRICT_FREM;
5966     break;
5967   case Intrinsic::experimental_constrained_fma:
5968     Opcode = ISD::STRICT_FMA;
5969     break;
5970   case Intrinsic::experimental_constrained_sqrt:
5971     Opcode = ISD::STRICT_FSQRT;
5972     break;
5973   case Intrinsic::experimental_constrained_pow:
5974     Opcode = ISD::STRICT_FPOW;
5975     break;
5976   case Intrinsic::experimental_constrained_powi:
5977     Opcode = ISD::STRICT_FPOWI;
5978     break;
5979   case Intrinsic::experimental_constrained_sin:
5980     Opcode = ISD::STRICT_FSIN;
5981     break;
5982   case Intrinsic::experimental_constrained_cos:
5983     Opcode = ISD::STRICT_FCOS;
5984     break;
5985   case Intrinsic::experimental_constrained_exp:
5986     Opcode = ISD::STRICT_FEXP;
5987     break;
5988   case Intrinsic::experimental_constrained_exp2:
5989     Opcode = ISD::STRICT_FEXP2;
5990     break;
5991   case Intrinsic::experimental_constrained_log:
5992     Opcode = ISD::STRICT_FLOG;
5993     break;
5994   case Intrinsic::experimental_constrained_log10:
5995     Opcode = ISD::STRICT_FLOG10;
5996     break;
5997   case Intrinsic::experimental_constrained_log2:
5998     Opcode = ISD::STRICT_FLOG2;
5999     break;
6000   case Intrinsic::experimental_constrained_rint:
6001     Opcode = ISD::STRICT_FRINT;
6002     break;
6003   case Intrinsic::experimental_constrained_nearbyint:
6004     Opcode = ISD::STRICT_FNEARBYINT;
6005     break;
6006   }
6007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6008   SDValue Chain = getRoot();
6009   SmallVector<EVT, 4> ValueVTs;
6010   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6011   ValueVTs.push_back(MVT::Other); // Out chain
6012 
6013   SDVTList VTs = DAG.getVTList(ValueVTs);
6014   SDValue Result;
6015   if (FPI.isUnaryOp())
6016     Result = DAG.getNode(Opcode, sdl, VTs,
6017                          { Chain, getValue(FPI.getArgOperand(0)) });
6018   else if (FPI.isTernaryOp())
6019     Result = DAG.getNode(Opcode, sdl, VTs,
6020                          { Chain, getValue(FPI.getArgOperand(0)),
6021                                   getValue(FPI.getArgOperand(1)),
6022                                   getValue(FPI.getArgOperand(2)) });
6023   else
6024     Result = DAG.getNode(Opcode, sdl, VTs,
6025                          { Chain, getValue(FPI.getArgOperand(0)),
6026                            getValue(FPI.getArgOperand(1))  });
6027 
6028   assert(Result.getNode()->getNumValues() == 2);
6029   SDValue OutChain = Result.getValue(1);
6030   DAG.setRoot(OutChain);
6031   SDValue FPResult = Result.getValue(0);
6032   setValue(&FPI, FPResult);
6033 }
6034 
6035 std::pair<SDValue, SDValue>
6036 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6037                                     const BasicBlock *EHPadBB) {
6038   MachineFunction &MF = DAG.getMachineFunction();
6039   MachineModuleInfo &MMI = MF.getMMI();
6040   MCSymbol *BeginLabel = nullptr;
6041 
6042   if (EHPadBB) {
6043     // Insert a label before the invoke call to mark the try range.  This can be
6044     // used to detect deletion of the invoke via the MachineModuleInfo.
6045     BeginLabel = MMI.getContext().createTempSymbol();
6046 
6047     // For SjLj, keep track of which landing pads go with which invokes
6048     // so as to maintain the ordering of pads in the LSDA.
6049     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6050     if (CallSiteIndex) {
6051       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6052       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6053 
6054       // Now that the call site is handled, stop tracking it.
6055       MMI.setCurrentCallSite(0);
6056     }
6057 
6058     // Both PendingLoads and PendingExports must be flushed here;
6059     // this call might not return.
6060     (void)getRoot();
6061     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6062 
6063     CLI.setChain(getRoot());
6064   }
6065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6066   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6067 
6068   assert((CLI.IsTailCall || Result.second.getNode()) &&
6069          "Non-null chain expected with non-tail call!");
6070   assert((Result.second.getNode() || !Result.first.getNode()) &&
6071          "Null value expected with tail call!");
6072 
6073   if (!Result.second.getNode()) {
6074     // As a special case, a null chain means that a tail call has been emitted
6075     // and the DAG root is already updated.
6076     HasTailCall = true;
6077 
6078     // Since there's no actual continuation from this block, nothing can be
6079     // relying on us setting vregs for them.
6080     PendingExports.clear();
6081   } else {
6082     DAG.setRoot(Result.second);
6083   }
6084 
6085   if (EHPadBB) {
6086     // Insert a label at the end of the invoke call to mark the try range.  This
6087     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6088     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6089     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6090 
6091     // Inform MachineModuleInfo of range.
6092     if (MF.hasEHFunclets()) {
6093       assert(CLI.CS);
6094       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6095       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6096                                 BeginLabel, EndLabel);
6097     } else {
6098       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6099     }
6100   }
6101 
6102   return Result;
6103 }
6104 
6105 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6106                                       bool isTailCall,
6107                                       const BasicBlock *EHPadBB) {
6108   auto &DL = DAG.getDataLayout();
6109   FunctionType *FTy = CS.getFunctionType();
6110   Type *RetTy = CS.getType();
6111 
6112   TargetLowering::ArgListTy Args;
6113   Args.reserve(CS.arg_size());
6114 
6115   const Value *SwiftErrorVal = nullptr;
6116   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6117 
6118   // We can't tail call inside a function with a swifterror argument. Lowering
6119   // does not support this yet. It would have to move into the swifterror
6120   // register before the call.
6121   auto *Caller = CS.getInstruction()->getParent()->getParent();
6122   if (TLI.supportSwiftError() &&
6123       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6124     isTailCall = false;
6125 
6126   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6127        i != e; ++i) {
6128     TargetLowering::ArgListEntry Entry;
6129     const Value *V = *i;
6130 
6131     // Skip empty types
6132     if (V->getType()->isEmptyTy())
6133       continue;
6134 
6135     SDValue ArgNode = getValue(V);
6136     Entry.Node = ArgNode; Entry.Ty = V->getType();
6137 
6138     Entry.setAttributes(&CS, i - CS.arg_begin());
6139 
6140     // Use swifterror virtual register as input to the call.
6141     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6142       SwiftErrorVal = V;
6143       // We find the virtual register for the actual swifterror argument.
6144       // Instead of using the Value, we use the virtual register instead.
6145       Entry.Node = DAG.getRegister(FuncInfo
6146                                        .getOrCreateSwiftErrorVRegUseAt(
6147                                            CS.getInstruction(), FuncInfo.MBB, V)
6148                                        .first,
6149                                    EVT(TLI.getPointerTy(DL)));
6150     }
6151 
6152     Args.push_back(Entry);
6153 
6154     // If we have an explicit sret argument that is an Instruction, (i.e., it
6155     // might point to function-local memory), we can't meaningfully tail-call.
6156     if (Entry.IsSRet && isa<Instruction>(V))
6157       isTailCall = false;
6158   }
6159 
6160   // Check if target-independent constraints permit a tail call here.
6161   // Target-dependent constraints are checked within TLI->LowerCallTo.
6162   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6163     isTailCall = false;
6164 
6165   // Disable tail calls if there is an swifterror argument. Targets have not
6166   // been updated to support tail calls.
6167   if (TLI.supportSwiftError() && SwiftErrorVal)
6168     isTailCall = false;
6169 
6170   TargetLowering::CallLoweringInfo CLI(DAG);
6171   CLI.setDebugLoc(getCurSDLoc())
6172       .setChain(getRoot())
6173       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6174       .setTailCall(isTailCall)
6175       .setConvergent(CS.isConvergent());
6176   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6177 
6178   if (Result.first.getNode()) {
6179     const Instruction *Inst = CS.getInstruction();
6180     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6181     setValue(Inst, Result.first);
6182   }
6183 
6184   // The last element of CLI.InVals has the SDValue for swifterror return.
6185   // Here we copy it to a virtual register and update SwiftErrorMap for
6186   // book-keeping.
6187   if (SwiftErrorVal && TLI.supportSwiftError()) {
6188     // Get the last element of InVals.
6189     SDValue Src = CLI.InVals.back();
6190     unsigned VReg; bool CreatedVReg;
6191     std::tie(VReg, CreatedVReg) =
6192         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6193     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6194     // We update the virtual register for the actual swifterror argument.
6195     if (CreatedVReg)
6196       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6197     DAG.setRoot(CopyNode);
6198   }
6199 }
6200 
6201 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6202                              SelectionDAGBuilder &Builder) {
6203 
6204   // Check to see if this load can be trivially constant folded, e.g. if the
6205   // input is from a string literal.
6206   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6207     // Cast pointer to the type we really want to load.
6208     Type *LoadTy =
6209         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6210     if (LoadVT.isVector())
6211       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6212 
6213     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6214                                          PointerType::getUnqual(LoadTy));
6215 
6216     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6217             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6218       return Builder.getValue(LoadCst);
6219   }
6220 
6221   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6222   // still constant memory, the input chain can be the entry node.
6223   SDValue Root;
6224   bool ConstantMemory = false;
6225 
6226   // Do not serialize (non-volatile) loads of constant memory with anything.
6227   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6228     Root = Builder.DAG.getEntryNode();
6229     ConstantMemory = true;
6230   } else {
6231     // Do not serialize non-volatile loads against each other.
6232     Root = Builder.DAG.getRoot();
6233   }
6234 
6235   SDValue Ptr = Builder.getValue(PtrVal);
6236   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6237                                         Ptr, MachinePointerInfo(PtrVal),
6238                                         /* Alignment = */ 1);
6239 
6240   if (!ConstantMemory)
6241     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6242   return LoadVal;
6243 }
6244 
6245 /// Record the value for an instruction that produces an integer result,
6246 /// converting the type where necessary.
6247 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6248                                                   SDValue Value,
6249                                                   bool IsSigned) {
6250   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6251                                                     I.getType(), true);
6252   if (IsSigned)
6253     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6254   else
6255     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6256   setValue(&I, Value);
6257 }
6258 
6259 /// See if we can lower a memcmp call into an optimized form. If so, return
6260 /// true and lower it. Otherwise return false, and it will be lowered like a
6261 /// normal call.
6262 /// The caller already checked that \p I calls the appropriate LibFunc with a
6263 /// correct prototype.
6264 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6265   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6266   const Value *Size = I.getArgOperand(2);
6267   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6268   if (CSize && CSize->getZExtValue() == 0) {
6269     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6270                                                           I.getType(), true);
6271     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6272     return true;
6273   }
6274 
6275   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6276   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6277       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6278       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6279   if (Res.first.getNode()) {
6280     processIntegerCallValue(I, Res.first, true);
6281     PendingLoads.push_back(Res.second);
6282     return true;
6283   }
6284 
6285   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6286   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6287   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6288     return false;
6289 
6290   // If the target has a fast compare for the given size, it will return a
6291   // preferred load type for that size. Require that the load VT is legal and
6292   // that the target supports unaligned loads of that type. Otherwise, return
6293   // INVALID.
6294   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6295     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6296     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6297     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6298       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6299       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6300       // TODO: Check alignment of src and dest ptrs.
6301       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6302       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6303       if (!TLI.isTypeLegal(LVT) ||
6304           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6305           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6306         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6307     }
6308 
6309     return LVT;
6310   };
6311 
6312   // This turns into unaligned loads. We only do this if the target natively
6313   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6314   // we'll only produce a small number of byte loads.
6315   MVT LoadVT;
6316   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6317   switch (NumBitsToCompare) {
6318   default:
6319     return false;
6320   case 16:
6321     LoadVT = MVT::i16;
6322     break;
6323   case 32:
6324     LoadVT = MVT::i32;
6325     break;
6326   case 64:
6327   case 128:
6328   case 256:
6329     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6330     break;
6331   }
6332 
6333   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6334     return false;
6335 
6336   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6337   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6338 
6339   // Bitcast to a wide integer type if the loads are vectors.
6340   if (LoadVT.isVector()) {
6341     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6342     LoadL = DAG.getBitcast(CmpVT, LoadL);
6343     LoadR = DAG.getBitcast(CmpVT, LoadR);
6344   }
6345 
6346   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6347   processIntegerCallValue(I, Cmp, false);
6348   return true;
6349 }
6350 
6351 /// See if we can lower a memchr call into an optimized form. If so, return
6352 /// true and lower it. Otherwise return false, and it will be lowered like a
6353 /// normal call.
6354 /// The caller already checked that \p I calls the appropriate LibFunc with a
6355 /// correct prototype.
6356 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6357   const Value *Src = I.getArgOperand(0);
6358   const Value *Char = I.getArgOperand(1);
6359   const Value *Length = I.getArgOperand(2);
6360 
6361   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6362   std::pair<SDValue, SDValue> Res =
6363     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6364                                 getValue(Src), getValue(Char), getValue(Length),
6365                                 MachinePointerInfo(Src));
6366   if (Res.first.getNode()) {
6367     setValue(&I, Res.first);
6368     PendingLoads.push_back(Res.second);
6369     return true;
6370   }
6371 
6372   return false;
6373 }
6374 
6375 /// See if we can lower a mempcpy call into an optimized form. If so, return
6376 /// true and lower it. Otherwise return false, and it will be lowered like a
6377 /// normal call.
6378 /// The caller already checked that \p I calls the appropriate LibFunc with a
6379 /// correct prototype.
6380 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6381   SDValue Dst = getValue(I.getArgOperand(0));
6382   SDValue Src = getValue(I.getArgOperand(1));
6383   SDValue Size = getValue(I.getArgOperand(2));
6384 
6385   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6386   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6387   unsigned Align = std::min(DstAlign, SrcAlign);
6388   if (Align == 0) // Alignment of one or both could not be inferred.
6389     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6390 
6391   bool isVol = false;
6392   SDLoc sdl = getCurSDLoc();
6393 
6394   // In the mempcpy context we need to pass in a false value for isTailCall
6395   // because the return pointer needs to be adjusted by the size of
6396   // the copied memory.
6397   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6398                              false, /*isTailCall=*/false,
6399                              MachinePointerInfo(I.getArgOperand(0)),
6400                              MachinePointerInfo(I.getArgOperand(1)));
6401   assert(MC.getNode() != nullptr &&
6402          "** memcpy should not be lowered as TailCall in mempcpy context **");
6403   DAG.setRoot(MC);
6404 
6405   // Check if Size needs to be truncated or extended.
6406   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6407 
6408   // Adjust return pointer to point just past the last dst byte.
6409   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6410                                     Dst, Size);
6411   setValue(&I, DstPlusSize);
6412   return true;
6413 }
6414 
6415 /// See if we can lower a strcpy call into an optimized form.  If so, return
6416 /// true and lower it, otherwise return false and it will be lowered like a
6417 /// normal call.
6418 /// The caller already checked that \p I calls the appropriate LibFunc with a
6419 /// correct prototype.
6420 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6421   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6422 
6423   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6424   std::pair<SDValue, SDValue> Res =
6425     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6426                                 getValue(Arg0), getValue(Arg1),
6427                                 MachinePointerInfo(Arg0),
6428                                 MachinePointerInfo(Arg1), isStpcpy);
6429   if (Res.first.getNode()) {
6430     setValue(&I, Res.first);
6431     DAG.setRoot(Res.second);
6432     return true;
6433   }
6434 
6435   return false;
6436 }
6437 
6438 /// See if we can lower a strcmp call into an optimized form.  If so, return
6439 /// true and lower it, otherwise return false and it will be lowered like a
6440 /// normal call.
6441 /// The caller already checked that \p I calls the appropriate LibFunc with a
6442 /// correct prototype.
6443 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6444   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6445 
6446   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6447   std::pair<SDValue, SDValue> Res =
6448     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6449                                 getValue(Arg0), getValue(Arg1),
6450                                 MachinePointerInfo(Arg0),
6451                                 MachinePointerInfo(Arg1));
6452   if (Res.first.getNode()) {
6453     processIntegerCallValue(I, Res.first, true);
6454     PendingLoads.push_back(Res.second);
6455     return true;
6456   }
6457 
6458   return false;
6459 }
6460 
6461 /// See if we can lower a strlen call into an optimized form.  If so, return
6462 /// true and lower it, otherwise return false and it will be lowered like a
6463 /// normal call.
6464 /// The caller already checked that \p I calls the appropriate LibFunc with a
6465 /// correct prototype.
6466 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6467   const Value *Arg0 = I.getArgOperand(0);
6468 
6469   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6470   std::pair<SDValue, SDValue> Res =
6471     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6472                                 getValue(Arg0), MachinePointerInfo(Arg0));
6473   if (Res.first.getNode()) {
6474     processIntegerCallValue(I, Res.first, false);
6475     PendingLoads.push_back(Res.second);
6476     return true;
6477   }
6478 
6479   return false;
6480 }
6481 
6482 /// See if we can lower a strnlen call into an optimized form.  If so, return
6483 /// true and lower it, otherwise return false and it will be lowered like a
6484 /// normal call.
6485 /// The caller already checked that \p I calls the appropriate LibFunc with a
6486 /// correct prototype.
6487 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6488   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6489 
6490   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6491   std::pair<SDValue, SDValue> Res =
6492     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6493                                  getValue(Arg0), getValue(Arg1),
6494                                  MachinePointerInfo(Arg0));
6495   if (Res.first.getNode()) {
6496     processIntegerCallValue(I, Res.first, false);
6497     PendingLoads.push_back(Res.second);
6498     return true;
6499   }
6500 
6501   return false;
6502 }
6503 
6504 /// See if we can lower a unary 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::visitUnaryFloatCall(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 Tmp = getValue(I.getArgOperand(0));
6516   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6517   return true;
6518 }
6519 
6520 /// See if we can lower a binary floating-point operation into an SDNode with
6521 /// the specified Opcode. If so, return true and lower it. Otherwise return
6522 /// false, and it will be lowered like a normal call.
6523 /// The caller already checked that \p I calls the appropriate LibFunc with a
6524 /// correct prototype.
6525 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6526                                                unsigned Opcode) {
6527   // We already checked this call's prototype; verify it doesn't modify errno.
6528   if (!I.onlyReadsMemory())
6529     return false;
6530 
6531   SDValue Tmp0 = getValue(I.getArgOperand(0));
6532   SDValue Tmp1 = getValue(I.getArgOperand(1));
6533   EVT VT = Tmp0.getValueType();
6534   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6535   return true;
6536 }
6537 
6538 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6539   // Handle inline assembly differently.
6540   if (isa<InlineAsm>(I.getCalledValue())) {
6541     visitInlineAsm(&I);
6542     return;
6543   }
6544 
6545   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6546   computeUsesVAFloatArgument(I, MMI);
6547 
6548   const char *RenameFn = nullptr;
6549   if (Function *F = I.getCalledFunction()) {
6550     if (F->isDeclaration()) {
6551       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6552         if (unsigned IID = II->getIntrinsicID(F)) {
6553           RenameFn = visitIntrinsicCall(I, IID);
6554           if (!RenameFn)
6555             return;
6556         }
6557       }
6558       if (Intrinsic::ID IID = F->getIntrinsicID()) {
6559         RenameFn = visitIntrinsicCall(I, IID);
6560         if (!RenameFn)
6561           return;
6562       }
6563     }
6564 
6565     // Check for well-known libc/libm calls.  If the function is internal, it
6566     // can't be a library call.  Don't do the check if marked as nobuiltin for
6567     // some reason or the call site requires strict floating point semantics.
6568     LibFunc Func;
6569     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6570         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6571         LibInfo->hasOptimizedCodeGen(Func)) {
6572       switch (Func) {
6573       default: break;
6574       case LibFunc_copysign:
6575       case LibFunc_copysignf:
6576       case LibFunc_copysignl:
6577         // We already checked this call's prototype; verify it doesn't modify
6578         // errno.
6579         if (I.onlyReadsMemory()) {
6580           SDValue LHS = getValue(I.getArgOperand(0));
6581           SDValue RHS = getValue(I.getArgOperand(1));
6582           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6583                                    LHS.getValueType(), LHS, RHS));
6584           return;
6585         }
6586         break;
6587       case LibFunc_fabs:
6588       case LibFunc_fabsf:
6589       case LibFunc_fabsl:
6590         if (visitUnaryFloatCall(I, ISD::FABS))
6591           return;
6592         break;
6593       case LibFunc_fmin:
6594       case LibFunc_fminf:
6595       case LibFunc_fminl:
6596         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6597           return;
6598         break;
6599       case LibFunc_fmax:
6600       case LibFunc_fmaxf:
6601       case LibFunc_fmaxl:
6602         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6603           return;
6604         break;
6605       case LibFunc_sin:
6606       case LibFunc_sinf:
6607       case LibFunc_sinl:
6608         if (visitUnaryFloatCall(I, ISD::FSIN))
6609           return;
6610         break;
6611       case LibFunc_cos:
6612       case LibFunc_cosf:
6613       case LibFunc_cosl:
6614         if (visitUnaryFloatCall(I, ISD::FCOS))
6615           return;
6616         break;
6617       case LibFunc_sqrt:
6618       case LibFunc_sqrtf:
6619       case LibFunc_sqrtl:
6620       case LibFunc_sqrt_finite:
6621       case LibFunc_sqrtf_finite:
6622       case LibFunc_sqrtl_finite:
6623         if (visitUnaryFloatCall(I, ISD::FSQRT))
6624           return;
6625         break;
6626       case LibFunc_floor:
6627       case LibFunc_floorf:
6628       case LibFunc_floorl:
6629         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6630           return;
6631         break;
6632       case LibFunc_nearbyint:
6633       case LibFunc_nearbyintf:
6634       case LibFunc_nearbyintl:
6635         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6636           return;
6637         break;
6638       case LibFunc_ceil:
6639       case LibFunc_ceilf:
6640       case LibFunc_ceill:
6641         if (visitUnaryFloatCall(I, ISD::FCEIL))
6642           return;
6643         break;
6644       case LibFunc_rint:
6645       case LibFunc_rintf:
6646       case LibFunc_rintl:
6647         if (visitUnaryFloatCall(I, ISD::FRINT))
6648           return;
6649         break;
6650       case LibFunc_round:
6651       case LibFunc_roundf:
6652       case LibFunc_roundl:
6653         if (visitUnaryFloatCall(I, ISD::FROUND))
6654           return;
6655         break;
6656       case LibFunc_trunc:
6657       case LibFunc_truncf:
6658       case LibFunc_truncl:
6659         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6660           return;
6661         break;
6662       case LibFunc_log2:
6663       case LibFunc_log2f:
6664       case LibFunc_log2l:
6665         if (visitUnaryFloatCall(I, ISD::FLOG2))
6666           return;
6667         break;
6668       case LibFunc_exp2:
6669       case LibFunc_exp2f:
6670       case LibFunc_exp2l:
6671         if (visitUnaryFloatCall(I, ISD::FEXP2))
6672           return;
6673         break;
6674       case LibFunc_memcmp:
6675         if (visitMemCmpCall(I))
6676           return;
6677         break;
6678       case LibFunc_mempcpy:
6679         if (visitMemPCpyCall(I))
6680           return;
6681         break;
6682       case LibFunc_memchr:
6683         if (visitMemChrCall(I))
6684           return;
6685         break;
6686       case LibFunc_strcpy:
6687         if (visitStrCpyCall(I, false))
6688           return;
6689         break;
6690       case LibFunc_stpcpy:
6691         if (visitStrCpyCall(I, true))
6692           return;
6693         break;
6694       case LibFunc_strcmp:
6695         if (visitStrCmpCall(I))
6696           return;
6697         break;
6698       case LibFunc_strlen:
6699         if (visitStrLenCall(I))
6700           return;
6701         break;
6702       case LibFunc_strnlen:
6703         if (visitStrNLenCall(I))
6704           return;
6705         break;
6706       }
6707     }
6708   }
6709 
6710   SDValue Callee;
6711   if (!RenameFn)
6712     Callee = getValue(I.getCalledValue());
6713   else
6714     Callee = DAG.getExternalSymbol(
6715         RenameFn,
6716         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6717 
6718   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6719   // have to do anything here to lower funclet bundles.
6720   assert(!I.hasOperandBundlesOtherThan(
6721              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6722          "Cannot lower calls with arbitrary operand bundles!");
6723 
6724   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6725     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6726   else
6727     // Check if we can potentially perform a tail call. More detailed checking
6728     // is be done within LowerCallTo, after more information about the call is
6729     // known.
6730     LowerCallTo(&I, Callee, I.isTailCall());
6731 }
6732 
6733 namespace {
6734 
6735 /// AsmOperandInfo - This contains information for each constraint that we are
6736 /// lowering.
6737 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6738 public:
6739   /// CallOperand - If this is the result output operand or a clobber
6740   /// this is null, otherwise it is the incoming operand to the CallInst.
6741   /// This gets modified as the asm is processed.
6742   SDValue CallOperand;
6743 
6744   /// AssignedRegs - If this is a register or register class operand, this
6745   /// contains the set of register corresponding to the operand.
6746   RegsForValue AssignedRegs;
6747 
6748   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6749     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6750   }
6751 
6752   /// Whether or not this operand accesses memory
6753   bool hasMemory(const TargetLowering &TLI) const {
6754     // Indirect operand accesses access memory.
6755     if (isIndirect)
6756       return true;
6757 
6758     for (const auto &Code : Codes)
6759       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
6760         return true;
6761 
6762     return false;
6763   }
6764 
6765   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6766   /// corresponds to.  If there is no Value* for this operand, it returns
6767   /// MVT::Other.
6768   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6769                            const DataLayout &DL) const {
6770     if (!CallOperandVal) return MVT::Other;
6771 
6772     if (isa<BasicBlock>(CallOperandVal))
6773       return TLI.getPointerTy(DL);
6774 
6775     llvm::Type *OpTy = CallOperandVal->getType();
6776 
6777     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6778     // If this is an indirect operand, the operand is a pointer to the
6779     // accessed type.
6780     if (isIndirect) {
6781       llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6782       if (!PtrTy)
6783         report_fatal_error("Indirect operand for inline asm not a pointer!");
6784       OpTy = PtrTy->getElementType();
6785     }
6786 
6787     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6788     if (StructType *STy = dyn_cast<StructType>(OpTy))
6789       if (STy->getNumElements() == 1)
6790         OpTy = STy->getElementType(0);
6791 
6792     // If OpTy is not a single value, it may be a struct/union that we
6793     // can tile with integers.
6794     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6795       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6796       switch (BitSize) {
6797       default: break;
6798       case 1:
6799       case 8:
6800       case 16:
6801       case 32:
6802       case 64:
6803       case 128:
6804         OpTy = IntegerType::get(Context, BitSize);
6805         break;
6806       }
6807     }
6808 
6809     return TLI.getValueType(DL, OpTy, true);
6810   }
6811 };
6812 
6813 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6814 
6815 } // end anonymous namespace
6816 
6817 /// Make sure that the output operand \p OpInfo and its corresponding input
6818 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
6819 /// out).
6820 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
6821                                SDISelAsmOperandInfo &MatchingOpInfo,
6822                                SelectionDAG &DAG) {
6823   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
6824     return;
6825 
6826   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6827   const auto &TLI = DAG.getTargetLoweringInfo();
6828 
6829   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6830       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6831                                        OpInfo.ConstraintVT);
6832   std::pair<unsigned, const TargetRegisterClass *> InputRC =
6833       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
6834                                        MatchingOpInfo.ConstraintVT);
6835   if ((OpInfo.ConstraintVT.isInteger() !=
6836        MatchingOpInfo.ConstraintVT.isInteger()) ||
6837       (MatchRC.second != InputRC.second)) {
6838     // FIXME: error out in a more elegant fashion
6839     report_fatal_error("Unsupported asm: input constraint"
6840                        " with a matching output constraint of"
6841                        " incompatible type!");
6842   }
6843   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
6844 }
6845 
6846 /// Get a direct memory input to behave well as an indirect operand.
6847 /// This may introduce stores, hence the need for a \p Chain.
6848 /// \return The (possibly updated) chain.
6849 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
6850                                         SDISelAsmOperandInfo &OpInfo,
6851                                         SelectionDAG &DAG) {
6852   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6853 
6854   // If we don't have an indirect input, put it in the constpool if we can,
6855   // otherwise spill it to a stack slot.
6856   // TODO: This isn't quite right. We need to handle these according to
6857   // the addressing mode that the constraint wants. Also, this may take
6858   // an additional register for the computation and we don't want that
6859   // either.
6860 
6861   // If the operand is a float, integer, or vector constant, spill to a
6862   // constant pool entry to get its address.
6863   const Value *OpVal = OpInfo.CallOperandVal;
6864   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6865       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6866     OpInfo.CallOperand = DAG.getConstantPool(
6867         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6868     return Chain;
6869   }
6870 
6871   // Otherwise, create a stack slot and emit a store to it before the asm.
6872   Type *Ty = OpVal->getType();
6873   auto &DL = DAG.getDataLayout();
6874   uint64_t TySize = DL.getTypeAllocSize(Ty);
6875   unsigned Align = DL.getPrefTypeAlignment(Ty);
6876   MachineFunction &MF = DAG.getMachineFunction();
6877   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
6878   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
6879   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
6880                        MachinePointerInfo::getFixedStack(MF, SSFI));
6881   OpInfo.CallOperand = StackSlot;
6882 
6883   return Chain;
6884 }
6885 
6886 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6887 /// specified operand.  We prefer to assign virtual registers, to allow the
6888 /// register allocator to handle the assignment process.  However, if the asm
6889 /// uses features that we can't model on machineinstrs, we have SDISel do the
6890 /// allocation.  This produces generally horrible, but correct, code.
6891 ///
6892 ///   OpInfo describes the operand.
6893 ///
6894 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
6895                                  const SDLoc &DL,
6896                                  SDISelAsmOperandInfo &OpInfo) {
6897   LLVMContext &Context = *DAG.getContext();
6898 
6899   MachineFunction &MF = DAG.getMachineFunction();
6900   SmallVector<unsigned, 4> Regs;
6901   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
6902 
6903   // If this is a constraint for a single physreg, or a constraint for a
6904   // register class, find it.
6905   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
6906       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
6907                                        OpInfo.ConstraintVT);
6908 
6909   unsigned NumRegs = 1;
6910   if (OpInfo.ConstraintVT != MVT::Other) {
6911     // If this is a FP input in an integer register (or visa versa) insert a bit
6912     // cast of the input value.  More generally, handle any case where the input
6913     // value disagrees with the register class we plan to stick this in.
6914     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
6915         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
6916       // Try to convert to the first EVT that the reg class contains.  If the
6917       // types are identical size, use a bitcast to convert (e.g. two differing
6918       // vector types).
6919       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
6920       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6921         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6922                                          RegVT, OpInfo.CallOperand);
6923         OpInfo.ConstraintVT = RegVT;
6924       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6925         // If the input is a FP value and we want it in FP registers, do a
6926         // bitcast to the corresponding integer type.  This turns an f64 value
6927         // into i64, which can be passed with two i32 values on a 32-bit
6928         // machine.
6929         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6930         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6931                                          RegVT, OpInfo.CallOperand);
6932         OpInfo.ConstraintVT = RegVT;
6933       }
6934     }
6935 
6936     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6937   }
6938 
6939   MVT RegVT;
6940   EVT ValueVT = OpInfo.ConstraintVT;
6941 
6942   // If this is a constraint for a specific physical register, like {r17},
6943   // assign it now.
6944   if (unsigned AssignedReg = PhysReg.first) {
6945     const TargetRegisterClass *RC = PhysReg.second;
6946     if (OpInfo.ConstraintVT == MVT::Other)
6947       ValueVT = *TRI.legalclasstypes_begin(*RC);
6948 
6949     // Get the actual register value type.  This is important, because the user
6950     // may have asked for (e.g.) the AX register in i32 type.  We need to
6951     // remember that AX is actually i16 to get the right extension.
6952     RegVT = *TRI.legalclasstypes_begin(*RC);
6953 
6954     // This is a explicit reference to a physical register.
6955     Regs.push_back(AssignedReg);
6956 
6957     // If this is an expanded reference, add the rest of the regs to Regs.
6958     if (NumRegs != 1) {
6959       TargetRegisterClass::iterator I = RC->begin();
6960       for (; *I != AssignedReg; ++I)
6961         assert(I != RC->end() && "Didn't find reg!");
6962 
6963       // Already added the first reg.
6964       --NumRegs; ++I;
6965       for (; NumRegs; --NumRegs, ++I) {
6966         assert(I != RC->end() && "Ran out of registers to allocate!");
6967         Regs.push_back(*I);
6968       }
6969     }
6970 
6971     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6972     return;
6973   }
6974 
6975   // Otherwise, if this was a reference to an LLVM register class, create vregs
6976   // for this reference.
6977   if (const TargetRegisterClass *RC = PhysReg.second) {
6978     RegVT = *TRI.legalclasstypes_begin(*RC);
6979     if (OpInfo.ConstraintVT == MVT::Other)
6980       ValueVT = RegVT;
6981 
6982     // Create the appropriate number of virtual registers.
6983     MachineRegisterInfo &RegInfo = MF.getRegInfo();
6984     for (; NumRegs; --NumRegs)
6985       Regs.push_back(RegInfo.createVirtualRegister(RC));
6986 
6987     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6988     return;
6989   }
6990 
6991   // Otherwise, we couldn't allocate enough registers for this.
6992 }
6993 
6994 static unsigned
6995 findMatchingInlineAsmOperand(unsigned OperandNo,
6996                              const std::vector<SDValue> &AsmNodeOperands) {
6997   // Scan until we find the definition we already emitted of this operand.
6998   unsigned CurOp = InlineAsm::Op_FirstOperand;
6999   for (; OperandNo; --OperandNo) {
7000     // Advance to the next operand.
7001     unsigned OpFlag =
7002         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7003     assert((InlineAsm::isRegDefKind(OpFlag) ||
7004             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7005             InlineAsm::isMemKind(OpFlag)) &&
7006            "Skipped past definitions?");
7007     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7008   }
7009   return CurOp;
7010 }
7011 
7012 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7013 /// \return true if it has succeeded, false otherwise
7014 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7015                               MVT RegVT, SelectionDAG &DAG) {
7016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7017   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7018   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7019     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7020       Regs.push_back(RegInfo.createVirtualRegister(RC));
7021     else
7022       return false;
7023   }
7024   return true;
7025 }
7026 
7027 namespace {
7028 class ExtraFlags {
7029   unsigned Flags = 0;
7030 
7031 public:
7032   explicit ExtraFlags(ImmutableCallSite CS) {
7033     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7034     if (IA->hasSideEffects())
7035       Flags |= InlineAsm::Extra_HasSideEffects;
7036     if (IA->isAlignStack())
7037       Flags |= InlineAsm::Extra_IsAlignStack;
7038     if (CS.isConvergent())
7039       Flags |= InlineAsm::Extra_IsConvergent;
7040     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7041   }
7042 
7043   void update(const llvm::TargetLowering::AsmOperandInfo &OpInfo) {
7044     // Ideally, we would only check against memory constraints.  However, the
7045     // meaning of an Other constraint can be target-specific and we can't easily
7046     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7047     // for Other constraints as well.
7048     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7049         OpInfo.ConstraintType == TargetLowering::C_Other) {
7050       if (OpInfo.Type == InlineAsm::isInput)
7051         Flags |= InlineAsm::Extra_MayLoad;
7052       else if (OpInfo.Type == InlineAsm::isOutput)
7053         Flags |= InlineAsm::Extra_MayStore;
7054       else if (OpInfo.Type == InlineAsm::isClobber)
7055         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7056     }
7057   }
7058 
7059   unsigned get() const { return Flags; }
7060 };
7061 } // namespace
7062 
7063 /// visitInlineAsm - Handle a call to an InlineAsm object.
7064 ///
7065 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7066   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7067 
7068   /// ConstraintOperands - Information about all of the constraints.
7069   SDISelAsmOperandInfoVector ConstraintOperands;
7070 
7071   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7072   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7073       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7074 
7075   bool hasMemory = false;
7076 
7077   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7078   ExtraFlags ExtraInfo(CS);
7079 
7080   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7081   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7082   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7083     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7084     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7085 
7086     MVT OpVT = MVT::Other;
7087 
7088     // Compute the value type for each operand.
7089     if (OpInfo.Type == InlineAsm::isInput ||
7090         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7091       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7092 
7093       // Process the call argument. BasicBlocks are labels, currently appearing
7094       // only in asm's.
7095       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7096         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7097       } else {
7098         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7099       }
7100 
7101       OpVT =
7102           OpInfo
7103               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7104               .getSimpleVT();
7105     }
7106 
7107     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7108       // The return value of the call is this value.  As such, there is no
7109       // corresponding argument.
7110       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7111       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7112         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7113                                       STy->getElementType(ResNo));
7114       } else {
7115         assert(ResNo == 0 && "Asm only has one result!");
7116         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7117       }
7118       ++ResNo;
7119     }
7120 
7121     OpInfo.ConstraintVT = OpVT;
7122 
7123     if (!hasMemory)
7124       hasMemory = OpInfo.hasMemory(TLI);
7125 
7126     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7127     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7128     auto TargetConstraint = TargetConstraints[i];
7129 
7130     // Compute the constraint code and ConstraintType to use.
7131     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7132 
7133     ExtraInfo.update(TargetConstraint);
7134   }
7135 
7136   SDValue Chain, Flag;
7137 
7138   // We won't need to flush pending loads if this asm doesn't touch
7139   // memory and is nonvolatile.
7140   if (hasMemory || IA->hasSideEffects())
7141     Chain = getRoot();
7142   else
7143     Chain = DAG.getRoot();
7144 
7145   // Second pass over the constraints: compute which constraint option to use
7146   // and assign registers to constraints that want a specific physreg.
7147   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7148     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7149 
7150     // If this is an output operand with a matching input operand, look up the
7151     // matching input. If their types mismatch, e.g. one is an integer, the
7152     // other is floating point, or their sizes are different, flag it as an
7153     // error.
7154     if (OpInfo.hasMatchingInput()) {
7155       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7156       patchMatchingInput(OpInfo, Input, DAG);
7157     }
7158 
7159     // Compute the constraint code and ConstraintType to use.
7160     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7161 
7162     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7163         OpInfo.Type == InlineAsm::isClobber)
7164       continue;
7165 
7166     // If this is a memory input, and if the operand is not indirect, do what we
7167     // need to to provide an address for the memory input.
7168     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7169         !OpInfo.isIndirect) {
7170       assert((OpInfo.isMultipleAlternative ||
7171               (OpInfo.Type == InlineAsm::isInput)) &&
7172              "Can only indirectify direct input operands!");
7173 
7174       // Memory operands really want the address of the value.
7175       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7176 
7177       // There is no longer a Value* corresponding to this operand.
7178       OpInfo.CallOperandVal = nullptr;
7179 
7180       // It is now an indirect operand.
7181       OpInfo.isIndirect = true;
7182     }
7183 
7184     // If this constraint is for a specific register, allocate it before
7185     // anything else.
7186     if (OpInfo.ConstraintType == TargetLowering::C_Register)
7187       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7188   }
7189 
7190   // Third pass - Loop over all of the operands, assigning virtual or physregs
7191   // to register class operands.
7192   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7193     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7194 
7195     // C_Register operands have already been allocated, Other/Memory don't need
7196     // to be.
7197     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7198       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7199   }
7200 
7201   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7202   std::vector<SDValue> AsmNodeOperands;
7203   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7204   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7205       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7206 
7207   // If we have a !srcloc metadata node associated with it, we want to attach
7208   // this to the ultimately generated inline asm machineinstr.  To do this, we
7209   // pass in the third operand as this (potentially null) inline asm MDNode.
7210   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7211   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7212 
7213   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7214   // bits as operand 3.
7215   AsmNodeOperands.push_back(DAG.getTargetConstant(
7216       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7217 
7218   // Loop over all of the inputs, copying the operand values into the
7219   // appropriate registers and processing the output regs.
7220   RegsForValue RetValRegs;
7221 
7222   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7223   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
7224 
7225   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7226     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7227 
7228     switch (OpInfo.Type) {
7229     case InlineAsm::isOutput: {
7230       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7231           OpInfo.ConstraintType != TargetLowering::C_Register) {
7232         // Memory output, or 'other' output (e.g. 'X' constraint).
7233         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7234 
7235         unsigned ConstraintID =
7236             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7237         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7238                "Failed to convert memory constraint code to constraint id.");
7239 
7240         // Add information to the INLINEASM node to know about this output.
7241         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7242         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7243         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7244                                                         MVT::i32));
7245         AsmNodeOperands.push_back(OpInfo.CallOperand);
7246         break;
7247       }
7248 
7249       // Otherwise, this is a register or register class output.
7250 
7251       // Copy the output from the appropriate register.  Find a register that
7252       // we can use.
7253       if (OpInfo.AssignedRegs.Regs.empty()) {
7254         emitInlineAsmError(
7255             CS, "couldn't allocate output register for constraint '" +
7256                     Twine(OpInfo.ConstraintCode) + "'");
7257         return;
7258       }
7259 
7260       // If this is an indirect operand, store through the pointer after the
7261       // asm.
7262       if (OpInfo.isIndirect) {
7263         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7264                                                       OpInfo.CallOperandVal));
7265       } else {
7266         // This is the result value of the call.
7267         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7268         // Concatenate this output onto the outputs list.
7269         RetValRegs.append(OpInfo.AssignedRegs);
7270       }
7271 
7272       // Add information to the INLINEASM node to know that this register is
7273       // set.
7274       OpInfo.AssignedRegs
7275           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7276                                     ? InlineAsm::Kind_RegDefEarlyClobber
7277                                     : InlineAsm::Kind_RegDef,
7278                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7279       break;
7280     }
7281     case InlineAsm::isInput: {
7282       SDValue InOperandVal = OpInfo.CallOperand;
7283 
7284       if (OpInfo.isMatchingInputConstraint()) {
7285         // If this is required to match an output register we have already set,
7286         // just use its register.
7287         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7288                                                   AsmNodeOperands);
7289         unsigned OpFlag =
7290           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7291         if (InlineAsm::isRegDefKind(OpFlag) ||
7292             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7293           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7294           if (OpInfo.isIndirect) {
7295             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7296             emitInlineAsmError(CS, "inline asm not supported yet:"
7297                                    " don't know how to handle tied "
7298                                    "indirect register inputs");
7299             return;
7300           }
7301 
7302           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7303           SmallVector<unsigned, 4> Regs;
7304 
7305           if (!createVirtualRegs(Regs,
7306                                  InlineAsm::getNumOperandRegisters(OpFlag),
7307                                  RegVT, DAG)) {
7308             emitInlineAsmError(CS, "inline asm error: This value type register "
7309                                    "class is not natively supported!");
7310             return;
7311           }
7312 
7313           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7314 
7315           SDLoc dl = getCurSDLoc();
7316           // Use the produced MatchedRegs object to
7317           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7318                                     CS.getInstruction());
7319           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7320                                            true, OpInfo.getMatchedOperand(), dl,
7321                                            DAG, AsmNodeOperands);
7322           break;
7323         }
7324 
7325         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7326         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7327                "Unexpected number of operands");
7328         // Add information to the INLINEASM node to know about this input.
7329         // See InlineAsm.h isUseOperandTiedToDef.
7330         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7331         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7332                                                     OpInfo.getMatchedOperand());
7333         AsmNodeOperands.push_back(DAG.getTargetConstant(
7334             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7335         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7336         break;
7337       }
7338 
7339       // Treat indirect 'X' constraint as memory.
7340       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7341           OpInfo.isIndirect)
7342         OpInfo.ConstraintType = TargetLowering::C_Memory;
7343 
7344       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7345         std::vector<SDValue> Ops;
7346         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7347                                           Ops, DAG);
7348         if (Ops.empty()) {
7349           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7350                                      Twine(OpInfo.ConstraintCode) + "'");
7351           return;
7352         }
7353 
7354         // Add information to the INLINEASM node to know about this input.
7355         unsigned ResOpType =
7356           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7357         AsmNodeOperands.push_back(DAG.getTargetConstant(
7358             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7359         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7360         break;
7361       }
7362 
7363       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7364         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7365         assert(InOperandVal.getValueType() ==
7366                    TLI.getPointerTy(DAG.getDataLayout()) &&
7367                "Memory operands expect pointer values");
7368 
7369         unsigned ConstraintID =
7370             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7371         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7372                "Failed to convert memory constraint code to constraint id.");
7373 
7374         // Add information to the INLINEASM node to know about this input.
7375         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7376         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7377         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7378                                                         getCurSDLoc(),
7379                                                         MVT::i32));
7380         AsmNodeOperands.push_back(InOperandVal);
7381         break;
7382       }
7383 
7384       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7385               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7386              "Unknown constraint type!");
7387 
7388       // TODO: Support this.
7389       if (OpInfo.isIndirect) {
7390         emitInlineAsmError(
7391             CS, "Don't know how to handle indirect register inputs yet "
7392                 "for constraint '" +
7393                     Twine(OpInfo.ConstraintCode) + "'");
7394         return;
7395       }
7396 
7397       // Copy the input into the appropriate registers.
7398       if (OpInfo.AssignedRegs.Regs.empty()) {
7399         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7400                                    Twine(OpInfo.ConstraintCode) + "'");
7401         return;
7402       }
7403 
7404       SDLoc dl = getCurSDLoc();
7405 
7406       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7407                                         Chain, &Flag, CS.getInstruction());
7408 
7409       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7410                                                dl, DAG, AsmNodeOperands);
7411       break;
7412     }
7413     case InlineAsm::isClobber: {
7414       // Add the clobbered value to the operand list, so that the register
7415       // allocator is aware that the physreg got clobbered.
7416       if (!OpInfo.AssignedRegs.Regs.empty())
7417         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7418                                                  false, 0, getCurSDLoc(), DAG,
7419                                                  AsmNodeOperands);
7420       break;
7421     }
7422     }
7423   }
7424 
7425   // Finish up input operands.  Set the input chain and add the flag last.
7426   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7427   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7428 
7429   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7430                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7431   Flag = Chain.getValue(1);
7432 
7433   // If this asm returns a register value, copy the result from that register
7434   // and set it as the value of the call.
7435   if (!RetValRegs.Regs.empty()) {
7436     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7437                                              Chain, &Flag, CS.getInstruction());
7438 
7439     // FIXME: Why don't we do this for inline asms with MRVs?
7440     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
7441       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7442 
7443       // If any of the results of the inline asm is a vector, it may have the
7444       // wrong width/num elts.  This can happen for register classes that can
7445       // contain multiple different value types.  The preg or vreg allocated may
7446       // not have the same VT as was expected.  Convert it to the right type
7447       // with bit_convert.
7448       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
7449         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
7450                           ResultType, Val);
7451 
7452       } else if (ResultType != Val.getValueType() &&
7453                  ResultType.isInteger() && Val.getValueType().isInteger()) {
7454         // If a result value was tied to an input value, the computed result may
7455         // have a wider width than the expected result.  Extract the relevant
7456         // portion.
7457         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
7458       }
7459 
7460       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
7461     }
7462 
7463     setValue(CS.getInstruction(), Val);
7464     // Don't need to use this as a chain in this case.
7465     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7466       return;
7467   }
7468 
7469   std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
7470 
7471   // Process indirect outputs, first output all of the flagged copies out of
7472   // physregs.
7473   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7474     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7475     const Value *Ptr = IndirectStoresToEmit[i].second;
7476     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7477                                              Chain, &Flag, IA);
7478     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7479   }
7480 
7481   // Emit the non-flagged stores from the physregs.
7482   SmallVector<SDValue, 8> OutChains;
7483   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7484     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7485                                getValue(StoresToEmit[i].second),
7486                                MachinePointerInfo(StoresToEmit[i].second));
7487     OutChains.push_back(Val);
7488   }
7489 
7490   if (!OutChains.empty())
7491     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7492 
7493   DAG.setRoot(Chain);
7494 }
7495 
7496 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7497                                              const Twine &Message) {
7498   LLVMContext &Ctx = *DAG.getContext();
7499   Ctx.emitError(CS.getInstruction(), Message);
7500 
7501   // Make sure we leave the DAG in a valid state
7502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7503   auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7504   setValue(CS.getInstruction(), DAG.getUNDEF(VT));
7505 }
7506 
7507 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7508   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7509                           MVT::Other, getRoot(),
7510                           getValue(I.getArgOperand(0)),
7511                           DAG.getSrcValue(I.getArgOperand(0))));
7512 }
7513 
7514 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7516   const DataLayout &DL = DAG.getDataLayout();
7517   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7518                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7519                            DAG.getSrcValue(I.getOperand(0)),
7520                            DL.getABITypeAlignment(I.getType()));
7521   setValue(&I, V);
7522   DAG.setRoot(V.getValue(1));
7523 }
7524 
7525 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7526   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7527                           MVT::Other, getRoot(),
7528                           getValue(I.getArgOperand(0)),
7529                           DAG.getSrcValue(I.getArgOperand(0))));
7530 }
7531 
7532 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7533   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7534                           MVT::Other, getRoot(),
7535                           getValue(I.getArgOperand(0)),
7536                           getValue(I.getArgOperand(1)),
7537                           DAG.getSrcValue(I.getArgOperand(0)),
7538                           DAG.getSrcValue(I.getArgOperand(1))));
7539 }
7540 
7541 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7542                                                     const Instruction &I,
7543                                                     SDValue Op) {
7544   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7545   if (!Range)
7546     return Op;
7547 
7548   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7549   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7550     return Op;
7551 
7552   APInt Lo = CR.getUnsignedMin();
7553   if (!Lo.isMinValue())
7554     return Op;
7555 
7556   APInt Hi = CR.getUnsignedMax();
7557   unsigned Bits = Hi.getActiveBits();
7558 
7559   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7560 
7561   SDLoc SL = getCurSDLoc();
7562 
7563   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7564                              DAG.getValueType(SmallVT));
7565   unsigned NumVals = Op.getNode()->getNumValues();
7566   if (NumVals == 1)
7567     return ZExt;
7568 
7569   SmallVector<SDValue, 4> Ops;
7570 
7571   Ops.push_back(ZExt);
7572   for (unsigned I = 1; I != NumVals; ++I)
7573     Ops.push_back(Op.getValue(I));
7574 
7575   return DAG.getMergeValues(Ops, SL);
7576 }
7577 
7578 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
7579 /// the call being lowered.
7580 ///
7581 /// This is a helper for lowering intrinsics that follow a target calling
7582 /// convention or require stack pointer adjustment. Only a subset of the
7583 /// intrinsic's operands need to participate in the calling convention.
7584 void SelectionDAGBuilder::populateCallLoweringInfo(
7585     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7586     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7587     bool IsPatchPoint) {
7588   TargetLowering::ArgListTy Args;
7589   Args.reserve(NumArgs);
7590 
7591   // Populate the argument list.
7592   // Attributes for args start at offset 1, after the return attribute.
7593   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7594        ArgI != ArgE; ++ArgI) {
7595     const Value *V = CS->getOperand(ArgI);
7596 
7597     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7598 
7599     TargetLowering::ArgListEntry Entry;
7600     Entry.Node = getValue(V);
7601     Entry.Ty = V->getType();
7602     Entry.setAttributes(&CS, ArgIdx);
7603     Args.push_back(Entry);
7604   }
7605 
7606   CLI.setDebugLoc(getCurSDLoc())
7607       .setChain(getRoot())
7608       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7609       .setDiscardResult(CS->use_empty())
7610       .setIsPatchPoint(IsPatchPoint);
7611 }
7612 
7613 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
7614 /// or patchpoint target node's operand list.
7615 ///
7616 /// Constants are converted to TargetConstants purely as an optimization to
7617 /// avoid constant materialization and register allocation.
7618 ///
7619 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7620 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
7621 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7622 /// address materialization and register allocation, but may also be required
7623 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7624 /// alloca in the entry block, then the runtime may assume that the alloca's
7625 /// StackMap location can be read immediately after compilation and that the
7626 /// location is valid at any point during execution (this is similar to the
7627 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7628 /// only available in a register, then the runtime would need to trap when
7629 /// execution reaches the StackMap in order to read the alloca's location.
7630 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7631                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
7632                                 SelectionDAGBuilder &Builder) {
7633   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7634     SDValue OpVal = Builder.getValue(CS.getArgument(i));
7635     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7636       Ops.push_back(
7637         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7638       Ops.push_back(
7639         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7640     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7641       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7642       Ops.push_back(Builder.DAG.getTargetFrameIndex(
7643           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
7644     } else
7645       Ops.push_back(OpVal);
7646   }
7647 }
7648 
7649 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7650 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7651   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7652   //                                  [live variables...])
7653 
7654   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7655 
7656   SDValue Chain, InFlag, Callee, NullPtr;
7657   SmallVector<SDValue, 32> Ops;
7658 
7659   SDLoc DL = getCurSDLoc();
7660   Callee = getValue(CI.getCalledValue());
7661   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7662 
7663   // The stackmap intrinsic only records the live variables (the arguemnts
7664   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7665   // intrinsic, this won't be lowered to a function call. This means we don't
7666   // have to worry about calling conventions and target specific lowering code.
7667   // Instead we perform the call lowering right here.
7668   //
7669   // chain, flag = CALLSEQ_START(chain, 0, 0)
7670   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7671   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7672   //
7673   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
7674   InFlag = Chain.getValue(1);
7675 
7676   // Add the <id> and <numBytes> constants.
7677   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7678   Ops.push_back(DAG.getTargetConstant(
7679                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7680   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7681   Ops.push_back(DAG.getTargetConstant(
7682                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7683                   MVT::i32));
7684 
7685   // Push live variables for the stack map.
7686   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7687 
7688   // We are not pushing any register mask info here on the operands list,
7689   // because the stackmap doesn't clobber anything.
7690 
7691   // Push the chain and the glue flag.
7692   Ops.push_back(Chain);
7693   Ops.push_back(InFlag);
7694 
7695   // Create the STACKMAP node.
7696   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7697   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7698   Chain = SDValue(SM, 0);
7699   InFlag = Chain.getValue(1);
7700 
7701   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7702 
7703   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7704 
7705   // Set the root to the target-lowered call chain.
7706   DAG.setRoot(Chain);
7707 
7708   // Inform the Frame Information that we have a stackmap in this function.
7709   FuncInfo.MF->getFrameInfo().setHasStackMap();
7710 }
7711 
7712 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7713 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7714                                           const BasicBlock *EHPadBB) {
7715   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7716   //                                                 i32 <numBytes>,
7717   //                                                 i8* <target>,
7718   //                                                 i32 <numArgs>,
7719   //                                                 [Args...],
7720   //                                                 [live variables...])
7721 
7722   CallingConv::ID CC = CS.getCallingConv();
7723   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7724   bool HasDef = !CS->getType()->isVoidTy();
7725   SDLoc dl = getCurSDLoc();
7726   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7727 
7728   // Handle immediate and symbolic callees.
7729   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7730     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7731                                    /*isTarget=*/true);
7732   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7733     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7734                                          SDLoc(SymbolicCallee),
7735                                          SymbolicCallee->getValueType(0));
7736 
7737   // Get the real number of arguments participating in the call <numArgs>
7738   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7739   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7740 
7741   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7742   // Intrinsics include all meta-operands up to but not including CC.
7743   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7744   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7745          "Not enough arguments provided to the patchpoint intrinsic");
7746 
7747   // For AnyRegCC the arguments are lowered later on manually.
7748   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7749   Type *ReturnTy =
7750     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7751 
7752   TargetLowering::CallLoweringInfo CLI(DAG);
7753   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7754                            true);
7755   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7756 
7757   SDNode *CallEnd = Result.second.getNode();
7758   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7759     CallEnd = CallEnd->getOperand(0).getNode();
7760 
7761   /// Get a call instruction from the call sequence chain.
7762   /// Tail calls are not allowed.
7763   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7764          "Expected a callseq node.");
7765   SDNode *Call = CallEnd->getOperand(0).getNode();
7766   bool HasGlue = Call->getGluedNode();
7767 
7768   // Replace the target specific call node with the patchable intrinsic.
7769   SmallVector<SDValue, 8> Ops;
7770 
7771   // Add the <id> and <numBytes> constants.
7772   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7773   Ops.push_back(DAG.getTargetConstant(
7774                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7775   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7776   Ops.push_back(DAG.getTargetConstant(
7777                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7778                   MVT::i32));
7779 
7780   // Add the callee.
7781   Ops.push_back(Callee);
7782 
7783   // Adjust <numArgs> to account for any arguments that have been passed on the
7784   // stack instead.
7785   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7786   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7787   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7788   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7789 
7790   // Add the calling convention
7791   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7792 
7793   // Add the arguments we omitted previously. The register allocator should
7794   // place these in any free register.
7795   if (IsAnyRegCC)
7796     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7797       Ops.push_back(getValue(CS.getArgument(i)));
7798 
7799   // Push the arguments from the call instruction up to the register mask.
7800   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7801   Ops.append(Call->op_begin() + 2, e);
7802 
7803   // Push live variables for the stack map.
7804   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
7805 
7806   // Push the register mask info.
7807   if (HasGlue)
7808     Ops.push_back(*(Call->op_end()-2));
7809   else
7810     Ops.push_back(*(Call->op_end()-1));
7811 
7812   // Push the chain (this is originally the first operand of the call, but
7813   // becomes now the last or second to last operand).
7814   Ops.push_back(*(Call->op_begin()));
7815 
7816   // Push the glue flag (last operand).
7817   if (HasGlue)
7818     Ops.push_back(*(Call->op_end()-1));
7819 
7820   SDVTList NodeTys;
7821   if (IsAnyRegCC && HasDef) {
7822     // Create the return types based on the intrinsic definition
7823     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7824     SmallVector<EVT, 3> ValueVTs;
7825     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7826     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7827 
7828     // There is always a chain and a glue type at the end
7829     ValueVTs.push_back(MVT::Other);
7830     ValueVTs.push_back(MVT::Glue);
7831     NodeTys = DAG.getVTList(ValueVTs);
7832   } else
7833     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7834 
7835   // Replace the target specific call node with a PATCHPOINT node.
7836   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7837                                          dl, NodeTys, Ops);
7838 
7839   // Update the NodeMap.
7840   if (HasDef) {
7841     if (IsAnyRegCC)
7842       setValue(CS.getInstruction(), SDValue(MN, 0));
7843     else
7844       setValue(CS.getInstruction(), Result.first);
7845   }
7846 
7847   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7848   // call sequence. Furthermore the location of the chain and glue can change
7849   // when the AnyReg calling convention is used and the intrinsic returns a
7850   // value.
7851   if (IsAnyRegCC && HasDef) {
7852     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7853     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7854     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7855   } else
7856     DAG.ReplaceAllUsesWith(Call, MN);
7857   DAG.DeleteNode(Call);
7858 
7859   // Inform the Frame Information that we have a patchpoint in this function.
7860   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
7861 }
7862 
7863 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
7864                                             unsigned Intrinsic) {
7865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7866   SDValue Op1 = getValue(I.getArgOperand(0));
7867   SDValue Op2;
7868   if (I.getNumArgOperands() > 1)
7869     Op2 = getValue(I.getArgOperand(1));
7870   SDLoc dl = getCurSDLoc();
7871   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7872   SDValue Res;
7873   FastMathFlags FMF;
7874   if (isa<FPMathOperator>(I))
7875     FMF = I.getFastMathFlags();
7876   SDNodeFlags SDFlags;
7877   SDFlags.setNoNaNs(FMF.noNaNs());
7878 
7879   switch (Intrinsic) {
7880   case Intrinsic::experimental_vector_reduce_fadd:
7881     if (FMF.unsafeAlgebra())
7882       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
7883     else
7884       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
7885     break;
7886   case Intrinsic::experimental_vector_reduce_fmul:
7887     if (FMF.unsafeAlgebra())
7888       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
7889     else
7890       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
7891     break;
7892   case Intrinsic::experimental_vector_reduce_add:
7893     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
7894     break;
7895   case Intrinsic::experimental_vector_reduce_mul:
7896     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
7897     break;
7898   case Intrinsic::experimental_vector_reduce_and:
7899     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
7900     break;
7901   case Intrinsic::experimental_vector_reduce_or:
7902     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
7903     break;
7904   case Intrinsic::experimental_vector_reduce_xor:
7905     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
7906     break;
7907   case Intrinsic::experimental_vector_reduce_smax:
7908     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
7909     break;
7910   case Intrinsic::experimental_vector_reduce_smin:
7911     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
7912     break;
7913   case Intrinsic::experimental_vector_reduce_umax:
7914     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
7915     break;
7916   case Intrinsic::experimental_vector_reduce_umin:
7917     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
7918     break;
7919   case Intrinsic::experimental_vector_reduce_fmax: {
7920     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
7921     break;
7922   }
7923   case Intrinsic::experimental_vector_reduce_fmin: {
7924     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
7925     break;
7926   }
7927   default:
7928     llvm_unreachable("Unhandled vector reduce intrinsic");
7929   }
7930   setValue(&I, Res);
7931 }
7932 
7933 /// Returns an AttributeList representing the attributes applied to the return
7934 /// value of the given call.
7935 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7936   SmallVector<Attribute::AttrKind, 2> Attrs;
7937   if (CLI.RetSExt)
7938     Attrs.push_back(Attribute::SExt);
7939   if (CLI.RetZExt)
7940     Attrs.push_back(Attribute::ZExt);
7941   if (CLI.IsInReg)
7942     Attrs.push_back(Attribute::InReg);
7943 
7944   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
7945                             Attrs);
7946 }
7947 
7948 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7949 /// implementation, which just calls LowerCall.
7950 /// FIXME: When all targets are
7951 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7952 std::pair<SDValue, SDValue>
7953 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7954   // Handle the incoming return values from the call.
7955   CLI.Ins.clear();
7956   Type *OrigRetTy = CLI.RetTy;
7957   SmallVector<EVT, 4> RetTys;
7958   SmallVector<uint64_t, 4> Offsets;
7959   auto &DL = CLI.DAG.getDataLayout();
7960   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
7961 
7962   if (CLI.IsPostTypeLegalization) {
7963     // If we are lowering a libcall after legalization, split the return type.
7964     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
7965     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
7966     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
7967       EVT RetVT = OldRetTys[i];
7968       uint64_t Offset = OldOffsets[i];
7969       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
7970       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
7971       unsigned RegisterVTSize = RegisterVT.getSizeInBits();
7972       RetTys.append(NumRegs, RegisterVT);
7973       for (unsigned j = 0; j != NumRegs; ++j)
7974         Offsets.push_back(Offset + j * RegisterVTSize);
7975     }
7976   }
7977 
7978   SmallVector<ISD::OutputArg, 4> Outs;
7979   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
7980 
7981   bool CanLowerReturn =
7982       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7983                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7984 
7985   SDValue DemoteStackSlot;
7986   int DemoteStackIdx = -100;
7987   if (!CanLowerReturn) {
7988     // FIXME: equivalent assert?
7989     // assert(!CS.hasInAllocaArgument() &&
7990     //        "sret demotion is incompatible with inalloca");
7991     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
7992     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
7993     MachineFunction &MF = CLI.DAG.getMachineFunction();
7994     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7995     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7996 
7997     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
7998     ArgListEntry Entry;
7999     Entry.Node = DemoteStackSlot;
8000     Entry.Ty = StackSlotPtrType;
8001     Entry.IsSExt = false;
8002     Entry.IsZExt = false;
8003     Entry.IsInReg = false;
8004     Entry.IsSRet = true;
8005     Entry.IsNest = false;
8006     Entry.IsByVal = false;
8007     Entry.IsReturned = false;
8008     Entry.IsSwiftSelf = false;
8009     Entry.IsSwiftError = false;
8010     Entry.Alignment = Align;
8011     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8012     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8013 
8014     // sret demotion isn't compatible with tail-calls, since the sret argument
8015     // points into the callers stack frame.
8016     CLI.IsTailCall = false;
8017   } else {
8018     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8019       EVT VT = RetTys[I];
8020       MVT RegisterVT =
8021           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8022       unsigned NumRegs =
8023           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8024       for (unsigned i = 0; i != NumRegs; ++i) {
8025         ISD::InputArg MyFlags;
8026         MyFlags.VT = RegisterVT;
8027         MyFlags.ArgVT = VT;
8028         MyFlags.Used = CLI.IsReturnValueUsed;
8029         if (CLI.RetSExt)
8030           MyFlags.Flags.setSExt();
8031         if (CLI.RetZExt)
8032           MyFlags.Flags.setZExt();
8033         if (CLI.IsInReg)
8034           MyFlags.Flags.setInReg();
8035         CLI.Ins.push_back(MyFlags);
8036       }
8037     }
8038   }
8039 
8040   // We push in swifterror return as the last element of CLI.Ins.
8041   ArgListTy &Args = CLI.getArgs();
8042   if (supportSwiftError()) {
8043     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8044       if (Args[i].IsSwiftError) {
8045         ISD::InputArg MyFlags;
8046         MyFlags.VT = getPointerTy(DL);
8047         MyFlags.ArgVT = EVT(getPointerTy(DL));
8048         MyFlags.Flags.setSwiftError();
8049         CLI.Ins.push_back(MyFlags);
8050       }
8051     }
8052   }
8053 
8054   // Handle all of the outgoing arguments.
8055   CLI.Outs.clear();
8056   CLI.OutVals.clear();
8057   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8058     SmallVector<EVT, 4> ValueVTs;
8059     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8060     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8061     Type *FinalType = Args[i].Ty;
8062     if (Args[i].IsByVal)
8063       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8064     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8065         FinalType, CLI.CallConv, CLI.IsVarArg);
8066     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8067          ++Value) {
8068       EVT VT = ValueVTs[Value];
8069       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8070       SDValue Op = SDValue(Args[i].Node.getNode(),
8071                            Args[i].Node.getResNo() + Value);
8072       ISD::ArgFlagsTy Flags;
8073 
8074       // Certain targets (such as MIPS), may have a different ABI alignment
8075       // for a type depending on the context. Give the target a chance to
8076       // specify the alignment it wants.
8077       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8078 
8079       if (Args[i].IsZExt)
8080         Flags.setZExt();
8081       if (Args[i].IsSExt)
8082         Flags.setSExt();
8083       if (Args[i].IsInReg) {
8084         // If we are using vectorcall calling convention, a structure that is
8085         // passed InReg - is surely an HVA
8086         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8087             isa<StructType>(FinalType)) {
8088           // The first value of a structure is marked
8089           if (0 == Value)
8090             Flags.setHvaStart();
8091           Flags.setHva();
8092         }
8093         // Set InReg Flag
8094         Flags.setInReg();
8095       }
8096       if (Args[i].IsSRet)
8097         Flags.setSRet();
8098       if (Args[i].IsSwiftSelf)
8099         Flags.setSwiftSelf();
8100       if (Args[i].IsSwiftError)
8101         Flags.setSwiftError();
8102       if (Args[i].IsByVal)
8103         Flags.setByVal();
8104       if (Args[i].IsInAlloca) {
8105         Flags.setInAlloca();
8106         // Set the byval flag for CCAssignFn callbacks that don't know about
8107         // inalloca.  This way we can know how many bytes we should've allocated
8108         // and how many bytes a callee cleanup function will pop.  If we port
8109         // inalloca to more targets, we'll have to add custom inalloca handling
8110         // in the various CC lowering callbacks.
8111         Flags.setByVal();
8112       }
8113       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8114         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8115         Type *ElementTy = Ty->getElementType();
8116         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8117         // For ByVal, alignment should come from FE.  BE will guess if this
8118         // info is not there but there are cases it cannot get right.
8119         unsigned FrameAlign;
8120         if (Args[i].Alignment)
8121           FrameAlign = Args[i].Alignment;
8122         else
8123           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8124         Flags.setByValAlign(FrameAlign);
8125       }
8126       if (Args[i].IsNest)
8127         Flags.setNest();
8128       if (NeedsRegBlock)
8129         Flags.setInConsecutiveRegs();
8130       Flags.setOrigAlign(OriginalAlignment);
8131 
8132       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8133       unsigned NumParts =
8134           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8135       SmallVector<SDValue, 4> Parts(NumParts);
8136       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8137 
8138       if (Args[i].IsSExt)
8139         ExtendKind = ISD::SIGN_EXTEND;
8140       else if (Args[i].IsZExt)
8141         ExtendKind = ISD::ZERO_EXTEND;
8142 
8143       // Conservatively only handle 'returned' on non-vectors for now
8144       if (Args[i].IsReturned && !Op.getValueType().isVector()) {
8145         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8146                "unexpected use of 'returned'");
8147         // Before passing 'returned' to the target lowering code, ensure that
8148         // either the register MVT and the actual EVT are the same size or that
8149         // the return value and argument are extended in the same way; in these
8150         // cases it's safe to pass the argument register value unchanged as the
8151         // return register value (although it's at the target's option whether
8152         // to do so)
8153         // TODO: allow code generation to take advantage of partially preserved
8154         // registers rather than clobbering the entire register when the
8155         // parameter extension method is not compatible with the return
8156         // extension method
8157         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8158             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8159              CLI.RetZExt == Args[i].IsZExt))
8160           Flags.setReturned();
8161       }
8162 
8163       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8164                      CLI.CS.getInstruction(), ExtendKind, true);
8165 
8166       for (unsigned j = 0; j != NumParts; ++j) {
8167         // if it isn't first piece, alignment must be 1
8168         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8169                                i < CLI.NumFixedArgs,
8170                                i, j*Parts[j].getValueType().getStoreSize());
8171         if (NumParts > 1 && j == 0)
8172           MyFlags.Flags.setSplit();
8173         else if (j != 0) {
8174           MyFlags.Flags.setOrigAlign(1);
8175           if (j == NumParts - 1)
8176             MyFlags.Flags.setSplitEnd();
8177         }
8178 
8179         CLI.Outs.push_back(MyFlags);
8180         CLI.OutVals.push_back(Parts[j]);
8181       }
8182 
8183       if (NeedsRegBlock && Value == NumValues - 1)
8184         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8185     }
8186   }
8187 
8188   SmallVector<SDValue, 4> InVals;
8189   CLI.Chain = LowerCall(CLI, InVals);
8190 
8191   // Update CLI.InVals to use outside of this function.
8192   CLI.InVals = InVals;
8193 
8194   // Verify that the target's LowerCall behaved as expected.
8195   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8196          "LowerCall didn't return a valid chain!");
8197   assert((!CLI.IsTailCall || InVals.empty()) &&
8198          "LowerCall emitted a return value for a tail call!");
8199   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8200          "LowerCall didn't emit the correct number of values!");
8201 
8202   // For a tail call, the return value is merely live-out and there aren't
8203   // any nodes in the DAG representing it. Return a special value to
8204   // indicate that a tail call has been emitted and no more Instructions
8205   // should be processed in the current block.
8206   if (CLI.IsTailCall) {
8207     CLI.DAG.setRoot(CLI.Chain);
8208     return std::make_pair(SDValue(), SDValue());
8209   }
8210 
8211 #ifndef NDEBUG
8212   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8213     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8214     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8215            "LowerCall emitted a value with the wrong type!");
8216   }
8217 #endif
8218 
8219   SmallVector<SDValue, 4> ReturnValues;
8220   if (!CanLowerReturn) {
8221     // The instruction result is the result of loading from the
8222     // hidden sret parameter.
8223     SmallVector<EVT, 1> PVTs;
8224     Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
8225 
8226     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8227     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8228     EVT PtrVT = PVTs[0];
8229 
8230     unsigned NumValues = RetTys.size();
8231     ReturnValues.resize(NumValues);
8232     SmallVector<SDValue, 4> Chains(NumValues);
8233 
8234     // An aggregate return value cannot wrap around the address space, so
8235     // offsets to its parts don't wrap either.
8236     SDNodeFlags Flags;
8237     Flags.setNoUnsignedWrap(true);
8238 
8239     for (unsigned i = 0; i < NumValues; ++i) {
8240       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8241                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8242                                                         PtrVT), Flags);
8243       SDValue L = CLI.DAG.getLoad(
8244           RetTys[i], CLI.DL, CLI.Chain, Add,
8245           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8246                                             DemoteStackIdx, Offsets[i]),
8247           /* Alignment = */ 1);
8248       ReturnValues[i] = L;
8249       Chains[i] = L.getValue(1);
8250     }
8251 
8252     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8253   } else {
8254     // Collect the legal value parts into potentially illegal values
8255     // that correspond to the original function's return values.
8256     Optional<ISD::NodeType> AssertOp;
8257     if (CLI.RetSExt)
8258       AssertOp = ISD::AssertSext;
8259     else if (CLI.RetZExt)
8260       AssertOp = ISD::AssertZext;
8261     unsigned CurReg = 0;
8262     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8263       EVT VT = RetTys[I];
8264       MVT RegisterVT =
8265           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8266       unsigned NumRegs =
8267           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8268 
8269       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8270                                               NumRegs, RegisterVT, VT, nullptr,
8271                                               AssertOp, true));
8272       CurReg += NumRegs;
8273     }
8274 
8275     // For a function returning void, there is no return value. We can't create
8276     // such a node, so we just return a null return value in that case. In
8277     // that case, nothing will actually look at the value.
8278     if (ReturnValues.empty())
8279       return std::make_pair(SDValue(), CLI.Chain);
8280   }
8281 
8282   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8283                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8284   return std::make_pair(Res, CLI.Chain);
8285 }
8286 
8287 void TargetLowering::LowerOperationWrapper(SDNode *N,
8288                                            SmallVectorImpl<SDValue> &Results,
8289                                            SelectionDAG &DAG) const {
8290   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8291     Results.push_back(Res);
8292 }
8293 
8294 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8295   llvm_unreachable("LowerOperation not implemented for this target!");
8296 }
8297 
8298 void
8299 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8300   SDValue Op = getNonRegisterValue(V);
8301   assert((Op.getOpcode() != ISD::CopyFromReg ||
8302           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8303          "Copy from a reg to the same reg!");
8304   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8305 
8306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8307   // If this is an InlineAsm we have to match the registers required, not the
8308   // notional registers required by the type.
8309 
8310   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
8311                    V->getType(), isABIRegCopy(V));
8312   SDValue Chain = DAG.getEntryNode();
8313 
8314   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8315                               FuncInfo.PreferredExtendType.end())
8316                                  ? ISD::ANY_EXTEND
8317                                  : FuncInfo.PreferredExtendType[V];
8318   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8319   PendingExports.push_back(Chain);
8320 }
8321 
8322 #include "llvm/CodeGen/SelectionDAGISel.h"
8323 
8324 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8325 /// entry block, return true.  This includes arguments used by switches, since
8326 /// the switch may expand into multiple basic blocks.
8327 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8328   // With FastISel active, we may be splitting blocks, so force creation
8329   // of virtual registers for all non-dead arguments.
8330   if (FastISel)
8331     return A->use_empty();
8332 
8333   const BasicBlock &Entry = A->getParent()->front();
8334   for (const User *U : A->users())
8335     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8336       return false;  // Use not in entry block.
8337 
8338   return true;
8339 }
8340 
8341 typedef DenseMap<const Argument *,
8342                  std::pair<const AllocaInst *, const StoreInst *>>
8343     ArgCopyElisionMapTy;
8344 
8345 /// Scan the entry block of the function in FuncInfo for arguments that look
8346 /// like copies into a local alloca. Record any copied arguments in
8347 /// ArgCopyElisionCandidates.
8348 static void
8349 findArgumentCopyElisionCandidates(const DataLayout &DL,
8350                                   FunctionLoweringInfo *FuncInfo,
8351                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8352   // Record the state of every static alloca used in the entry block. Argument
8353   // allocas are all used in the entry block, so we need approximately as many
8354   // entries as we have arguments.
8355   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8356   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8357   unsigned NumArgs = FuncInfo->Fn->arg_size();
8358   StaticAllocas.reserve(NumArgs * 2);
8359 
8360   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8361     if (!V)
8362       return nullptr;
8363     V = V->stripPointerCasts();
8364     const auto *AI = dyn_cast<AllocaInst>(V);
8365     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8366       return nullptr;
8367     auto Iter = StaticAllocas.insert({AI, Unknown});
8368     return &Iter.first->second;
8369   };
8370 
8371   // Look for stores of arguments to static allocas. Look through bitcasts and
8372   // GEPs to handle type coercions, as long as the alloca is fully initialized
8373   // by the store. Any non-store use of an alloca escapes it and any subsequent
8374   // unanalyzed store might write it.
8375   // FIXME: Handle structs initialized with multiple stores.
8376   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8377     // Look for stores, and handle non-store uses conservatively.
8378     const auto *SI = dyn_cast<StoreInst>(&I);
8379     if (!SI) {
8380       // We will look through cast uses, so ignore them completely.
8381       if (I.isCast())
8382         continue;
8383       // Ignore debug info intrinsics, they don't escape or store to allocas.
8384       if (isa<DbgInfoIntrinsic>(I))
8385         continue;
8386       // This is an unknown instruction. Assume it escapes or writes to all
8387       // static alloca operands.
8388       for (const Use &U : I.operands()) {
8389         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8390           *Info = StaticAllocaInfo::Clobbered;
8391       }
8392       continue;
8393     }
8394 
8395     // If the stored value is a static alloca, mark it as escaped.
8396     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8397       *Info = StaticAllocaInfo::Clobbered;
8398 
8399     // Check if the destination is a static alloca.
8400     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8401     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8402     if (!Info)
8403       continue;
8404     const AllocaInst *AI = cast<AllocaInst>(Dst);
8405 
8406     // Skip allocas that have been initialized or clobbered.
8407     if (*Info != StaticAllocaInfo::Unknown)
8408       continue;
8409 
8410     // Check if the stored value is an argument, and that this store fully
8411     // initializes the alloca. Don't elide copies from the same argument twice.
8412     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8413     const auto *Arg = dyn_cast<Argument>(Val);
8414     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8415         Arg->getType()->isEmptyTy() ||
8416         DL.getTypeStoreSize(Arg->getType()) !=
8417             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8418         ArgCopyElisionCandidates.count(Arg)) {
8419       *Info = StaticAllocaInfo::Clobbered;
8420       continue;
8421     }
8422 
8423     DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
8424 
8425     // Mark this alloca and store for argument copy elision.
8426     *Info = StaticAllocaInfo::Elidable;
8427     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8428 
8429     // Stop scanning if we've seen all arguments. This will happen early in -O0
8430     // builds, which is useful, because -O0 builds have large entry blocks and
8431     // many allocas.
8432     if (ArgCopyElisionCandidates.size() == NumArgs)
8433       break;
8434   }
8435 }
8436 
8437 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8438 /// ArgVal is a load from a suitable fixed stack object.
8439 static void tryToElideArgumentCopy(
8440     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8441     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8442     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8443     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8444     SDValue ArgVal, bool &ArgHasUses) {
8445   // Check if this is a load from a fixed stack object.
8446   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8447   if (!LNode)
8448     return;
8449   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8450   if (!FINode)
8451     return;
8452 
8453   // Check that the fixed stack object is the right size and alignment.
8454   // Look at the alignment that the user wrote on the alloca instead of looking
8455   // at the stack object.
8456   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8457   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8458   const AllocaInst *AI = ArgCopyIter->second.first;
8459   int FixedIndex = FINode->getIndex();
8460   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8461   int OldIndex = AllocaIndex;
8462   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8463   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8464     DEBUG(dbgs() << "  argument copy elision failed due to bad fixed stack "
8465                     "object size\n");
8466     return;
8467   }
8468   unsigned RequiredAlignment = AI->getAlignment();
8469   if (!RequiredAlignment) {
8470     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8471         AI->getAllocatedType());
8472   }
8473   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8474     DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8475                     "greater than stack argument alignment ("
8476                  << RequiredAlignment << " vs "
8477                  << MFI.getObjectAlignment(FixedIndex) << ")\n");
8478     return;
8479   }
8480 
8481   // Perform the elision. Delete the old stack object and replace its only use
8482   // in the variable info map. Mark the stack object as mutable.
8483   DEBUG({
8484     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8485            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8486            << '\n';
8487   });
8488   MFI.RemoveStackObject(OldIndex);
8489   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8490   AllocaIndex = FixedIndex;
8491   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8492   Chains.push_back(ArgVal.getValue(1));
8493 
8494   // Avoid emitting code for the store implementing the copy.
8495   const StoreInst *SI = ArgCopyIter->second.second;
8496   ElidedArgCopyInstrs.insert(SI);
8497 
8498   // Check for uses of the argument again so that we can avoid exporting ArgVal
8499   // if it is't used by anything other than the store.
8500   for (const Value *U : Arg.users()) {
8501     if (U != SI) {
8502       ArgHasUses = true;
8503       break;
8504     }
8505   }
8506 }
8507 
8508 void SelectionDAGISel::LowerArguments(const Function &F) {
8509   SelectionDAG &DAG = SDB->DAG;
8510   SDLoc dl = SDB->getCurSDLoc();
8511   const DataLayout &DL = DAG.getDataLayout();
8512   SmallVector<ISD::InputArg, 16> Ins;
8513 
8514   if (!FuncInfo->CanLowerReturn) {
8515     // Put in an sret pointer parameter before all the other parameters.
8516     SmallVector<EVT, 1> ValueVTs;
8517     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8518                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
8519 
8520     // NOTE: Assuming that a pointer will never break down to more than one VT
8521     // or one register.
8522     ISD::ArgFlagsTy Flags;
8523     Flags.setSRet();
8524     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8525     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8526                          ISD::InputArg::NoArgIndex, 0);
8527     Ins.push_back(RetArg);
8528   }
8529 
8530   // Look for stores of arguments to static allocas. Mark such arguments with a
8531   // flag to ask the target to give us the memory location of that argument if
8532   // available.
8533   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8534   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8535 
8536   // Set up the incoming argument description vector.
8537   for (const Argument &Arg : F.args()) {
8538     unsigned ArgNo = Arg.getArgNo();
8539     SmallVector<EVT, 4> ValueVTs;
8540     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8541     bool isArgValueUsed = !Arg.use_empty();
8542     unsigned PartBase = 0;
8543     Type *FinalType = Arg.getType();
8544     if (Arg.hasAttribute(Attribute::ByVal))
8545       FinalType = cast<PointerType>(FinalType)->getElementType();
8546     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8547         FinalType, F.getCallingConv(), F.isVarArg());
8548     for (unsigned Value = 0, NumValues = ValueVTs.size();
8549          Value != NumValues; ++Value) {
8550       EVT VT = ValueVTs[Value];
8551       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8552       ISD::ArgFlagsTy Flags;
8553 
8554       // Certain targets (such as MIPS), may have a different ABI alignment
8555       // for a type depending on the context. Give the target a chance to
8556       // specify the alignment it wants.
8557       unsigned OriginalAlignment =
8558           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8559 
8560       if (Arg.hasAttribute(Attribute::ZExt))
8561         Flags.setZExt();
8562       if (Arg.hasAttribute(Attribute::SExt))
8563         Flags.setSExt();
8564       if (Arg.hasAttribute(Attribute::InReg)) {
8565         // If we are using vectorcall calling convention, a structure that is
8566         // passed InReg - is surely an HVA
8567         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8568             isa<StructType>(Arg.getType())) {
8569           // The first value of a structure is marked
8570           if (0 == Value)
8571             Flags.setHvaStart();
8572           Flags.setHva();
8573         }
8574         // Set InReg Flag
8575         Flags.setInReg();
8576       }
8577       if (Arg.hasAttribute(Attribute::StructRet))
8578         Flags.setSRet();
8579       if (Arg.hasAttribute(Attribute::SwiftSelf))
8580         Flags.setSwiftSelf();
8581       if (Arg.hasAttribute(Attribute::SwiftError))
8582         Flags.setSwiftError();
8583       if (Arg.hasAttribute(Attribute::ByVal))
8584         Flags.setByVal();
8585       if (Arg.hasAttribute(Attribute::InAlloca)) {
8586         Flags.setInAlloca();
8587         // Set the byval flag for CCAssignFn callbacks that don't know about
8588         // inalloca.  This way we can know how many bytes we should've allocated
8589         // and how many bytes a callee cleanup function will pop.  If we port
8590         // inalloca to more targets, we'll have to add custom inalloca handling
8591         // in the various CC lowering callbacks.
8592         Flags.setByVal();
8593       }
8594       if (F.getCallingConv() == CallingConv::X86_INTR) {
8595         // IA Interrupt passes frame (1st parameter) by value in the stack.
8596         if (ArgNo == 0)
8597           Flags.setByVal();
8598       }
8599       if (Flags.isByVal() || Flags.isInAlloca()) {
8600         PointerType *Ty = cast<PointerType>(Arg.getType());
8601         Type *ElementTy = Ty->getElementType();
8602         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8603         // For ByVal, alignment should be passed from FE.  BE will guess if
8604         // this info is not there but there are cases it cannot get right.
8605         unsigned FrameAlign;
8606         if (Arg.getParamAlignment())
8607           FrameAlign = Arg.getParamAlignment();
8608         else
8609           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
8610         Flags.setByValAlign(FrameAlign);
8611       }
8612       if (Arg.hasAttribute(Attribute::Nest))
8613         Flags.setNest();
8614       if (NeedsRegBlock)
8615         Flags.setInConsecutiveRegs();
8616       Flags.setOrigAlign(OriginalAlignment);
8617       if (ArgCopyElisionCandidates.count(&Arg))
8618         Flags.setCopyElisionCandidate();
8619 
8620       MVT RegisterVT =
8621           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8622       unsigned NumRegs =
8623           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8624       for (unsigned i = 0; i != NumRegs; ++i) {
8625         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
8626                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
8627         if (NumRegs > 1 && i == 0)
8628           MyFlags.Flags.setSplit();
8629         // if it isn't first piece, alignment must be 1
8630         else if (i > 0) {
8631           MyFlags.Flags.setOrigAlign(1);
8632           if (i == NumRegs - 1)
8633             MyFlags.Flags.setSplitEnd();
8634         }
8635         Ins.push_back(MyFlags);
8636       }
8637       if (NeedsRegBlock && Value == NumValues - 1)
8638         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
8639       PartBase += VT.getStoreSize();
8640     }
8641   }
8642 
8643   // Call the target to set up the argument values.
8644   SmallVector<SDValue, 8> InVals;
8645   SDValue NewRoot = TLI->LowerFormalArguments(
8646       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
8647 
8648   // Verify that the target's LowerFormalArguments behaved as expected.
8649   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
8650          "LowerFormalArguments didn't return a valid chain!");
8651   assert(InVals.size() == Ins.size() &&
8652          "LowerFormalArguments didn't emit the correct number of values!");
8653   DEBUG({
8654       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
8655         assert(InVals[i].getNode() &&
8656                "LowerFormalArguments emitted a null value!");
8657         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
8658                "LowerFormalArguments emitted a value with the wrong type!");
8659       }
8660     });
8661 
8662   // Update the DAG with the new chain value resulting from argument lowering.
8663   DAG.setRoot(NewRoot);
8664 
8665   // Set up the argument values.
8666   unsigned i = 0;
8667   if (!FuncInfo->CanLowerReturn) {
8668     // Create a virtual register for the sret pointer, and put in a copy
8669     // from the sret argument into it.
8670     SmallVector<EVT, 1> ValueVTs;
8671     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8672                     PointerType::getUnqual(F.getReturnType()), ValueVTs);
8673     MVT VT = ValueVTs[0].getSimpleVT();
8674     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
8675     Optional<ISD::NodeType> AssertOp = None;
8676     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
8677                                         RegVT, VT, nullptr, AssertOp);
8678 
8679     MachineFunction& MF = SDB->DAG.getMachineFunction();
8680     MachineRegisterInfo& RegInfo = MF.getRegInfo();
8681     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
8682     FuncInfo->DemoteRegister = SRetReg;
8683     NewRoot =
8684         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
8685     DAG.setRoot(NewRoot);
8686 
8687     // i indexes lowered arguments.  Bump it past the hidden sret argument.
8688     ++i;
8689   }
8690 
8691   SmallVector<SDValue, 4> Chains;
8692   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
8693   for (const Argument &Arg : F.args()) {
8694     SmallVector<SDValue, 4> ArgValues;
8695     SmallVector<EVT, 4> ValueVTs;
8696     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8697     unsigned NumValues = ValueVTs.size();
8698     if (NumValues == 0)
8699       continue;
8700 
8701     bool ArgHasUses = !Arg.use_empty();
8702 
8703     // Elide the copying store if the target loaded this argument from a
8704     // suitable fixed stack object.
8705     if (Ins[i].Flags.isCopyElisionCandidate()) {
8706       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
8707                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
8708                              InVals[i], ArgHasUses);
8709     }
8710 
8711     // If this argument is unused then remember its value. It is used to generate
8712     // debugging information.
8713     bool isSwiftErrorArg =
8714         TLI->supportSwiftError() &&
8715         Arg.hasAttribute(Attribute::SwiftError);
8716     if (!ArgHasUses && !isSwiftErrorArg) {
8717       SDB->setUnusedArgValue(&Arg, InVals[i]);
8718 
8719       // Also remember any frame index for use in FastISel.
8720       if (FrameIndexSDNode *FI =
8721           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
8722         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8723     }
8724 
8725     for (unsigned Val = 0; Val != NumValues; ++Val) {
8726       EVT VT = ValueVTs[Val];
8727       MVT PartVT =
8728           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8729       unsigned NumParts =
8730           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8731 
8732       // Even an apparant 'unused' swifterror argument needs to be returned. So
8733       // we do generate a copy for it that can be used on return from the
8734       // function.
8735       if (ArgHasUses || isSwiftErrorArg) {
8736         Optional<ISD::NodeType> AssertOp;
8737         if (Arg.hasAttribute(Attribute::SExt))
8738           AssertOp = ISD::AssertSext;
8739         else if (Arg.hasAttribute(Attribute::ZExt))
8740           AssertOp = ISD::AssertZext;
8741 
8742         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
8743                                              PartVT, VT, nullptr, AssertOp,
8744                                              true));
8745       }
8746 
8747       i += NumParts;
8748     }
8749 
8750     // We don't need to do anything else for unused arguments.
8751     if (ArgValues.empty())
8752       continue;
8753 
8754     // Note down frame index.
8755     if (FrameIndexSDNode *FI =
8756         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
8757       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8758 
8759     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
8760                                      SDB->getCurSDLoc());
8761 
8762     SDB->setValue(&Arg, Res);
8763     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
8764       if (LoadSDNode *LNode =
8765           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
8766         if (FrameIndexSDNode *FI =
8767             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
8768         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8769     }
8770 
8771     // Update the SwiftErrorVRegDefMap.
8772     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
8773       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
8774       if (TargetRegisterInfo::isVirtualRegister(Reg))
8775         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
8776                                            FuncInfo->SwiftErrorArg, Reg);
8777     }
8778 
8779     // If this argument is live outside of the entry block, insert a copy from
8780     // wherever we got it to the vreg that other BB's will reference it as.
8781     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
8782       // If we can, though, try to skip creating an unnecessary vreg.
8783       // FIXME: This isn't very clean... it would be nice to make this more
8784       // general.  It's also subtly incompatible with the hacks FastISel
8785       // uses with vregs.
8786       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
8787       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
8788         FuncInfo->ValueMap[&Arg] = Reg;
8789         continue;
8790       }
8791     }
8792     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
8793       FuncInfo->InitializeRegForValue(&Arg);
8794       SDB->CopyToExportRegsIfNeeded(&Arg);
8795     }
8796   }
8797 
8798   if (!Chains.empty()) {
8799     Chains.push_back(NewRoot);
8800     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
8801   }
8802 
8803   DAG.setRoot(NewRoot);
8804 
8805   assert(i == InVals.size() && "Argument register count mismatch!");
8806 
8807   // If any argument copy elisions occurred and we have debug info, update the
8808   // stale frame indices used in the dbg.declare variable info table.
8809   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
8810   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
8811     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
8812       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
8813       if (I != ArgCopyElisionFrameIndexMap.end())
8814         VI.Slot = I->second;
8815     }
8816   }
8817 
8818   // Finally, if the target has anything special to do, allow it to do so.
8819   EmitFunctionEntryCode();
8820 }
8821 
8822 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
8823 /// ensure constants are generated when needed.  Remember the virtual registers
8824 /// that need to be added to the Machine PHI nodes as input.  We cannot just
8825 /// directly add them, because expansion might result in multiple MBB's for one
8826 /// BB.  As such, the start of the BB might correspond to a different MBB than
8827 /// the end.
8828 ///
8829 void
8830 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
8831   const TerminatorInst *TI = LLVMBB->getTerminator();
8832 
8833   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
8834 
8835   // Check PHI nodes in successors that expect a value to be available from this
8836   // block.
8837   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
8838     const BasicBlock *SuccBB = TI->getSuccessor(succ);
8839     if (!isa<PHINode>(SuccBB->begin())) continue;
8840     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
8841 
8842     // If this terminator has multiple identical successors (common for
8843     // switches), only handle each succ once.
8844     if (!SuccsHandled.insert(SuccMBB).second)
8845       continue;
8846 
8847     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
8848 
8849     // At this point we know that there is a 1-1 correspondence between LLVM PHI
8850     // nodes and Machine PHI nodes, but the incoming operands have not been
8851     // emitted yet.
8852     for (BasicBlock::const_iterator I = SuccBB->begin();
8853          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
8854       // Ignore dead phi's.
8855       if (PN->use_empty()) continue;
8856 
8857       // Skip empty types
8858       if (PN->getType()->isEmptyTy())
8859         continue;
8860 
8861       unsigned Reg;
8862       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
8863 
8864       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
8865         unsigned &RegOut = ConstantsOut[C];
8866         if (RegOut == 0) {
8867           RegOut = FuncInfo.CreateRegs(C->getType());
8868           CopyValueToVirtualRegister(C, RegOut);
8869         }
8870         Reg = RegOut;
8871       } else {
8872         DenseMap<const Value *, unsigned>::iterator I =
8873           FuncInfo.ValueMap.find(PHIOp);
8874         if (I != FuncInfo.ValueMap.end())
8875           Reg = I->second;
8876         else {
8877           assert(isa<AllocaInst>(PHIOp) &&
8878                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
8879                  "Didn't codegen value into a register!??");
8880           Reg = FuncInfo.CreateRegs(PHIOp->getType());
8881           CopyValueToVirtualRegister(PHIOp, Reg);
8882         }
8883       }
8884 
8885       // Remember that this register needs to added to the machine PHI node as
8886       // the input for this MBB.
8887       SmallVector<EVT, 4> ValueVTs;
8888       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8889       ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
8890       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
8891         EVT VT = ValueVTs[vti];
8892         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
8893         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
8894           FuncInfo.PHINodesToUpdate.push_back(
8895               std::make_pair(&*MBBI++, Reg + i));
8896         Reg += NumRegisters;
8897       }
8898     }
8899   }
8900 
8901   ConstantsOut.clear();
8902 }
8903 
8904 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
8905 /// is 0.
8906 MachineBasicBlock *
8907 SelectionDAGBuilder::StackProtectorDescriptor::
8908 AddSuccessorMBB(const BasicBlock *BB,
8909                 MachineBasicBlock *ParentMBB,
8910                 bool IsLikely,
8911                 MachineBasicBlock *SuccMBB) {
8912   // If SuccBB has not been created yet, create it.
8913   if (!SuccMBB) {
8914     MachineFunction *MF = ParentMBB->getParent();
8915     MachineFunction::iterator BBI(ParentMBB);
8916     SuccMBB = MF->CreateMachineBasicBlock(BB);
8917     MF->insert(++BBI, SuccMBB);
8918   }
8919   // Add it as a successor of ParentMBB.
8920   ParentMBB->addSuccessor(
8921       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
8922   return SuccMBB;
8923 }
8924 
8925 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
8926   MachineFunction::iterator I(MBB);
8927   if (++I == FuncInfo.MF->end())
8928     return nullptr;
8929   return &*I;
8930 }
8931 
8932 /// During lowering new call nodes can be created (such as memset, etc.).
8933 /// Those will become new roots of the current DAG, but complications arise
8934 /// when they are tail calls. In such cases, the call lowering will update
8935 /// the root, but the builder still needs to know that a tail call has been
8936 /// lowered in order to avoid generating an additional return.
8937 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
8938   // If the node is null, we do have a tail call.
8939   if (MaybeTC.getNode() != nullptr)
8940     DAG.setRoot(MaybeTC);
8941   else
8942     HasTailCall = true;
8943 }
8944 
8945 uint64_t
8946 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
8947                                        unsigned First, unsigned Last) const {
8948   assert(Last >= First);
8949   const APInt &LowCase = Clusters[First].Low->getValue();
8950   const APInt &HighCase = Clusters[Last].High->getValue();
8951   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
8952 
8953   // FIXME: A range of consecutive cases has 100% density, but only requires one
8954   // comparison to lower. We should discriminate against such consecutive ranges
8955   // in jump tables.
8956 
8957   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
8958 }
8959 
8960 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
8961     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
8962     unsigned Last) const {
8963   assert(Last >= First);
8964   assert(TotalCases[Last] >= TotalCases[First]);
8965   uint64_t NumCases =
8966       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
8967   return NumCases;
8968 }
8969 
8970 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
8971                                          unsigned First, unsigned Last,
8972                                          const SwitchInst *SI,
8973                                          MachineBasicBlock *DefaultMBB,
8974                                          CaseCluster &JTCluster) {
8975   assert(First <= Last);
8976 
8977   auto Prob = BranchProbability::getZero();
8978   unsigned NumCmps = 0;
8979   std::vector<MachineBasicBlock*> Table;
8980   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
8981 
8982   // Initialize probabilities in JTProbs.
8983   for (unsigned I = First; I <= Last; ++I)
8984     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
8985 
8986   for (unsigned I = First; I <= Last; ++I) {
8987     assert(Clusters[I].Kind == CC_Range);
8988     Prob += Clusters[I].Prob;
8989     const APInt &Low = Clusters[I].Low->getValue();
8990     const APInt &High = Clusters[I].High->getValue();
8991     NumCmps += (Low == High) ? 1 : 2;
8992     if (I != First) {
8993       // Fill the gap between this and the previous cluster.
8994       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
8995       assert(PreviousHigh.slt(Low));
8996       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
8997       for (uint64_t J = 0; J < Gap; J++)
8998         Table.push_back(DefaultMBB);
8999     }
9000     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9001     for (uint64_t J = 0; J < ClusterSize; ++J)
9002       Table.push_back(Clusters[I].MBB);
9003     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9004   }
9005 
9006   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9007   unsigned NumDests = JTProbs.size();
9008   if (TLI.isSuitableForBitTests(
9009           NumDests, NumCmps, Clusters[First].Low->getValue(),
9010           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9011     // Clusters[First..Last] should be lowered as bit tests instead.
9012     return false;
9013   }
9014 
9015   // Create the MBB that will load from and jump through the table.
9016   // Note: We create it here, but it's not inserted into the function yet.
9017   MachineFunction *CurMF = FuncInfo.MF;
9018   MachineBasicBlock *JumpTableMBB =
9019       CurMF->CreateMachineBasicBlock(SI->getParent());
9020 
9021   // Add successors. Note: use table order for determinism.
9022   SmallPtrSet<MachineBasicBlock *, 8> Done;
9023   for (MachineBasicBlock *Succ : Table) {
9024     if (Done.count(Succ))
9025       continue;
9026     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9027     Done.insert(Succ);
9028   }
9029   JumpTableMBB->normalizeSuccProbs();
9030 
9031   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9032                      ->createJumpTableIndex(Table);
9033 
9034   // Set up the jump table info.
9035   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9036   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9037                       Clusters[Last].High->getValue(), SI->getCondition(),
9038                       nullptr, false);
9039   JTCases.emplace_back(std::move(JTH), std::move(JT));
9040 
9041   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9042                                      JTCases.size() - 1, Prob);
9043   return true;
9044 }
9045 
9046 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9047                                          const SwitchInst *SI,
9048                                          MachineBasicBlock *DefaultMBB) {
9049 #ifndef NDEBUG
9050   // Clusters must be non-empty, sorted, and only contain Range clusters.
9051   assert(!Clusters.empty());
9052   for (CaseCluster &C : Clusters)
9053     assert(C.Kind == CC_Range);
9054   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9055     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9056 #endif
9057 
9058   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9059   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9060     return;
9061 
9062   const int64_t N = Clusters.size();
9063   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9064   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9065 
9066   if (N < 2 || N < MinJumpTableEntries)
9067     return;
9068 
9069   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9070   SmallVector<unsigned, 8> TotalCases(N);
9071   for (unsigned i = 0; i < N; ++i) {
9072     const APInt &Hi = Clusters[i].High->getValue();
9073     const APInt &Lo = Clusters[i].Low->getValue();
9074     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9075     if (i != 0)
9076       TotalCases[i] += TotalCases[i - 1];
9077   }
9078 
9079   // Cheap case: the whole range may be suitable for jump table.
9080   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9081   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9082   assert(NumCases < UINT64_MAX / 100);
9083   assert(Range >= NumCases);
9084   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9085     CaseCluster JTCluster;
9086     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9087       Clusters[0] = JTCluster;
9088       Clusters.resize(1);
9089       return;
9090     }
9091   }
9092 
9093   // The algorithm below is not suitable for -O0.
9094   if (TM.getOptLevel() == CodeGenOpt::None)
9095     return;
9096 
9097   // Split Clusters into minimum number of dense partitions. The algorithm uses
9098   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9099   // for the Case Statement'" (1994), but builds the MinPartitions array in
9100   // reverse order to make it easier to reconstruct the partitions in ascending
9101   // order. In the choice between two optimal partitionings, it picks the one
9102   // which yields more jump tables.
9103 
9104   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9105   SmallVector<unsigned, 8> MinPartitions(N);
9106   // LastElement[i] is the last element of the partition starting at i.
9107   SmallVector<unsigned, 8> LastElement(N);
9108   // PartitionsScore[i] is used to break ties when choosing between two
9109   // partitionings resulting in the same number of partitions.
9110   SmallVector<unsigned, 8> PartitionsScore(N);
9111   // For PartitionsScore, a small number of comparisons is considered as good as
9112   // a jump table and a single comparison is considered better than a jump
9113   // table.
9114   enum PartitionScores : unsigned {
9115     NoTable = 0,
9116     Table = 1,
9117     FewCases = 1,
9118     SingleCase = 2
9119   };
9120 
9121   // Base case: There is only one way to partition Clusters[N-1].
9122   MinPartitions[N - 1] = 1;
9123   LastElement[N - 1] = N - 1;
9124   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9125 
9126   // Note: loop indexes are signed to avoid underflow.
9127   for (int64_t i = N - 2; i >= 0; i--) {
9128     // Find optimal partitioning of Clusters[i..N-1].
9129     // Baseline: Put Clusters[i] into a partition on its own.
9130     MinPartitions[i] = MinPartitions[i + 1] + 1;
9131     LastElement[i] = i;
9132     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9133 
9134     // Search for a solution that results in fewer partitions.
9135     for (int64_t j = N - 1; j > i; j--) {
9136       // Try building a partition from Clusters[i..j].
9137       uint64_t Range = getJumpTableRange(Clusters, i, j);
9138       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9139       assert(NumCases < UINT64_MAX / 100);
9140       assert(Range >= NumCases);
9141       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9142         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9143         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9144         int64_t NumEntries = j - i + 1;
9145 
9146         if (NumEntries == 1)
9147           Score += PartitionScores::SingleCase;
9148         else if (NumEntries <= SmallNumberOfEntries)
9149           Score += PartitionScores::FewCases;
9150         else if (NumEntries >= MinJumpTableEntries)
9151           Score += PartitionScores::Table;
9152 
9153         // If this leads to fewer partitions, or to the same number of
9154         // partitions with better score, it is a better partitioning.
9155         if (NumPartitions < MinPartitions[i] ||
9156             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9157           MinPartitions[i] = NumPartitions;
9158           LastElement[i] = j;
9159           PartitionsScore[i] = Score;
9160         }
9161       }
9162     }
9163   }
9164 
9165   // Iterate over the partitions, replacing some with jump tables in-place.
9166   unsigned DstIndex = 0;
9167   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9168     Last = LastElement[First];
9169     assert(Last >= First);
9170     assert(DstIndex <= First);
9171     unsigned NumClusters = Last - First + 1;
9172 
9173     CaseCluster JTCluster;
9174     if (NumClusters >= MinJumpTableEntries &&
9175         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9176       Clusters[DstIndex++] = JTCluster;
9177     } else {
9178       for (unsigned I = First; I <= Last; ++I)
9179         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9180     }
9181   }
9182   Clusters.resize(DstIndex);
9183 }
9184 
9185 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9186                                         unsigned First, unsigned Last,
9187                                         const SwitchInst *SI,
9188                                         CaseCluster &BTCluster) {
9189   assert(First <= Last);
9190   if (First == Last)
9191     return false;
9192 
9193   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9194   unsigned NumCmps = 0;
9195   for (int64_t I = First; I <= Last; ++I) {
9196     assert(Clusters[I].Kind == CC_Range);
9197     Dests.set(Clusters[I].MBB->getNumber());
9198     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9199   }
9200   unsigned NumDests = Dests.count();
9201 
9202   APInt Low = Clusters[First].Low->getValue();
9203   APInt High = Clusters[Last].High->getValue();
9204   assert(Low.slt(High));
9205 
9206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9207   const DataLayout &DL = DAG.getDataLayout();
9208   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9209     return false;
9210 
9211   APInt LowBound;
9212   APInt CmpRange;
9213 
9214   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9215   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9216          "Case range must fit in bit mask!");
9217 
9218   // Check if the clusters cover a contiguous range such that no value in the
9219   // range will jump to the default statement.
9220   bool ContiguousRange = true;
9221   for (int64_t I = First + 1; I <= Last; ++I) {
9222     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9223       ContiguousRange = false;
9224       break;
9225     }
9226   }
9227 
9228   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9229     // Optimize the case where all the case values fit in a word without having
9230     // to subtract minValue. In this case, we can optimize away the subtraction.
9231     LowBound = APInt::getNullValue(Low.getBitWidth());
9232     CmpRange = High;
9233     ContiguousRange = false;
9234   } else {
9235     LowBound = Low;
9236     CmpRange = High - Low;
9237   }
9238 
9239   CaseBitsVector CBV;
9240   auto TotalProb = BranchProbability::getZero();
9241   for (unsigned i = First; i <= Last; ++i) {
9242     // Find the CaseBits for this destination.
9243     unsigned j;
9244     for (j = 0; j < CBV.size(); ++j)
9245       if (CBV[j].BB == Clusters[i].MBB)
9246         break;
9247     if (j == CBV.size())
9248       CBV.push_back(
9249           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9250     CaseBits *CB = &CBV[j];
9251 
9252     // Update Mask, Bits and ExtraProb.
9253     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9254     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9255     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9256     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9257     CB->Bits += Hi - Lo + 1;
9258     CB->ExtraProb += Clusters[i].Prob;
9259     TotalProb += Clusters[i].Prob;
9260   }
9261 
9262   BitTestInfo BTI;
9263   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9264     // Sort by probability first, number of bits second.
9265     if (a.ExtraProb != b.ExtraProb)
9266       return a.ExtraProb > b.ExtraProb;
9267     return a.Bits > b.Bits;
9268   });
9269 
9270   for (auto &CB : CBV) {
9271     MachineBasicBlock *BitTestBB =
9272         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9273     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9274   }
9275   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9276                             SI->getCondition(), -1U, MVT::Other, false,
9277                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9278                             TotalProb);
9279 
9280   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9281                                     BitTestCases.size() - 1, TotalProb);
9282   return true;
9283 }
9284 
9285 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9286                                               const SwitchInst *SI) {
9287 // Partition Clusters into as few subsets as possible, where each subset has a
9288 // range that fits in a machine word and has <= 3 unique destinations.
9289 
9290 #ifndef NDEBUG
9291   // Clusters must be sorted and contain Range or JumpTable clusters.
9292   assert(!Clusters.empty());
9293   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9294   for (const CaseCluster &C : Clusters)
9295     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9296   for (unsigned i = 1; i < Clusters.size(); ++i)
9297     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9298 #endif
9299 
9300   // The algorithm below is not suitable for -O0.
9301   if (TM.getOptLevel() == CodeGenOpt::None)
9302     return;
9303 
9304   // If target does not have legal shift left, do not emit bit tests at all.
9305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9306   const DataLayout &DL = DAG.getDataLayout();
9307 
9308   EVT PTy = TLI.getPointerTy(DL);
9309   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9310     return;
9311 
9312   int BitWidth = PTy.getSizeInBits();
9313   const int64_t N = Clusters.size();
9314 
9315   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9316   SmallVector<unsigned, 8> MinPartitions(N);
9317   // LastElement[i] is the last element of the partition starting at i.
9318   SmallVector<unsigned, 8> LastElement(N);
9319 
9320   // FIXME: This might not be the best algorithm for finding bit test clusters.
9321 
9322   // Base case: There is only one way to partition Clusters[N-1].
9323   MinPartitions[N - 1] = 1;
9324   LastElement[N - 1] = N - 1;
9325 
9326   // Note: loop indexes are signed to avoid underflow.
9327   for (int64_t i = N - 2; i >= 0; --i) {
9328     // Find optimal partitioning of Clusters[i..N-1].
9329     // Baseline: Put Clusters[i] into a partition on its own.
9330     MinPartitions[i] = MinPartitions[i + 1] + 1;
9331     LastElement[i] = i;
9332 
9333     // Search for a solution that results in fewer partitions.
9334     // Note: the search is limited by BitWidth, reducing time complexity.
9335     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9336       // Try building a partition from Clusters[i..j].
9337 
9338       // Check the range.
9339       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9340                                Clusters[j].High->getValue(), DL))
9341         continue;
9342 
9343       // Check nbr of destinations and cluster types.
9344       // FIXME: This works, but doesn't seem very efficient.
9345       bool RangesOnly = true;
9346       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9347       for (int64_t k = i; k <= j; k++) {
9348         if (Clusters[k].Kind != CC_Range) {
9349           RangesOnly = false;
9350           break;
9351         }
9352         Dests.set(Clusters[k].MBB->getNumber());
9353       }
9354       if (!RangesOnly || Dests.count() > 3)
9355         break;
9356 
9357       // Check if it's a better partition.
9358       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9359       if (NumPartitions < MinPartitions[i]) {
9360         // Found a better partition.
9361         MinPartitions[i] = NumPartitions;
9362         LastElement[i] = j;
9363       }
9364     }
9365   }
9366 
9367   // Iterate over the partitions, replacing with bit-test clusters in-place.
9368   unsigned DstIndex = 0;
9369   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9370     Last = LastElement[First];
9371     assert(First <= Last);
9372     assert(DstIndex <= First);
9373 
9374     CaseCluster BitTestCluster;
9375     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9376       Clusters[DstIndex++] = BitTestCluster;
9377     } else {
9378       size_t NumClusters = Last - First + 1;
9379       std::memmove(&Clusters[DstIndex], &Clusters[First],
9380                    sizeof(Clusters[0]) * NumClusters);
9381       DstIndex += NumClusters;
9382     }
9383   }
9384   Clusters.resize(DstIndex);
9385 }
9386 
9387 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9388                                         MachineBasicBlock *SwitchMBB,
9389                                         MachineBasicBlock *DefaultMBB) {
9390   MachineFunction *CurMF = FuncInfo.MF;
9391   MachineBasicBlock *NextMBB = nullptr;
9392   MachineFunction::iterator BBI(W.MBB);
9393   if (++BBI != FuncInfo.MF->end())
9394     NextMBB = &*BBI;
9395 
9396   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9397 
9398   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9399 
9400   if (Size == 2 && W.MBB == SwitchMBB) {
9401     // If any two of the cases has the same destination, and if one value
9402     // is the same as the other, but has one bit unset that the other has set,
9403     // use bit manipulation to do two compares at once.  For example:
9404     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9405     // TODO: This could be extended to merge any 2 cases in switches with 3
9406     // cases.
9407     // TODO: Handle cases where W.CaseBB != SwitchBB.
9408     CaseCluster &Small = *W.FirstCluster;
9409     CaseCluster &Big = *W.LastCluster;
9410 
9411     if (Small.Low == Small.High && Big.Low == Big.High &&
9412         Small.MBB == Big.MBB) {
9413       const APInt &SmallValue = Small.Low->getValue();
9414       const APInt &BigValue = Big.Low->getValue();
9415 
9416       // Check that there is only one bit different.
9417       APInt CommonBit = BigValue ^ SmallValue;
9418       if (CommonBit.isPowerOf2()) {
9419         SDValue CondLHS = getValue(Cond);
9420         EVT VT = CondLHS.getValueType();
9421         SDLoc DL = getCurSDLoc();
9422 
9423         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9424                                  DAG.getConstant(CommonBit, DL, VT));
9425         SDValue Cond = DAG.getSetCC(
9426             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9427             ISD::SETEQ);
9428 
9429         // Update successor info.
9430         // Both Small and Big will jump to Small.BB, so we sum up the
9431         // probabilities.
9432         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9433         if (BPI)
9434           addSuccessorWithProb(
9435               SwitchMBB, DefaultMBB,
9436               // The default destination is the first successor in IR.
9437               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9438         else
9439           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9440 
9441         // Insert the true branch.
9442         SDValue BrCond =
9443             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9444                         DAG.getBasicBlock(Small.MBB));
9445         // Insert the false branch.
9446         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9447                              DAG.getBasicBlock(DefaultMBB));
9448 
9449         DAG.setRoot(BrCond);
9450         return;
9451       }
9452     }
9453   }
9454 
9455   if (TM.getOptLevel() != CodeGenOpt::None) {
9456     // Order cases by probability so the most likely case will be checked first.
9457     std::sort(W.FirstCluster, W.LastCluster + 1,
9458               [](const CaseCluster &a, const CaseCluster &b) {
9459       return a.Prob > b.Prob;
9460     });
9461 
9462     // Rearrange the case blocks so that the last one falls through if possible
9463     // without without changing the order of probabilities.
9464     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9465       --I;
9466       if (I->Prob > W.LastCluster->Prob)
9467         break;
9468       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9469         std::swap(*I, *W.LastCluster);
9470         break;
9471       }
9472     }
9473   }
9474 
9475   // Compute total probability.
9476   BranchProbability DefaultProb = W.DefaultProb;
9477   BranchProbability UnhandledProbs = DefaultProb;
9478   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9479     UnhandledProbs += I->Prob;
9480 
9481   MachineBasicBlock *CurMBB = W.MBB;
9482   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9483     MachineBasicBlock *Fallthrough;
9484     if (I == W.LastCluster) {
9485       // For the last cluster, fall through to the default destination.
9486       Fallthrough = DefaultMBB;
9487     } else {
9488       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9489       CurMF->insert(BBI, Fallthrough);
9490       // Put Cond in a virtual register to make it available from the new blocks.
9491       ExportFromCurrentBlock(Cond);
9492     }
9493     UnhandledProbs -= I->Prob;
9494 
9495     switch (I->Kind) {
9496       case CC_JumpTable: {
9497         // FIXME: Optimize away range check based on pivot comparisons.
9498         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9499         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9500 
9501         // The jump block hasn't been inserted yet; insert it here.
9502         MachineBasicBlock *JumpMBB = JT->MBB;
9503         CurMF->insert(BBI, JumpMBB);
9504 
9505         auto JumpProb = I->Prob;
9506         auto FallthroughProb = UnhandledProbs;
9507 
9508         // If the default statement is a target of the jump table, we evenly
9509         // distribute the default probability to successors of CurMBB. Also
9510         // update the probability on the edge from JumpMBB to Fallthrough.
9511         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9512                                               SE = JumpMBB->succ_end();
9513              SI != SE; ++SI) {
9514           if (*SI == DefaultMBB) {
9515             JumpProb += DefaultProb / 2;
9516             FallthroughProb -= DefaultProb / 2;
9517             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9518             JumpMBB->normalizeSuccProbs();
9519             break;
9520           }
9521         }
9522 
9523         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9524         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9525         CurMBB->normalizeSuccProbs();
9526 
9527         // The jump table header will be inserted in our current block, do the
9528         // range check, and fall through to our fallthrough block.
9529         JTH->HeaderBB = CurMBB;
9530         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9531 
9532         // If we're in the right place, emit the jump table header right now.
9533         if (CurMBB == SwitchMBB) {
9534           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9535           JTH->Emitted = true;
9536         }
9537         break;
9538       }
9539       case CC_BitTests: {
9540         // FIXME: Optimize away range check based on pivot comparisons.
9541         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9542 
9543         // The bit test blocks haven't been inserted yet; insert them here.
9544         for (BitTestCase &BTC : BTB->Cases)
9545           CurMF->insert(BBI, BTC.ThisBB);
9546 
9547         // Fill in fields of the BitTestBlock.
9548         BTB->Parent = CurMBB;
9549         BTB->Default = Fallthrough;
9550 
9551         BTB->DefaultProb = UnhandledProbs;
9552         // If the cases in bit test don't form a contiguous range, we evenly
9553         // distribute the probability on the edge to Fallthrough to two
9554         // successors of CurMBB.
9555         if (!BTB->ContiguousRange) {
9556           BTB->Prob += DefaultProb / 2;
9557           BTB->DefaultProb -= DefaultProb / 2;
9558         }
9559 
9560         // If we're in the right place, emit the bit test header right now.
9561         if (CurMBB == SwitchMBB) {
9562           visitBitTestHeader(*BTB, SwitchMBB);
9563           BTB->Emitted = true;
9564         }
9565         break;
9566       }
9567       case CC_Range: {
9568         const Value *RHS, *LHS, *MHS;
9569         ISD::CondCode CC;
9570         if (I->Low == I->High) {
9571           // Check Cond == I->Low.
9572           CC = ISD::SETEQ;
9573           LHS = Cond;
9574           RHS=I->Low;
9575           MHS = nullptr;
9576         } else {
9577           // Check I->Low <= Cond <= I->High.
9578           CC = ISD::SETLE;
9579           LHS = I->Low;
9580           MHS = Cond;
9581           RHS = I->High;
9582         }
9583 
9584         // The false probability is the sum of all unhandled cases.
9585         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
9586                      getCurSDLoc(), I->Prob, UnhandledProbs);
9587 
9588         if (CurMBB == SwitchMBB)
9589           visitSwitchCase(CB, SwitchMBB);
9590         else
9591           SwitchCases.push_back(CB);
9592 
9593         break;
9594       }
9595     }
9596     CurMBB = Fallthrough;
9597   }
9598 }
9599 
9600 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
9601                                               CaseClusterIt First,
9602                                               CaseClusterIt Last) {
9603   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
9604     if (X.Prob != CC.Prob)
9605       return X.Prob > CC.Prob;
9606 
9607     // Ties are broken by comparing the case value.
9608     return X.Low->getValue().slt(CC.Low->getValue());
9609   });
9610 }
9611 
9612 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
9613                                         const SwitchWorkListItem &W,
9614                                         Value *Cond,
9615                                         MachineBasicBlock *SwitchMBB) {
9616   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
9617          "Clusters not sorted?");
9618 
9619   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
9620 
9621   // Balance the tree based on branch probabilities to create a near-optimal (in
9622   // terms of search time given key frequency) binary search tree. See e.g. Kurt
9623   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
9624   CaseClusterIt LastLeft = W.FirstCluster;
9625   CaseClusterIt FirstRight = W.LastCluster;
9626   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
9627   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
9628 
9629   // Move LastLeft and FirstRight towards each other from opposite directions to
9630   // find a partitioning of the clusters which balances the probability on both
9631   // sides. If LeftProb and RightProb are equal, alternate which side is
9632   // taken to ensure 0-probability nodes are distributed evenly.
9633   unsigned I = 0;
9634   while (LastLeft + 1 < FirstRight) {
9635     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
9636       LeftProb += (++LastLeft)->Prob;
9637     else
9638       RightProb += (--FirstRight)->Prob;
9639     I++;
9640   }
9641 
9642   for (;;) {
9643     // Our binary search tree differs from a typical BST in that ours can have up
9644     // to three values in each leaf. The pivot selection above doesn't take that
9645     // into account, which means the tree might require more nodes and be less
9646     // efficient. We compensate for this here.
9647 
9648     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
9649     unsigned NumRight = W.LastCluster - FirstRight + 1;
9650 
9651     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
9652       // If one side has less than 3 clusters, and the other has more than 3,
9653       // consider taking a cluster from the other side.
9654 
9655       if (NumLeft < NumRight) {
9656         // Consider moving the first cluster on the right to the left side.
9657         CaseCluster &CC = *FirstRight;
9658         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9659         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9660         if (LeftSideRank <= RightSideRank) {
9661           // Moving the cluster to the left does not demote it.
9662           ++LastLeft;
9663           ++FirstRight;
9664           continue;
9665         }
9666       } else {
9667         assert(NumRight < NumLeft);
9668         // Consider moving the last element on the left to the right side.
9669         CaseCluster &CC = *LastLeft;
9670         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9671         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9672         if (RightSideRank <= LeftSideRank) {
9673           // Moving the cluster to the right does not demot it.
9674           --LastLeft;
9675           --FirstRight;
9676           continue;
9677         }
9678       }
9679     }
9680     break;
9681   }
9682 
9683   assert(LastLeft + 1 == FirstRight);
9684   assert(LastLeft >= W.FirstCluster);
9685   assert(FirstRight <= W.LastCluster);
9686 
9687   // Use the first element on the right as pivot since we will make less-than
9688   // comparisons against it.
9689   CaseClusterIt PivotCluster = FirstRight;
9690   assert(PivotCluster > W.FirstCluster);
9691   assert(PivotCluster <= W.LastCluster);
9692 
9693   CaseClusterIt FirstLeft = W.FirstCluster;
9694   CaseClusterIt LastRight = W.LastCluster;
9695 
9696   const ConstantInt *Pivot = PivotCluster->Low;
9697 
9698   // New blocks will be inserted immediately after the current one.
9699   MachineFunction::iterator BBI(W.MBB);
9700   ++BBI;
9701 
9702   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
9703   // we can branch to its destination directly if it's squeezed exactly in
9704   // between the known lower bound and Pivot - 1.
9705   MachineBasicBlock *LeftMBB;
9706   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
9707       FirstLeft->Low == W.GE &&
9708       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
9709     LeftMBB = FirstLeft->MBB;
9710   } else {
9711     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9712     FuncInfo.MF->insert(BBI, LeftMBB);
9713     WorkList.push_back(
9714         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
9715     // Put Cond in a virtual register to make it available from the new blocks.
9716     ExportFromCurrentBlock(Cond);
9717   }
9718 
9719   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
9720   // single cluster, RHS.Low == Pivot, and we can branch to its destination
9721   // directly if RHS.High equals the current upper bound.
9722   MachineBasicBlock *RightMBB;
9723   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
9724       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
9725     RightMBB = FirstRight->MBB;
9726   } else {
9727     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9728     FuncInfo.MF->insert(BBI, RightMBB);
9729     WorkList.push_back(
9730         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
9731     // Put Cond in a virtual register to make it available from the new blocks.
9732     ExportFromCurrentBlock(Cond);
9733   }
9734 
9735   // Create the CaseBlock record that will be used to lower the branch.
9736   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
9737                getCurSDLoc(), LeftProb, RightProb);
9738 
9739   if (W.MBB == SwitchMBB)
9740     visitSwitchCase(CB, SwitchMBB);
9741   else
9742     SwitchCases.push_back(CB);
9743 }
9744 
9745 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
9746   // Extract cases from the switch.
9747   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9748   CaseClusterVector Clusters;
9749   Clusters.reserve(SI.getNumCases());
9750   for (auto I : SI.cases()) {
9751     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
9752     const ConstantInt *CaseVal = I.getCaseValue();
9753     BranchProbability Prob =
9754         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
9755             : BranchProbability(1, SI.getNumCases() + 1);
9756     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
9757   }
9758 
9759   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
9760 
9761   // Cluster adjacent cases with the same destination. We do this at all
9762   // optimization levels because it's cheap to do and will make codegen faster
9763   // if there are many clusters.
9764   sortAndRangeify(Clusters);
9765 
9766   if (TM.getOptLevel() != CodeGenOpt::None) {
9767     // Replace an unreachable default with the most popular destination.
9768     // FIXME: Exploit unreachable default more aggressively.
9769     bool UnreachableDefault =
9770         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
9771     if (UnreachableDefault && !Clusters.empty()) {
9772       DenseMap<const BasicBlock *, unsigned> Popularity;
9773       unsigned MaxPop = 0;
9774       const BasicBlock *MaxBB = nullptr;
9775       for (auto I : SI.cases()) {
9776         const BasicBlock *BB = I.getCaseSuccessor();
9777         if (++Popularity[BB] > MaxPop) {
9778           MaxPop = Popularity[BB];
9779           MaxBB = BB;
9780         }
9781       }
9782       // Set new default.
9783       assert(MaxPop > 0 && MaxBB);
9784       DefaultMBB = FuncInfo.MBBMap[MaxBB];
9785 
9786       // Remove cases that were pointing to the destination that is now the
9787       // default.
9788       CaseClusterVector New;
9789       New.reserve(Clusters.size());
9790       for (CaseCluster &CC : Clusters) {
9791         if (CC.MBB != DefaultMBB)
9792           New.push_back(CC);
9793       }
9794       Clusters = std::move(New);
9795     }
9796   }
9797 
9798   // If there is only the default destination, jump there directly.
9799   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
9800   if (Clusters.empty()) {
9801     SwitchMBB->addSuccessor(DefaultMBB);
9802     if (DefaultMBB != NextBlock(SwitchMBB)) {
9803       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
9804                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
9805     }
9806     return;
9807   }
9808 
9809   findJumpTables(Clusters, &SI, DefaultMBB);
9810   findBitTestClusters(Clusters, &SI);
9811 
9812   DEBUG({
9813     dbgs() << "Case clusters: ";
9814     for (const CaseCluster &C : Clusters) {
9815       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
9816       if (C.Kind == CC_BitTests) dbgs() << "BT:";
9817 
9818       C.Low->getValue().print(dbgs(), true);
9819       if (C.Low != C.High) {
9820         dbgs() << '-';
9821         C.High->getValue().print(dbgs(), true);
9822       }
9823       dbgs() << ' ';
9824     }
9825     dbgs() << '\n';
9826   });
9827 
9828   assert(!Clusters.empty());
9829   SwitchWorkList WorkList;
9830   CaseClusterIt First = Clusters.begin();
9831   CaseClusterIt Last = Clusters.end() - 1;
9832   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
9833   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
9834 
9835   while (!WorkList.empty()) {
9836     SwitchWorkListItem W = WorkList.back();
9837     WorkList.pop_back();
9838     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
9839 
9840     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
9841         !DefaultMBB->getParent()->getFunction()->optForMinSize()) {
9842       // For optimized builds, lower large range as a balanced binary tree.
9843       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
9844       continue;
9845     }
9846 
9847     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
9848   }
9849 }
9850