xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision e0b5f86b3083747beaf5d7639333af0109c9e6ef)
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/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Analysis/VectorUtils.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/FunctionLoweringInfo.h"
41 #include "llvm/CodeGen/GCMetadata.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineJumpTableInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/RuntimeLibcalls.h"
54 #include "llvm/CodeGen/SelectionDAG.h"
55 #include "llvm/CodeGen/SelectionDAGNodes.h"
56 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
57 #include "llvm/CodeGen/StackMaps.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstring>
116 #include <iterator>
117 #include <limits>
118 #include <numeric>
119 #include <tuple>
120 #include <utility>
121 #include <vector>
122 
123 using namespace llvm;
124 
125 #define DEBUG_TYPE "isel"
126 
127 /// LimitFloatPrecision - Generate low-precision inline sequences for
128 /// some float libcalls (6, 8 or 12 bits).
129 static unsigned LimitFloatPrecision;
130 
131 static cl::opt<unsigned, true>
132     LimitFPPrecision("limit-float-precision",
133                      cl::desc("Generate low-precision inline sequences "
134                               "for some float libcalls"),
135                      cl::location(LimitFloatPrecision), cl::Hidden,
136                      cl::init(0));
137 
138 static cl::opt<unsigned> SwitchPeelThreshold(
139     "switch-peel-threshold", cl::Hidden, cl::init(66),
140     cl::desc("Set the case probability threshold for peeling the case from a "
141              "switch statement. A value greater than 100 will void this "
142              "optimization"));
143 
144 // Limit the width of DAG chains. This is important in general to prevent
145 // DAG-based analysis from blowing up. For example, alias analysis and
146 // load clustering may not complete in reasonable time. It is difficult to
147 // recognize and avoid this situation within each individual analysis, and
148 // future analyses are likely to have the same behavior. Limiting DAG width is
149 // the safe approach and will be especially important with global DAGs.
150 //
151 // MaxParallelChains default is arbitrarily high to avoid affecting
152 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
153 // sequence over this should have been converted to llvm.memcpy by the
154 // frontend. It is easy to induce this behavior with .ll code such as:
155 // %buffer = alloca [4096 x i8]
156 // %data = load [4096 x i8]* %argPtr
157 // store [4096 x i8] %data, [4096 x i8]* %buffer
158 static const unsigned MaxParallelChains = 64;
159 
160 // True if the Value passed requires ABI mangling as it is a parameter to a
161 // function or a return value from a function which is not an intrinsic.
162 static bool isABIRegCopy(const Value *V) {
163   const bool IsRetInst = V && isa<ReturnInst>(V);
164   const bool IsCallInst = V && isa<CallInst>(V);
165   const bool IsInLineAsm =
166       IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
167   const bool IsIndirectFunctionCall =
168       IsCallInst && !IsInLineAsm &&
169       !static_cast<const CallInst *>(V)->getCalledFunction();
170   // It is possible that the call instruction is an inline asm statement or an
171   // indirect function call in which case the return value of
172   // getCalledFunction() would be nullptr.
173   const bool IsInstrinsicCall =
174       IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
175       static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
176           Intrinsic::not_intrinsic;
177 
178   return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
179 }
180 
181 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
182                                       const SDValue *Parts, unsigned NumParts,
183                                       MVT PartVT, EVT ValueVT, const Value *V,
184                                       bool IsABIRegCopy);
185 
186 /// getCopyFromParts - Create a value that contains the specified legal parts
187 /// combined into the value they represent.  If the parts combine to a type
188 /// larger than ValueVT then AssertOp can be used to specify whether the extra
189 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
190 /// (ISD::AssertSext).
191 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
192                                 const SDValue *Parts, unsigned NumParts,
193                                 MVT PartVT, EVT ValueVT, const Value *V,
194                                 Optional<ISD::NodeType> AssertOp = None,
195                                 bool IsABIRegCopy = false) {
196   if (ValueVT.isVector())
197     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
198                                   PartVT, ValueVT, V, IsABIRegCopy);
199 
200   assert(NumParts > 0 && "No parts to assemble!");
201   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
202   SDValue Val = Parts[0];
203 
204   if (NumParts > 1) {
205     // Assemble the value from multiple parts.
206     if (ValueVT.isInteger()) {
207       unsigned PartBits = PartVT.getSizeInBits();
208       unsigned ValueBits = ValueVT.getSizeInBits();
209 
210       // Assemble the power of 2 part.
211       unsigned RoundParts = NumParts & (NumParts - 1) ?
212         1 << Log2_32(NumParts) : NumParts;
213       unsigned RoundBits = PartBits * RoundParts;
214       EVT RoundVT = RoundBits == ValueBits ?
215         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
216       SDValue Lo, Hi;
217 
218       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
219 
220       if (RoundParts > 2) {
221         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
222                               PartVT, HalfVT, V);
223         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
224                               RoundParts / 2, PartVT, HalfVT, V);
225       } else {
226         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
227         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
228       }
229 
230       if (DAG.getDataLayout().isBigEndian())
231         std::swap(Lo, Hi);
232 
233       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
234 
235       if (RoundParts < NumParts) {
236         // Assemble the trailing non-power-of-2 part.
237         unsigned OddParts = NumParts - RoundParts;
238         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
239         Hi = getCopyFromParts(DAG, DL,
240                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
241 
242         // Combine the round and odd parts.
243         Lo = Val;
244         if (DAG.getDataLayout().isBigEndian())
245           std::swap(Lo, Hi);
246         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
247         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
248         Hi =
249             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
250                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
251                                         TLI.getPointerTy(DAG.getDataLayout())));
252         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
253         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
254       }
255     } else if (PartVT.isFloatingPoint()) {
256       // FP split into multiple FP parts (for ppcf128)
257       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
258              "Unexpected split");
259       SDValue Lo, Hi;
260       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
261       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
262       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
263         std::swap(Lo, Hi);
264       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
265     } else {
266       // FP split into integer parts (soft fp)
267       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
268              !PartVT.isVector() && "Unexpected split");
269       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
270       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
271     }
272   }
273 
274   // There is now one part, held in Val.  Correct it to match ValueVT.
275   // PartEVT is the type of the register class that holds the value.
276   // ValueVT is the type of the inline asm operation.
277   EVT PartEVT = Val.getValueType();
278 
279   if (PartEVT == ValueVT)
280     return Val;
281 
282   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
283       ValueVT.bitsLT(PartEVT)) {
284     // For an FP value in an integer part, we need to truncate to the right
285     // width first.
286     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
287     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
288   }
289 
290   // Handle types that have the same size.
291   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
292     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
293 
294   // Handle types with different sizes.
295   if (PartEVT.isInteger() && ValueVT.isInteger()) {
296     if (ValueVT.bitsLT(PartEVT)) {
297       // For a truncate, see if we have any information to
298       // indicate whether the truncated bits will always be
299       // zero or sign-extension.
300       if (AssertOp.hasValue())
301         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
302                           DAG.getValueType(ValueVT));
303       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
304     }
305     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
306   }
307 
308   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
309     // FP_ROUND's are always exact here.
310     if (ValueVT.bitsLT(Val.getValueType()))
311       return DAG.getNode(
312           ISD::FP_ROUND, DL, ValueVT, Val,
313           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
314 
315     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
316   }
317 
318   llvm_unreachable("Unknown mismatch!");
319 }
320 
321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
322                                               const Twine &ErrMsg) {
323   const Instruction *I = dyn_cast_or_null<Instruction>(V);
324   if (!V)
325     return Ctx.emitError(ErrMsg);
326 
327   const char *AsmError = ", possible invalid constraint for vector type";
328   if (const CallInst *CI = dyn_cast<CallInst>(I))
329     if (isa<InlineAsm>(CI->getCalledValue()))
330       return Ctx.emitError(I, ErrMsg + AsmError);
331 
332   return Ctx.emitError(I, ErrMsg);
333 }
334 
335 /// getCopyFromPartsVector - Create a value that contains the specified legal
336 /// parts combined into the value they represent.  If the parts combine to a
337 /// type larger than ValueVT then AssertOp can be used to specify whether the
338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
339 /// ValueVT (ISD::AssertSext).
340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
341                                       const SDValue *Parts, unsigned NumParts,
342                                       MVT PartVT, EVT ValueVT, const Value *V,
343                                       bool IsABIRegCopy) {
344   assert(ValueVT.isVector() && "Not a vector value");
345   assert(NumParts > 0 && "No parts to assemble!");
346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
347   SDValue Val = Parts[0];
348 
349   // Handle a multi-element vector.
350   if (NumParts > 1) {
351     EVT IntermediateVT;
352     MVT RegisterVT;
353     unsigned NumIntermediates;
354     unsigned NumRegs;
355 
356     if (IsABIRegCopy) {
357       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
358           *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
359           RegisterVT);
360     } else {
361       NumRegs =
362           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
363                                      NumIntermediates, RegisterVT);
364     }
365 
366     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
367     NumParts = NumRegs; // Silence a compiler warning.
368     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
369     assert(RegisterVT.getSizeInBits() ==
370            Parts[0].getSimpleValueType().getSizeInBits() &&
371            "Part type sizes don't match!");
372 
373     // Assemble the parts into intermediate operands.
374     SmallVector<SDValue, 8> Ops(NumIntermediates);
375     if (NumIntermediates == NumParts) {
376       // If the register was not expanded, truncate or copy the value,
377       // as appropriate.
378       for (unsigned i = 0; i != NumParts; ++i)
379         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
380                                   PartVT, IntermediateVT, V);
381     } else if (NumParts > 0) {
382       // If the intermediate type was expanded, build the intermediate
383       // operands from the parts.
384       assert(NumParts % NumIntermediates == 0 &&
385              "Must expand into a divisible number of parts!");
386       unsigned Factor = NumParts / NumIntermediates;
387       for (unsigned i = 0; i != NumIntermediates; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
389                                   PartVT, IntermediateVT, V);
390     }
391 
392     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
393     // intermediate operands.
394     EVT BuiltVectorTy =
395         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
396                          (IntermediateVT.isVector()
397                               ? IntermediateVT.getVectorNumElements() * NumParts
398                               : NumIntermediates));
399     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
400                                                 : ISD::BUILD_VECTOR,
401                       DL, BuiltVectorTy, Ops);
402   }
403 
404   // There is now one part, held in Val.  Correct it to match ValueVT.
405   EVT PartEVT = Val.getValueType();
406 
407   if (PartEVT == ValueVT)
408     return Val;
409 
410   if (PartEVT.isVector()) {
411     // If the element type of the source/dest vectors are the same, but the
412     // parts vector has more elements than the value vector, then we have a
413     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
414     // elements we want.
415     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
416       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
417              "Cannot narrow, it would be a lossy transformation");
418       return DAG.getNode(
419           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
420           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
421     }
422 
423     // Vector/Vector bitcast.
424     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
425       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
426 
427     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
428       "Cannot handle this kind of promotion");
429     // Promoted vector extract
430     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
431 
432   }
433 
434   // Trivial bitcast if the types are the same size and the destination
435   // vector type is legal.
436   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
437       TLI.isTypeLegal(ValueVT))
438     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
439 
440   if (ValueVT.getVectorNumElements() != 1) {
441      // Certain ABIs require that vectors are passed as integers. For vectors
442      // are the same size, this is an obvious bitcast.
443      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
444        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
445      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
446        // Bitcast Val back the original type and extract the corresponding
447        // vector we want.
448        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
449        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
450                                            ValueVT.getVectorElementType(), Elts);
451        Val = DAG.getBitcast(WiderVecType, Val);
452        return DAG.getNode(
453            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
454            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
455      }
456 
457      diagnosePossiblyInvalidConstraint(
458          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
459      return DAG.getUNDEF(ValueVT);
460   }
461 
462   // Handle cases such as i8 -> <1 x i1>
463   EVT ValueSVT = ValueVT.getVectorElementType();
464   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
465     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
466                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
467 
468   return DAG.getBuildVector(ValueVT, DL, Val);
469 }
470 
471 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
472                                  SDValue Val, SDValue *Parts, unsigned NumParts,
473                                  MVT PartVT, const Value *V, bool IsABIRegCopy);
474 
475 /// getCopyToParts - Create a series of nodes that contain the specified value
476 /// split into legal parts.  If the parts contain more bits than Val, then, for
477 /// integers, ExtendKind can be used to specify how to generate the extra bits.
478 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
479                            SDValue *Parts, unsigned NumParts, MVT PartVT,
480                            const Value *V,
481                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
482                            bool IsABIRegCopy = false) {
483   EVT ValueVT = Val.getValueType();
484 
485   // Handle the vector case separately.
486   if (ValueVT.isVector())
487     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
488                                 IsABIRegCopy);
489 
490   unsigned PartBits = PartVT.getSizeInBits();
491   unsigned OrigNumParts = NumParts;
492   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
493          "Copying to an illegal type!");
494 
495   if (NumParts == 0)
496     return;
497 
498   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
499   EVT PartEVT = PartVT;
500   if (PartEVT == ValueVT) {
501     assert(NumParts == 1 && "No-op copy with multiple parts!");
502     Parts[0] = Val;
503     return;
504   }
505 
506   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
507     // If the parts cover more bits than the value has, promote the value.
508     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
509       assert(NumParts == 1 && "Do not know what to promote to!");
510       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
511     } else {
512       if (ValueVT.isFloatingPoint()) {
513         // FP values need to be bitcast, then extended if they are being put
514         // into a larger container.
515         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
516         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
517       }
518       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
519              ValueVT.isInteger() &&
520              "Unknown mismatch!");
521       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
522       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
523       if (PartVT == MVT::x86mmx)
524         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525     }
526   } else if (PartBits == ValueVT.getSizeInBits()) {
527     // Different types of the same size.
528     assert(NumParts == 1 && PartEVT != ValueVT);
529     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
530   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
531     // If the parts cover less bits than value has, truncate the value.
532     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
533            ValueVT.isInteger() &&
534            "Unknown mismatch!");
535     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
536     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
537     if (PartVT == MVT::x86mmx)
538       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   }
540 
541   // The value may have changed - recompute ValueVT.
542   ValueVT = Val.getValueType();
543   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
544          "Failed to tile the value with PartVT!");
545 
546   if (NumParts == 1) {
547     if (PartEVT != ValueVT) {
548       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
549                                         "scalar-to-vector conversion failed");
550       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
551     }
552 
553     Parts[0] = Val;
554     return;
555   }
556 
557   // Expand the value into multiple parts.
558   if (NumParts & (NumParts - 1)) {
559     // The number of parts is not a power of 2.  Split off and copy the tail.
560     assert(PartVT.isInteger() && ValueVT.isInteger() &&
561            "Do not know what to expand to!");
562     unsigned RoundParts = 1 << Log2_32(NumParts);
563     unsigned RoundBits = RoundParts * PartBits;
564     unsigned OddParts = NumParts - RoundParts;
565     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
566                                  DAG.getIntPtrConstant(RoundBits, DL));
567     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
568 
569     if (DAG.getDataLayout().isBigEndian())
570       // The odd parts were reversed by getCopyToParts - unreverse them.
571       std::reverse(Parts + RoundParts, Parts + NumParts);
572 
573     NumParts = RoundParts;
574     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
575     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
576   }
577 
578   // The number of parts is a power of 2.  Repeatedly bisect the value using
579   // EXTRACT_ELEMENT.
580   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
581                          EVT::getIntegerVT(*DAG.getContext(),
582                                            ValueVT.getSizeInBits()),
583                          Val);
584 
585   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
586     for (unsigned i = 0; i < NumParts; i += StepSize) {
587       unsigned ThisBits = StepSize * PartBits / 2;
588       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
589       SDValue &Part0 = Parts[i];
590       SDValue &Part1 = Parts[i+StepSize/2];
591 
592       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
593                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
594       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
595                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
596 
597       if (ThisBits == PartBits && ThisVT != PartVT) {
598         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
599         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
600       }
601     }
602   }
603 
604   if (DAG.getDataLayout().isBigEndian())
605     std::reverse(Parts, Parts + OrigNumParts);
606 }
607 
608 
609 /// getCopyToPartsVector - Create a series of nodes that contain the specified
610 /// value split into legal parts.
611 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
612                                  SDValue Val, SDValue *Parts, unsigned NumParts,
613                                  MVT PartVT, const Value *V,
614                                  bool IsABIRegCopy) {
615   EVT ValueVT = Val.getValueType();
616   assert(ValueVT.isVector() && "Not a vector");
617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
618 
619   if (NumParts == 1) {
620     EVT PartEVT = PartVT;
621     if (PartEVT == ValueVT) {
622       // Nothing to do.
623     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
624       // Bitconvert vector->vector case.
625       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
626     } else if (PartVT.isVector() &&
627                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
628                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
629       EVT ElementVT = PartVT.getVectorElementType();
630       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
631       // undef elements.
632       SmallVector<SDValue, 16> Ops;
633       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
634         Ops.push_back(DAG.getNode(
635             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
636             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
637 
638       for (unsigned i = ValueVT.getVectorNumElements(),
639            e = PartVT.getVectorNumElements(); i != e; ++i)
640         Ops.push_back(DAG.getUNDEF(ElementVT));
641 
642       Val = DAG.getBuildVector(PartVT, DL, Ops);
643 
644       // FIXME: Use CONCAT for 2x -> 4x.
645 
646       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
647       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
648     } else if (PartVT.isVector() &&
649                PartEVT.getVectorElementType().bitsGE(
650                  ValueVT.getVectorElementType()) &&
651                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
652 
653       // Promoted vector extract
654       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
655     } else {
656       if (ValueVT.getVectorNumElements() == 1) {
657         Val = DAG.getNode(
658             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
659             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
660       } else {
661         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
662                "lossy conversion of vector to scalar type");
663         EVT IntermediateType =
664             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
665         Val = DAG.getBitcast(IntermediateType, Val);
666         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
667       }
668     }
669 
670     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
671     Parts[0] = Val;
672     return;
673   }
674 
675   // Handle a multi-element vector.
676   EVT IntermediateVT;
677   MVT RegisterVT;
678   unsigned NumIntermediates;
679   unsigned NumRegs;
680   if (IsABIRegCopy) {
681     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
682         *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
683         RegisterVT);
684   } else {
685     NumRegs =
686         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
687                                    NumIntermediates, RegisterVT);
688   }
689   unsigned NumElements = ValueVT.getVectorNumElements();
690 
691   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
692   NumParts = NumRegs; // Silence a compiler warning.
693   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
694 
695   // Convert the vector to the appropiate type if necessary.
696   unsigned DestVectorNoElts =
697       NumIntermediates *
698       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
699   EVT BuiltVectorTy = EVT::getVectorVT(
700       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
701   if (Val.getValueType() != BuiltVectorTy)
702     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
703 
704   // Split the vector into intermediate operands.
705   SmallVector<SDValue, 8> Ops(NumIntermediates);
706   for (unsigned i = 0; i != NumIntermediates; ++i) {
707     if (IntermediateVT.isVector())
708       Ops[i] =
709           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
710                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
711                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
712     else
713       Ops[i] = DAG.getNode(
714           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
715           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
716   }
717 
718   // Split the intermediate operands into legal parts.
719   if (NumParts == NumIntermediates) {
720     // If the register was not expanded, promote or copy the value,
721     // as appropriate.
722     for (unsigned i = 0; i != NumParts; ++i)
723       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
724   } else if (NumParts > 0) {
725     // If the intermediate type was expanded, split each the value into
726     // legal parts.
727     assert(NumIntermediates != 0 && "division by zero");
728     assert(NumParts % NumIntermediates == 0 &&
729            "Must expand into a divisible number of parts!");
730     unsigned Factor = NumParts / NumIntermediates;
731     for (unsigned i = 0; i != NumIntermediates; ++i)
732       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
733   }
734 }
735 
736 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
737                            EVT valuevt, bool IsABIMangledValue)
738     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
739       RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
740 
741 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
742                            const DataLayout &DL, unsigned Reg, Type *Ty,
743                            bool IsABIMangledValue) {
744   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
745 
746   IsABIMangled = IsABIMangledValue;
747 
748   for (EVT ValueVT : ValueVTs) {
749     unsigned NumRegs = IsABIMangledValue
750                            ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
751                            : TLI.getNumRegisters(Context, ValueVT);
752     MVT RegisterVT = IsABIMangledValue
753                          ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
754                          : TLI.getRegisterType(Context, ValueVT);
755     for (unsigned i = 0; i != NumRegs; ++i)
756       Regs.push_back(Reg + i);
757     RegVTs.push_back(RegisterVT);
758     RegCount.push_back(NumRegs);
759     Reg += NumRegs;
760   }
761 }
762 
763 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
764                                       FunctionLoweringInfo &FuncInfo,
765                                       const SDLoc &dl, SDValue &Chain,
766                                       SDValue *Flag, const Value *V) const {
767   // A Value with type {} or [0 x %t] needs no registers.
768   if (ValueVTs.empty())
769     return SDValue();
770 
771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
772 
773   // Assemble the legal parts into the final values.
774   SmallVector<SDValue, 4> Values(ValueVTs.size());
775   SmallVector<SDValue, 8> Parts;
776   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
777     // Copy the legal parts from the registers.
778     EVT ValueVT = ValueVTs[Value];
779     unsigned NumRegs = RegCount[Value];
780     MVT RegisterVT = IsABIMangled
781                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
782                          : RegVTs[Value];
783 
784     Parts.resize(NumRegs);
785     for (unsigned i = 0; i != NumRegs; ++i) {
786       SDValue P;
787       if (!Flag) {
788         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
789       } else {
790         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
791         *Flag = P.getValue(2);
792       }
793 
794       Chain = P.getValue(1);
795       Parts[i] = P;
796 
797       // If the source register was virtual and if we know something about it,
798       // add an assert node.
799       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
800           !RegisterVT.isInteger() || RegisterVT.isVector())
801         continue;
802 
803       const FunctionLoweringInfo::LiveOutInfo *LOI =
804         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
805       if (!LOI)
806         continue;
807 
808       unsigned RegSize = RegisterVT.getSizeInBits();
809       unsigned NumSignBits = LOI->NumSignBits;
810       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
811 
812       if (NumZeroBits == RegSize) {
813         // The current value is a zero.
814         // Explicitly express that as it would be easier for
815         // optimizations to kick in.
816         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
817         continue;
818       }
819 
820       // FIXME: We capture more information than the dag can represent.  For
821       // now, just use the tightest assertzext/assertsext possible.
822       bool isSExt = true;
823       EVT FromVT(MVT::Other);
824       if (NumSignBits == RegSize) {
825         isSExt = true;   // ASSERT SEXT 1
826         FromVT = MVT::i1;
827       } else if (NumZeroBits >= RegSize - 1) {
828         isSExt = false;  // ASSERT ZEXT 1
829         FromVT = MVT::i1;
830       } else if (NumSignBits > RegSize - 8) {
831         isSExt = true;   // ASSERT SEXT 8
832         FromVT = MVT::i8;
833       } else if (NumZeroBits >= RegSize - 8) {
834         isSExt = false;  // ASSERT ZEXT 8
835         FromVT = MVT::i8;
836       } else if (NumSignBits > RegSize - 16) {
837         isSExt = true;   // ASSERT SEXT 16
838         FromVT = MVT::i16;
839       } else if (NumZeroBits >= RegSize - 16) {
840         isSExt = false;  // ASSERT ZEXT 16
841         FromVT = MVT::i16;
842       } else if (NumSignBits > RegSize - 32) {
843         isSExt = true;   // ASSERT SEXT 32
844         FromVT = MVT::i32;
845       } else if (NumZeroBits >= RegSize - 32) {
846         isSExt = false;  // ASSERT ZEXT 32
847         FromVT = MVT::i32;
848       } else {
849         continue;
850       }
851       // Add an assertion node.
852       assert(FromVT != MVT::Other);
853       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
854                              RegisterVT, P, DAG.getValueType(FromVT));
855     }
856 
857     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
858                                      NumRegs, RegisterVT, ValueVT, V);
859     Part += NumRegs;
860     Parts.clear();
861   }
862 
863   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
864 }
865 
866 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
867                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
868                                  const Value *V,
869                                  ISD::NodeType PreferredExtendType) const {
870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
871   ISD::NodeType ExtendKind = PreferredExtendType;
872 
873   // Get the list of the values's legal parts.
874   unsigned NumRegs = Regs.size();
875   SmallVector<SDValue, 8> Parts(NumRegs);
876   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
877     unsigned NumParts = RegCount[Value];
878 
879     MVT RegisterVT = IsABIMangled
880                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
881                          : RegVTs[Value];
882 
883     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
884       ExtendKind = ISD::ZERO_EXTEND;
885 
886     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
887                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
888     Part += NumParts;
889   }
890 
891   // Copy the parts into the registers.
892   SmallVector<SDValue, 8> Chains(NumRegs);
893   for (unsigned i = 0; i != NumRegs; ++i) {
894     SDValue Part;
895     if (!Flag) {
896       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
897     } else {
898       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
899       *Flag = Part.getValue(1);
900     }
901 
902     Chains[i] = Part.getValue(0);
903   }
904 
905   if (NumRegs == 1 || Flag)
906     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
907     // flagged to it. That is the CopyToReg nodes and the user are considered
908     // a single scheduling unit. If we create a TokenFactor and return it as
909     // chain, then the TokenFactor is both a predecessor (operand) of the
910     // user as well as a successor (the TF operands are flagged to the user).
911     // c1, f1 = CopyToReg
912     // c2, f2 = CopyToReg
913     // c3     = TokenFactor c1, c2
914     // ...
915     //        = op c3, ..., f2
916     Chain = Chains[NumRegs-1];
917   else
918     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
919 }
920 
921 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
922                                         unsigned MatchingIdx, const SDLoc &dl,
923                                         SelectionDAG &DAG,
924                                         std::vector<SDValue> &Ops) const {
925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
926 
927   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
928   if (HasMatching)
929     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
930   else if (!Regs.empty() &&
931            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
932     // Put the register class of the virtual registers in the flag word.  That
933     // way, later passes can recompute register class constraints for inline
934     // assembly as well as normal instructions.
935     // Don't do this for tied operands that can use the regclass information
936     // from the def.
937     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
938     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
939     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
940   }
941 
942   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
943   Ops.push_back(Res);
944 
945   if (Code == InlineAsm::Kind_Clobber) {
946     // Clobbers should always have a 1:1 mapping with registers, and may
947     // reference registers that have illegal (e.g. vector) types. Hence, we
948     // shouldn't try to apply any sort of splitting logic to them.
949     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
950            "No 1:1 mapping from clobbers to regs?");
951     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
952     (void)SP;
953     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
954       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
955       assert(
956           (Regs[I] != SP ||
957            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
958           "If we clobbered the stack pointer, MFI should know about it.");
959     }
960     return;
961   }
962 
963   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
964     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
965     MVT RegisterVT = RegVTs[Value];
966     for (unsigned i = 0; i != NumRegs; ++i) {
967       assert(Reg < Regs.size() && "Mismatch in # registers expected");
968       unsigned TheReg = Regs[Reg++];
969       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
970     }
971   }
972 }
973 
974 SmallVector<std::pair<unsigned, unsigned>, 4>
975 RegsForValue::getRegsAndSizes() const {
976   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
977   unsigned I = 0;
978   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
979     unsigned RegCount = std::get<0>(CountAndVT);
980     MVT RegisterVT = std::get<1>(CountAndVT);
981     unsigned RegisterSize = RegisterVT.getSizeInBits();
982     for (unsigned E = I + RegCount; I != E; ++I)
983       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
984   }
985   return OutVec;
986 }
987 
988 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
989                                const TargetLibraryInfo *li) {
990   AA = aa;
991   GFI = gfi;
992   LibInfo = li;
993   DL = &DAG.getDataLayout();
994   Context = DAG.getContext();
995   LPadToCallSiteMap.clear();
996 }
997 
998 void SelectionDAGBuilder::clear() {
999   NodeMap.clear();
1000   UnusedArgNodeMap.clear();
1001   PendingLoads.clear();
1002   PendingExports.clear();
1003   CurInst = nullptr;
1004   HasTailCall = false;
1005   SDNodeOrder = LowestSDNodeOrder;
1006   StatepointLowering.clear();
1007 }
1008 
1009 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1010   DanglingDebugInfoMap.clear();
1011 }
1012 
1013 SDValue SelectionDAGBuilder::getRoot() {
1014   if (PendingLoads.empty())
1015     return DAG.getRoot();
1016 
1017   if (PendingLoads.size() == 1) {
1018     SDValue Root = PendingLoads[0];
1019     DAG.setRoot(Root);
1020     PendingLoads.clear();
1021     return Root;
1022   }
1023 
1024   // Otherwise, we have to make a token factor node.
1025   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1026                              PendingLoads);
1027   PendingLoads.clear();
1028   DAG.setRoot(Root);
1029   return Root;
1030 }
1031 
1032 SDValue SelectionDAGBuilder::getControlRoot() {
1033   SDValue Root = DAG.getRoot();
1034 
1035   if (PendingExports.empty())
1036     return Root;
1037 
1038   // Turn all of the CopyToReg chains into one factored node.
1039   if (Root.getOpcode() != ISD::EntryToken) {
1040     unsigned i = 0, e = PendingExports.size();
1041     for (; i != e; ++i) {
1042       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1043       if (PendingExports[i].getNode()->getOperand(0) == Root)
1044         break;  // Don't add the root if we already indirectly depend on it.
1045     }
1046 
1047     if (i == e)
1048       PendingExports.push_back(Root);
1049   }
1050 
1051   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1052                      PendingExports);
1053   PendingExports.clear();
1054   DAG.setRoot(Root);
1055   return Root;
1056 }
1057 
1058 void SelectionDAGBuilder::visit(const Instruction &I) {
1059   // Set up outgoing PHI node register values before emitting the terminator.
1060   if (isa<TerminatorInst>(&I)) {
1061     HandlePHINodesInSuccessorBlocks(I.getParent());
1062   }
1063 
1064   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1065   if (!isa<DbgInfoIntrinsic>(I))
1066     ++SDNodeOrder;
1067 
1068   CurInst = &I;
1069 
1070   visit(I.getOpcode(), I);
1071 
1072   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
1073       !isStatepoint(&I)) // statepoints handle their exports internally
1074     CopyToExportRegsIfNeeded(&I);
1075 
1076   CurInst = nullptr;
1077 }
1078 
1079 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1080   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1081 }
1082 
1083 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1084   // Note: this doesn't use InstVisitor, because it has to work with
1085   // ConstantExpr's in addition to instructions.
1086   switch (Opcode) {
1087   default: llvm_unreachable("Unknown instruction type encountered!");
1088     // Build the switch statement using the Instruction.def file.
1089 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1090     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1091 #include "llvm/IR/Instruction.def"
1092   }
1093 }
1094 
1095 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1096                                                 const DIExpression *Expr) {
1097   for (auto &DDIMI : DanglingDebugInfoMap)
1098     for (auto &DDI : DDIMI.second)
1099       if (DDI.getDI()) {
1100         const DbgValueInst *DI = DDI.getDI();
1101         DIVariable *DanglingVariable = DI->getVariable();
1102         DIExpression *DanglingExpr = DI->getExpression();
1103         if (DanglingVariable == Variable &&
1104             Expr->fragmentsOverlap(DanglingExpr)) {
1105           DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1106           DDI = DanglingDebugInfo();
1107         }
1108       }
1109 }
1110 
1111 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1112 // generate the debug data structures now that we've seen its definition.
1113 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1114                                                    SDValue Val) {
1115   DanglingDebugInfoVector &DDIV = DanglingDebugInfoMap[V];
1116   for (auto &DDI : DDIV) {
1117     if (!DDI.getDI())
1118       continue;
1119     const DbgValueInst *DI = DDI.getDI();
1120     DebugLoc dl = DDI.getdl();
1121     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1122     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1123     DILocalVariable *Variable = DI->getVariable();
1124     DIExpression *Expr = DI->getExpression();
1125     assert(Variable->isValidLocationForIntrinsic(dl) &&
1126            "Expected inlined-at fields to agree");
1127     SDDbgValue *SDV;
1128     if (Val.getNode()) {
1129       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1130         DEBUG(dbgs() << "Resolve dangling debug info [order=" << DbgSDNodeOrder
1131               << "] for:\n  " << *DI << "\n");
1132         DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1133         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1134         // inserted after the definition of Val when emitting the instructions
1135         // after ISel. An alternative could be to teach
1136         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1137         DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder)
1138                 dbgs() << "changing SDNodeOrder from " << DbgSDNodeOrder
1139                        << " to " << ValSDNodeOrder << "\n");
1140         SDV = getDbgValue(Val, Variable, Expr, dl,
1141                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1142         DAG.AddDbgValue(SDV, Val.getNode(), false);
1143       } else
1144         DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1145               << "in EmitFuncArgumentDbgValue\n");
1146     } else
1147       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1148   }
1149   DanglingDebugInfoMap[V].clear();
1150 }
1151 
1152 /// getCopyFromRegs - If there was virtual register allocated for the value V
1153 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1154 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1155   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1156   SDValue Result;
1157 
1158   if (It != FuncInfo.ValueMap.end()) {
1159     unsigned InReg = It->second;
1160 
1161     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1162                      DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
1163     SDValue Chain = DAG.getEntryNode();
1164     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1165                                  V);
1166     resolveDanglingDebugInfo(V, Result);
1167   }
1168 
1169   return Result;
1170 }
1171 
1172 /// getValue - Return an SDValue for the given Value.
1173 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1174   // If we already have an SDValue for this value, use it. It's important
1175   // to do this first, so that we don't create a CopyFromReg if we already
1176   // have a regular SDValue.
1177   SDValue &N = NodeMap[V];
1178   if (N.getNode()) return N;
1179 
1180   // If there's a virtual register allocated and initialized for this
1181   // value, use it.
1182   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1183     return copyFromReg;
1184 
1185   // Otherwise create a new SDValue and remember it.
1186   SDValue Val = getValueImpl(V);
1187   NodeMap[V] = Val;
1188   resolveDanglingDebugInfo(V, Val);
1189   return Val;
1190 }
1191 
1192 // Return true if SDValue exists for the given Value
1193 bool SelectionDAGBuilder::findValue(const Value *V) const {
1194   return (NodeMap.find(V) != NodeMap.end()) ||
1195     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1196 }
1197 
1198 /// getNonRegisterValue - Return an SDValue for the given Value, but
1199 /// don't look in FuncInfo.ValueMap for a virtual register.
1200 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1201   // If we already have an SDValue for this value, use it.
1202   SDValue &N = NodeMap[V];
1203   if (N.getNode()) {
1204     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1205       // Remove the debug location from the node as the node is about to be used
1206       // in a location which may differ from the original debug location.  This
1207       // is relevant to Constant and ConstantFP nodes because they can appear
1208       // as constant expressions inside PHI nodes.
1209       N->setDebugLoc(DebugLoc());
1210     }
1211     return N;
1212   }
1213 
1214   // Otherwise create a new SDValue and remember it.
1215   SDValue Val = getValueImpl(V);
1216   NodeMap[V] = Val;
1217   resolveDanglingDebugInfo(V, Val);
1218   return Val;
1219 }
1220 
1221 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1222 /// Create an SDValue for the given value.
1223 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1225 
1226   if (const Constant *C = dyn_cast<Constant>(V)) {
1227     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1228 
1229     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1230       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1231 
1232     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1233       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1234 
1235     if (isa<ConstantPointerNull>(C)) {
1236       unsigned AS = V->getType()->getPointerAddressSpace();
1237       return DAG.getConstant(0, getCurSDLoc(),
1238                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1239     }
1240 
1241     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1242       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1243 
1244     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1245       return DAG.getUNDEF(VT);
1246 
1247     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1248       visit(CE->getOpcode(), *CE);
1249       SDValue N1 = NodeMap[V];
1250       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1251       return N1;
1252     }
1253 
1254     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1255       SmallVector<SDValue, 4> Constants;
1256       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1257            OI != OE; ++OI) {
1258         SDNode *Val = getValue(*OI).getNode();
1259         // If the operand is an empty aggregate, there are no values.
1260         if (!Val) continue;
1261         // Add each leaf value from the operand to the Constants list
1262         // to form a flattened list of all the values.
1263         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1264           Constants.push_back(SDValue(Val, i));
1265       }
1266 
1267       return DAG.getMergeValues(Constants, getCurSDLoc());
1268     }
1269 
1270     if (const ConstantDataSequential *CDS =
1271           dyn_cast<ConstantDataSequential>(C)) {
1272       SmallVector<SDValue, 4> Ops;
1273       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1274         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1275         // Add each leaf value from the operand to the Constants list
1276         // to form a flattened list of all the values.
1277         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1278           Ops.push_back(SDValue(Val, i));
1279       }
1280 
1281       if (isa<ArrayType>(CDS->getType()))
1282         return DAG.getMergeValues(Ops, getCurSDLoc());
1283       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1284     }
1285 
1286     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1287       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1288              "Unknown struct or array constant!");
1289 
1290       SmallVector<EVT, 4> ValueVTs;
1291       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1292       unsigned NumElts = ValueVTs.size();
1293       if (NumElts == 0)
1294         return SDValue(); // empty struct
1295       SmallVector<SDValue, 4> Constants(NumElts);
1296       for (unsigned i = 0; i != NumElts; ++i) {
1297         EVT EltVT = ValueVTs[i];
1298         if (isa<UndefValue>(C))
1299           Constants[i] = DAG.getUNDEF(EltVT);
1300         else if (EltVT.isFloatingPoint())
1301           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1302         else
1303           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1304       }
1305 
1306       return DAG.getMergeValues(Constants, getCurSDLoc());
1307     }
1308 
1309     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1310       return DAG.getBlockAddress(BA, VT);
1311 
1312     VectorType *VecTy = cast<VectorType>(V->getType());
1313     unsigned NumElements = VecTy->getNumElements();
1314 
1315     // Now that we know the number and type of the elements, get that number of
1316     // elements into the Ops array based on what kind of constant it is.
1317     SmallVector<SDValue, 16> Ops;
1318     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1319       for (unsigned i = 0; i != NumElements; ++i)
1320         Ops.push_back(getValue(CV->getOperand(i)));
1321     } else {
1322       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1323       EVT EltVT =
1324           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1325 
1326       SDValue Op;
1327       if (EltVT.isFloatingPoint())
1328         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1329       else
1330         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1331       Ops.assign(NumElements, Op);
1332     }
1333 
1334     // Create a BUILD_VECTOR node.
1335     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1336   }
1337 
1338   // If this is a static alloca, generate it as the frameindex instead of
1339   // computation.
1340   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1341     DenseMap<const AllocaInst*, int>::iterator SI =
1342       FuncInfo.StaticAllocaMap.find(AI);
1343     if (SI != FuncInfo.StaticAllocaMap.end())
1344       return DAG.getFrameIndex(SI->second,
1345                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1346   }
1347 
1348   // If this is an instruction which fast-isel has deferred, select it now.
1349   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1350     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1351 
1352     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1353                      Inst->getType(), isABIRegCopy(V));
1354     SDValue Chain = DAG.getEntryNode();
1355     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1356   }
1357 
1358   llvm_unreachable("Can't get register for value!");
1359 }
1360 
1361 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1362   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1363   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1364   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1365   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1366   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1367   if (IsMSVCCXX || IsCoreCLR)
1368     CatchPadMBB->setIsEHFuncletEntry();
1369 
1370   DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
1371 }
1372 
1373 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1374   // Update machine-CFG edge.
1375   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1376   FuncInfo.MBB->addSuccessor(TargetMBB);
1377 
1378   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1379   bool IsSEH = isAsynchronousEHPersonality(Pers);
1380   if (IsSEH) {
1381     // If this is not a fall-through branch or optimizations are switched off,
1382     // emit the branch.
1383     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1384         TM.getOptLevel() == CodeGenOpt::None)
1385       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1386                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1387     return;
1388   }
1389 
1390   // Figure out the funclet membership for the catchret's successor.
1391   // This will be used by the FuncletLayout pass to determine how to order the
1392   // BB's.
1393   // A 'catchret' returns to the outer scope's color.
1394   Value *ParentPad = I.getCatchSwitchParentPad();
1395   const BasicBlock *SuccessorColor;
1396   if (isa<ConstantTokenNone>(ParentPad))
1397     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1398   else
1399     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1400   assert(SuccessorColor && "No parent funclet for catchret!");
1401   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1402   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1403 
1404   // Create the terminator node.
1405   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1406                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1407                             DAG.getBasicBlock(SuccessorColorMBB));
1408   DAG.setRoot(Ret);
1409 }
1410 
1411 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1412   // Don't emit any special code for the cleanuppad instruction. It just marks
1413   // the start of a funclet.
1414   FuncInfo.MBB->setIsEHFuncletEntry();
1415   FuncInfo.MBB->setIsCleanupFuncletEntry();
1416 }
1417 
1418 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1419 /// many places it could ultimately go. In the IR, we have a single unwind
1420 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1421 /// This function skips over imaginary basic blocks that hold catchswitch
1422 /// instructions, and finds all the "real" machine
1423 /// basic block destinations. As those destinations may not be successors of
1424 /// EHPadBB, here we also calculate the edge probability to those destinations.
1425 /// The passed-in Prob is the edge probability to EHPadBB.
1426 static void findUnwindDestinations(
1427     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1428     BranchProbability Prob,
1429     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1430         &UnwindDests) {
1431   EHPersonality Personality =
1432     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1433   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1434   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1435 
1436   while (EHPadBB) {
1437     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1438     BasicBlock *NewEHPadBB = nullptr;
1439     if (isa<LandingPadInst>(Pad)) {
1440       // Stop on landingpads. They are not funclets.
1441       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1442       break;
1443     } else if (isa<CleanupPadInst>(Pad)) {
1444       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1445       // personalities.
1446       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1447       UnwindDests.back().first->setIsEHFuncletEntry();
1448       break;
1449     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1450       // Add the catchpad handlers to the possible destinations.
1451       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1452         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1453         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1454         if (IsMSVCCXX || IsCoreCLR)
1455           UnwindDests.back().first->setIsEHFuncletEntry();
1456       }
1457       NewEHPadBB = CatchSwitch->getUnwindDest();
1458     } else {
1459       continue;
1460     }
1461 
1462     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1463     if (BPI && NewEHPadBB)
1464       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1465     EHPadBB = NewEHPadBB;
1466   }
1467 }
1468 
1469 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1470   // Update successor info.
1471   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1472   auto UnwindDest = I.getUnwindDest();
1473   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1474   BranchProbability UnwindDestProb =
1475       (BPI && UnwindDest)
1476           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1477           : BranchProbability::getZero();
1478   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1479   for (auto &UnwindDest : UnwindDests) {
1480     UnwindDest.first->setIsEHPad();
1481     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1482   }
1483   FuncInfo.MBB->normalizeSuccProbs();
1484 
1485   // Create the terminator node.
1486   SDValue Ret =
1487       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1488   DAG.setRoot(Ret);
1489 }
1490 
1491 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1492   report_fatal_error("visitCatchSwitch not yet implemented!");
1493 }
1494 
1495 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1497   auto &DL = DAG.getDataLayout();
1498   SDValue Chain = getControlRoot();
1499   SmallVector<ISD::OutputArg, 8> Outs;
1500   SmallVector<SDValue, 8> OutVals;
1501 
1502   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1503   // lower
1504   //
1505   //   %val = call <ty> @llvm.experimental.deoptimize()
1506   //   ret <ty> %val
1507   //
1508   // differently.
1509   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1510     LowerDeoptimizingReturn();
1511     return;
1512   }
1513 
1514   if (!FuncInfo.CanLowerReturn) {
1515     unsigned DemoteReg = FuncInfo.DemoteRegister;
1516     const Function *F = I.getParent()->getParent();
1517 
1518     // Emit a store of the return value through the virtual register.
1519     // Leave Outs empty so that LowerReturn won't try to load return
1520     // registers the usual way.
1521     SmallVector<EVT, 1> PtrValueVTs;
1522     ComputeValueVTs(TLI, DL,
1523                     F->getReturnType()->getPointerTo(
1524                         DAG.getDataLayout().getAllocaAddrSpace()),
1525                     PtrValueVTs);
1526 
1527     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1528                                         DemoteReg, PtrValueVTs[0]);
1529     SDValue RetOp = getValue(I.getOperand(0));
1530 
1531     SmallVector<EVT, 4> ValueVTs;
1532     SmallVector<uint64_t, 4> Offsets;
1533     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1534     unsigned NumValues = ValueVTs.size();
1535 
1536     SmallVector<SDValue, 4> Chains(NumValues);
1537     for (unsigned i = 0; i != NumValues; ++i) {
1538       // An aggregate return value cannot wrap around the address space, so
1539       // offsets to its parts don't wrap either.
1540       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1541       Chains[i] = DAG.getStore(
1542           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1543           // FIXME: better loc info would be nice.
1544           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1545     }
1546 
1547     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1548                         MVT::Other, Chains);
1549   } else if (I.getNumOperands() != 0) {
1550     SmallVector<EVT, 4> ValueVTs;
1551     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1552     unsigned NumValues = ValueVTs.size();
1553     if (NumValues) {
1554       SDValue RetOp = getValue(I.getOperand(0));
1555 
1556       const Function *F = I.getParent()->getParent();
1557 
1558       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1559       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1560                                           Attribute::SExt))
1561         ExtendKind = ISD::SIGN_EXTEND;
1562       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1563                                                Attribute::ZExt))
1564         ExtendKind = ISD::ZERO_EXTEND;
1565 
1566       LLVMContext &Context = F->getContext();
1567       bool RetInReg = F->getAttributes().hasAttribute(
1568           AttributeList::ReturnIndex, Attribute::InReg);
1569 
1570       for (unsigned j = 0; j != NumValues; ++j) {
1571         EVT VT = ValueVTs[j];
1572 
1573         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1574           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1575 
1576         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
1577         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
1578         SmallVector<SDValue, 4> Parts(NumParts);
1579         getCopyToParts(DAG, getCurSDLoc(),
1580                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1581                        &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
1582 
1583         // 'inreg' on function refers to return value
1584         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1585         if (RetInReg)
1586           Flags.setInReg();
1587 
1588         // Propagate extension type if any
1589         if (ExtendKind == ISD::SIGN_EXTEND)
1590           Flags.setSExt();
1591         else if (ExtendKind == ISD::ZERO_EXTEND)
1592           Flags.setZExt();
1593 
1594         for (unsigned i = 0; i < NumParts; ++i) {
1595           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1596                                         VT, /*isfixed=*/true, 0, 0));
1597           OutVals.push_back(Parts[i]);
1598         }
1599       }
1600     }
1601   }
1602 
1603   // Push in swifterror virtual register as the last element of Outs. This makes
1604   // sure swifterror virtual register will be returned in the swifterror
1605   // physical register.
1606   const Function *F = I.getParent()->getParent();
1607   if (TLI.supportSwiftError() &&
1608       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1609     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1610     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1611     Flags.setSwiftError();
1612     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1613                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1614                                   true /*isfixed*/, 1 /*origidx*/,
1615                                   0 /*partOffs*/));
1616     // Create SDNode for the swifterror virtual register.
1617     OutVals.push_back(
1618         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1619                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1620                         EVT(TLI.getPointerTy(DL))));
1621   }
1622 
1623   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1624   CallingConv::ID CallConv =
1625     DAG.getMachineFunction().getFunction().getCallingConv();
1626   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1627       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1628 
1629   // Verify that the target's LowerReturn behaved as expected.
1630   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1631          "LowerReturn didn't return a valid chain!");
1632 
1633   // Update the DAG with the new chain value resulting from return lowering.
1634   DAG.setRoot(Chain);
1635 }
1636 
1637 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1638 /// created for it, emit nodes to copy the value into the virtual
1639 /// registers.
1640 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1641   // Skip empty types
1642   if (V->getType()->isEmptyTy())
1643     return;
1644 
1645   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1646   if (VMI != FuncInfo.ValueMap.end()) {
1647     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1648     CopyValueToVirtualRegister(V, VMI->second);
1649   }
1650 }
1651 
1652 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1653 /// the current basic block, add it to ValueMap now so that we'll get a
1654 /// CopyTo/FromReg.
1655 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1656   // No need to export constants.
1657   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1658 
1659   // Already exported?
1660   if (FuncInfo.isExportedInst(V)) return;
1661 
1662   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1663   CopyValueToVirtualRegister(V, Reg);
1664 }
1665 
1666 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1667                                                      const BasicBlock *FromBB) {
1668   // The operands of the setcc have to be in this block.  We don't know
1669   // how to export them from some other block.
1670   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1671     // Can export from current BB.
1672     if (VI->getParent() == FromBB)
1673       return true;
1674 
1675     // Is already exported, noop.
1676     return FuncInfo.isExportedInst(V);
1677   }
1678 
1679   // If this is an argument, we can export it if the BB is the entry block or
1680   // if it is already exported.
1681   if (isa<Argument>(V)) {
1682     if (FromBB == &FromBB->getParent()->getEntryBlock())
1683       return true;
1684 
1685     // Otherwise, can only export this if it is already exported.
1686     return FuncInfo.isExportedInst(V);
1687   }
1688 
1689   // Otherwise, constants can always be exported.
1690   return true;
1691 }
1692 
1693 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1694 BranchProbability
1695 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1696                                         const MachineBasicBlock *Dst) const {
1697   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1698   const BasicBlock *SrcBB = Src->getBasicBlock();
1699   const BasicBlock *DstBB = Dst->getBasicBlock();
1700   if (!BPI) {
1701     // If BPI is not available, set the default probability as 1 / N, where N is
1702     // the number of successors.
1703     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1704     return BranchProbability(1, SuccSize);
1705   }
1706   return BPI->getEdgeProbability(SrcBB, DstBB);
1707 }
1708 
1709 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1710                                                MachineBasicBlock *Dst,
1711                                                BranchProbability Prob) {
1712   if (!FuncInfo.BPI)
1713     Src->addSuccessorWithoutProb(Dst);
1714   else {
1715     if (Prob.isUnknown())
1716       Prob = getEdgeProbability(Src, Dst);
1717     Src->addSuccessor(Dst, Prob);
1718   }
1719 }
1720 
1721 static bool InBlock(const Value *V, const BasicBlock *BB) {
1722   if (const Instruction *I = dyn_cast<Instruction>(V))
1723     return I->getParent() == BB;
1724   return true;
1725 }
1726 
1727 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1728 /// This function emits a branch and is used at the leaves of an OR or an
1729 /// AND operator tree.
1730 void
1731 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1732                                                   MachineBasicBlock *TBB,
1733                                                   MachineBasicBlock *FBB,
1734                                                   MachineBasicBlock *CurBB,
1735                                                   MachineBasicBlock *SwitchBB,
1736                                                   BranchProbability TProb,
1737                                                   BranchProbability FProb,
1738                                                   bool InvertCond) {
1739   const BasicBlock *BB = CurBB->getBasicBlock();
1740 
1741   // If the leaf of the tree is a comparison, merge the condition into
1742   // the caseblock.
1743   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1744     // The operands of the cmp have to be in this block.  We don't know
1745     // how to export them from some other block.  If this is the first block
1746     // of the sequence, no exporting is needed.
1747     if (CurBB == SwitchBB ||
1748         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1749          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1750       ISD::CondCode Condition;
1751       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1752         ICmpInst::Predicate Pred =
1753             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1754         Condition = getICmpCondCode(Pred);
1755       } else {
1756         const FCmpInst *FC = cast<FCmpInst>(Cond);
1757         FCmpInst::Predicate Pred =
1758             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1759         Condition = getFCmpCondCode(Pred);
1760         if (TM.Options.NoNaNsFPMath)
1761           Condition = getFCmpCodeWithoutNaN(Condition);
1762       }
1763 
1764       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1765                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1766       SwitchCases.push_back(CB);
1767       return;
1768     }
1769   }
1770 
1771   // Create a CaseBlock record representing this branch.
1772   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1773   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1774                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1775   SwitchCases.push_back(CB);
1776 }
1777 
1778 /// FindMergedConditions - If Cond is an expression like
1779 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1780                                                MachineBasicBlock *TBB,
1781                                                MachineBasicBlock *FBB,
1782                                                MachineBasicBlock *CurBB,
1783                                                MachineBasicBlock *SwitchBB,
1784                                                Instruction::BinaryOps Opc,
1785                                                BranchProbability TProb,
1786                                                BranchProbability FProb,
1787                                                bool InvertCond) {
1788   // Skip over not part of the tree and remember to invert op and operands at
1789   // next level.
1790   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
1791     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
1792     if (InBlock(CondOp, CurBB->getBasicBlock())) {
1793       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1794                            !InvertCond);
1795       return;
1796     }
1797   }
1798 
1799   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1800   // Compute the effective opcode for Cond, taking into account whether it needs
1801   // to be inverted, e.g.
1802   //   and (not (or A, B)), C
1803   // gets lowered as
1804   //   and (and (not A, not B), C)
1805   unsigned BOpc = 0;
1806   if (BOp) {
1807     BOpc = BOp->getOpcode();
1808     if (InvertCond) {
1809       if (BOpc == Instruction::And)
1810         BOpc = Instruction::Or;
1811       else if (BOpc == Instruction::Or)
1812         BOpc = Instruction::And;
1813     }
1814   }
1815 
1816   // If this node is not part of the or/and tree, emit it as a branch.
1817   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1818       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1819       BOp->getParent() != CurBB->getBasicBlock() ||
1820       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1821       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1822     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1823                                  TProb, FProb, InvertCond);
1824     return;
1825   }
1826 
1827   //  Create TmpBB after CurBB.
1828   MachineFunction::iterator BBI(CurBB);
1829   MachineFunction &MF = DAG.getMachineFunction();
1830   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1831   CurBB->getParent()->insert(++BBI, TmpBB);
1832 
1833   if (Opc == Instruction::Or) {
1834     // Codegen X | Y as:
1835     // BB1:
1836     //   jmp_if_X TBB
1837     //   jmp TmpBB
1838     // TmpBB:
1839     //   jmp_if_Y TBB
1840     //   jmp FBB
1841     //
1842 
1843     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1844     // The requirement is that
1845     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1846     //     = TrueProb for original BB.
1847     // Assuming the original probabilities are A and B, one choice is to set
1848     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1849     // A/(1+B) and 2B/(1+B). This choice assumes that
1850     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1851     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1852     // TmpBB, but the math is more complicated.
1853 
1854     auto NewTrueProb = TProb / 2;
1855     auto NewFalseProb = TProb / 2 + FProb;
1856     // Emit the LHS condition.
1857     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1858                          NewTrueProb, NewFalseProb, InvertCond);
1859 
1860     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1861     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1862     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1863     // Emit the RHS condition into TmpBB.
1864     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1865                          Probs[0], Probs[1], InvertCond);
1866   } else {
1867     assert(Opc == Instruction::And && "Unknown merge op!");
1868     // Codegen X & Y as:
1869     // BB1:
1870     //   jmp_if_X TmpBB
1871     //   jmp FBB
1872     // TmpBB:
1873     //   jmp_if_Y TBB
1874     //   jmp FBB
1875     //
1876     //  This requires creation of TmpBB after CurBB.
1877 
1878     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1879     // The requirement is that
1880     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1881     //     = FalseProb for original BB.
1882     // Assuming the original probabilities are A and B, one choice is to set
1883     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1884     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1885     // TrueProb for BB1 * FalseProb for TmpBB.
1886 
1887     auto NewTrueProb = TProb + FProb / 2;
1888     auto NewFalseProb = FProb / 2;
1889     // Emit the LHS condition.
1890     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1891                          NewTrueProb, NewFalseProb, InvertCond);
1892 
1893     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1894     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1895     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1896     // Emit the RHS condition into TmpBB.
1897     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1898                          Probs[0], Probs[1], InvertCond);
1899   }
1900 }
1901 
1902 /// If the set of cases should be emitted as a series of branches, return true.
1903 /// If we should emit this as a bunch of and/or'd together conditions, return
1904 /// false.
1905 bool
1906 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1907   if (Cases.size() != 2) return true;
1908 
1909   // If this is two comparisons of the same values or'd or and'd together, they
1910   // will get folded into a single comparison, so don't emit two blocks.
1911   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1912        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1913       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1914        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1915     return false;
1916   }
1917 
1918   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1919   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1920   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1921       Cases[0].CC == Cases[1].CC &&
1922       isa<Constant>(Cases[0].CmpRHS) &&
1923       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1924     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1925       return false;
1926     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1927       return false;
1928   }
1929 
1930   return true;
1931 }
1932 
1933 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1934   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1935 
1936   // Update machine-CFG edges.
1937   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1938 
1939   if (I.isUnconditional()) {
1940     // Update machine-CFG edges.
1941     BrMBB->addSuccessor(Succ0MBB);
1942 
1943     // If this is not a fall-through branch or optimizations are switched off,
1944     // emit the branch.
1945     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1946       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1947                               MVT::Other, getControlRoot(),
1948                               DAG.getBasicBlock(Succ0MBB)));
1949 
1950     return;
1951   }
1952 
1953   // If this condition is one of the special cases we handle, do special stuff
1954   // now.
1955   const Value *CondVal = I.getCondition();
1956   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1957 
1958   // If this is a series of conditions that are or'd or and'd together, emit
1959   // this as a sequence of branches instead of setcc's with and/or operations.
1960   // As long as jumps are not expensive, this should improve performance.
1961   // For example, instead of something like:
1962   //     cmp A, B
1963   //     C = seteq
1964   //     cmp D, E
1965   //     F = setle
1966   //     or C, F
1967   //     jnz foo
1968   // Emit:
1969   //     cmp A, B
1970   //     je foo
1971   //     cmp D, E
1972   //     jle foo
1973   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1974     Instruction::BinaryOps Opcode = BOp->getOpcode();
1975     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1976         !I.getMetadata(LLVMContext::MD_unpredictable) &&
1977         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1978       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1979                            Opcode,
1980                            getEdgeProbability(BrMBB, Succ0MBB),
1981                            getEdgeProbability(BrMBB, Succ1MBB),
1982                            /*InvertCond=*/false);
1983       // If the compares in later blocks need to use values not currently
1984       // exported from this block, export them now.  This block should always
1985       // be the first entry.
1986       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1987 
1988       // Allow some cases to be rejected.
1989       if (ShouldEmitAsBranches(SwitchCases)) {
1990         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1991           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1992           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1993         }
1994 
1995         // Emit the branch for this block.
1996         visitSwitchCase(SwitchCases[0], BrMBB);
1997         SwitchCases.erase(SwitchCases.begin());
1998         return;
1999       }
2000 
2001       // Okay, we decided not to do this, remove any inserted MBB's and clear
2002       // SwitchCases.
2003       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2004         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2005 
2006       SwitchCases.clear();
2007     }
2008   }
2009 
2010   // Create a CaseBlock record representing this branch.
2011   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2012                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2013 
2014   // Use visitSwitchCase to actually insert the fast branch sequence for this
2015   // cond branch.
2016   visitSwitchCase(CB, BrMBB);
2017 }
2018 
2019 /// visitSwitchCase - Emits the necessary code to represent a single node in
2020 /// the binary search tree resulting from lowering a switch instruction.
2021 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2022                                           MachineBasicBlock *SwitchBB) {
2023   SDValue Cond;
2024   SDValue CondLHS = getValue(CB.CmpLHS);
2025   SDLoc dl = CB.DL;
2026 
2027   // Build the setcc now.
2028   if (!CB.CmpMHS) {
2029     // Fold "(X == true)" to X and "(X == false)" to !X to
2030     // handle common cases produced by branch lowering.
2031     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2032         CB.CC == ISD::SETEQ)
2033       Cond = CondLHS;
2034     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2035              CB.CC == ISD::SETEQ) {
2036       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2037       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2038     } else
2039       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2040   } else {
2041     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2042 
2043     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2044     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2045 
2046     SDValue CmpOp = getValue(CB.CmpMHS);
2047     EVT VT = CmpOp.getValueType();
2048 
2049     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2050       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2051                           ISD::SETLE);
2052     } else {
2053       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2054                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2055       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2056                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2057     }
2058   }
2059 
2060   // Update successor info
2061   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2062   // TrueBB and FalseBB are always different unless the incoming IR is
2063   // degenerate. This only happens when running llc on weird IR.
2064   if (CB.TrueBB != CB.FalseBB)
2065     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2066   SwitchBB->normalizeSuccProbs();
2067 
2068   // If the lhs block is the next block, invert the condition so that we can
2069   // fall through to the lhs instead of the rhs block.
2070   if (CB.TrueBB == NextBlock(SwitchBB)) {
2071     std::swap(CB.TrueBB, CB.FalseBB);
2072     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2073     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2074   }
2075 
2076   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2077                                MVT::Other, getControlRoot(), Cond,
2078                                DAG.getBasicBlock(CB.TrueBB));
2079 
2080   // Insert the false branch. Do this even if it's a fall through branch,
2081   // this makes it easier to do DAG optimizations which require inverting
2082   // the branch condition.
2083   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2084                        DAG.getBasicBlock(CB.FalseBB));
2085 
2086   DAG.setRoot(BrCond);
2087 }
2088 
2089 /// visitJumpTable - Emit JumpTable node in the current MBB
2090 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2091   // Emit the code for the jump table
2092   assert(JT.Reg != -1U && "Should lower JT Header first!");
2093   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2094   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2095                                      JT.Reg, PTy);
2096   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2097   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2098                                     MVT::Other, Index.getValue(1),
2099                                     Table, Index);
2100   DAG.setRoot(BrJumpTable);
2101 }
2102 
2103 /// visitJumpTableHeader - This function emits necessary code to produce index
2104 /// in the JumpTable from switch case.
2105 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2106                                                JumpTableHeader &JTH,
2107                                                MachineBasicBlock *SwitchBB) {
2108   SDLoc dl = getCurSDLoc();
2109 
2110   // Subtract the lowest switch case value from the value being switched on and
2111   // conditional branch to default mbb if the result is greater than the
2112   // difference between smallest and largest cases.
2113   SDValue SwitchOp = getValue(JTH.SValue);
2114   EVT VT = SwitchOp.getValueType();
2115   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2116                             DAG.getConstant(JTH.First, dl, VT));
2117 
2118   // The SDNode we just created, which holds the value being switched on minus
2119   // the smallest case value, needs to be copied to a virtual register so it
2120   // can be used as an index into the jump table in a subsequent basic block.
2121   // This value may be smaller or larger than the target's pointer type, and
2122   // therefore require extension or truncating.
2123   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2124   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2125 
2126   unsigned JumpTableReg =
2127       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2128   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2129                                     JumpTableReg, SwitchOp);
2130   JT.Reg = JumpTableReg;
2131 
2132   // Emit the range check for the jump table, and branch to the default block
2133   // for the switch statement if the value being switched on exceeds the largest
2134   // case in the switch.
2135   SDValue CMP = DAG.getSetCC(
2136       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2137                                  Sub.getValueType()),
2138       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2139 
2140   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2141                                MVT::Other, CopyTo, CMP,
2142                                DAG.getBasicBlock(JT.Default));
2143 
2144   // Avoid emitting unnecessary branches to the next block.
2145   if (JT.MBB != NextBlock(SwitchBB))
2146     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2147                          DAG.getBasicBlock(JT.MBB));
2148 
2149   DAG.setRoot(BrCond);
2150 }
2151 
2152 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2153 /// variable if there exists one.
2154 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2155                                  SDValue &Chain) {
2156   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2157   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2158   MachineFunction &MF = DAG.getMachineFunction();
2159   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2160   MachineSDNode *Node =
2161       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2162   if (Global) {
2163     MachinePointerInfo MPInfo(Global);
2164     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
2165     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2166                  MachineMemOperand::MODereferenceable;
2167     *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
2168                                        DAG.getEVTAlignment(PtrTy));
2169     Node->setMemRefs(MemRefs, MemRefs + 1);
2170   }
2171   return SDValue(Node, 0);
2172 }
2173 
2174 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2175 /// tail spliced into a stack protector check success bb.
2176 ///
2177 /// For a high level explanation of how this fits into the stack protector
2178 /// generation see the comment on the declaration of class
2179 /// StackProtectorDescriptor.
2180 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2181                                                   MachineBasicBlock *ParentBB) {
2182 
2183   // First create the loads to the guard/stack slot for the comparison.
2184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2185   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2186 
2187   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2188   int FI = MFI.getStackProtectorIndex();
2189 
2190   SDValue Guard;
2191   SDLoc dl = getCurSDLoc();
2192   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2193   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2194   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2195 
2196   // Generate code to load the content of the guard slot.
2197   SDValue GuardVal = DAG.getLoad(
2198       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2199       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2200       MachineMemOperand::MOVolatile);
2201 
2202   if (TLI.useStackGuardXorFP())
2203     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2204 
2205   // Retrieve guard check function, nullptr if instrumentation is inlined.
2206   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2207     // The target provides a guard check function to validate the guard value.
2208     // Generate a call to that function with the content of the guard slot as
2209     // argument.
2210     auto *Fn = cast<Function>(GuardCheck);
2211     FunctionType *FnTy = Fn->getFunctionType();
2212     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2213 
2214     TargetLowering::ArgListTy Args;
2215     TargetLowering::ArgListEntry Entry;
2216     Entry.Node = GuardVal;
2217     Entry.Ty = FnTy->getParamType(0);
2218     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2219       Entry.IsInReg = true;
2220     Args.push_back(Entry);
2221 
2222     TargetLowering::CallLoweringInfo CLI(DAG);
2223     CLI.setDebugLoc(getCurSDLoc())
2224       .setChain(DAG.getEntryNode())
2225       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2226                  getValue(GuardCheck), std::move(Args));
2227 
2228     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2229     DAG.setRoot(Result.second);
2230     return;
2231   }
2232 
2233   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2234   // Otherwise, emit a volatile load to retrieve the stack guard value.
2235   SDValue Chain = DAG.getEntryNode();
2236   if (TLI.useLoadStackGuardNode()) {
2237     Guard = getLoadStackGuard(DAG, dl, Chain);
2238   } else {
2239     const Value *IRGuard = TLI.getSDagStackGuard(M);
2240     SDValue GuardPtr = getValue(IRGuard);
2241 
2242     Guard =
2243         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2244                     Align, MachineMemOperand::MOVolatile);
2245   }
2246 
2247   // Perform the comparison via a subtract/getsetcc.
2248   EVT VT = Guard.getValueType();
2249   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2250 
2251   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2252                                                         *DAG.getContext(),
2253                                                         Sub.getValueType()),
2254                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2255 
2256   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2257   // branch to failure MBB.
2258   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2259                                MVT::Other, GuardVal.getOperand(0),
2260                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2261   // Otherwise branch to success MBB.
2262   SDValue Br = DAG.getNode(ISD::BR, dl,
2263                            MVT::Other, BrCond,
2264                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2265 
2266   DAG.setRoot(Br);
2267 }
2268 
2269 /// Codegen the failure basic block for a stack protector check.
2270 ///
2271 /// A failure stack protector machine basic block consists simply of a call to
2272 /// __stack_chk_fail().
2273 ///
2274 /// For a high level explanation of how this fits into the stack protector
2275 /// generation see the comment on the declaration of class
2276 /// StackProtectorDescriptor.
2277 void
2278 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2279   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2280   SDValue Chain =
2281       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2282                       None, false, getCurSDLoc(), false, false).second;
2283   DAG.setRoot(Chain);
2284 }
2285 
2286 /// visitBitTestHeader - This function emits necessary code to produce value
2287 /// suitable for "bit tests"
2288 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2289                                              MachineBasicBlock *SwitchBB) {
2290   SDLoc dl = getCurSDLoc();
2291 
2292   // Subtract the minimum value
2293   SDValue SwitchOp = getValue(B.SValue);
2294   EVT VT = SwitchOp.getValueType();
2295   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2296                             DAG.getConstant(B.First, dl, VT));
2297 
2298   // Check range
2299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2300   SDValue RangeCmp = DAG.getSetCC(
2301       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2302                                  Sub.getValueType()),
2303       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2304 
2305   // Determine the type of the test operands.
2306   bool UsePtrType = false;
2307   if (!TLI.isTypeLegal(VT))
2308     UsePtrType = true;
2309   else {
2310     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2311       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2312         // Switch table case range are encoded into series of masks.
2313         // Just use pointer type, it's guaranteed to fit.
2314         UsePtrType = true;
2315         break;
2316       }
2317   }
2318   if (UsePtrType) {
2319     VT = TLI.getPointerTy(DAG.getDataLayout());
2320     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2321   }
2322 
2323   B.RegVT = VT.getSimpleVT();
2324   B.Reg = FuncInfo.CreateReg(B.RegVT);
2325   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2326 
2327   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2328 
2329   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2330   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2331   SwitchBB->normalizeSuccProbs();
2332 
2333   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2334                                 MVT::Other, CopyTo, RangeCmp,
2335                                 DAG.getBasicBlock(B.Default));
2336 
2337   // Avoid emitting unnecessary branches to the next block.
2338   if (MBB != NextBlock(SwitchBB))
2339     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2340                           DAG.getBasicBlock(MBB));
2341 
2342   DAG.setRoot(BrRange);
2343 }
2344 
2345 /// visitBitTestCase - this function produces one "bit test"
2346 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2347                                            MachineBasicBlock* NextMBB,
2348                                            BranchProbability BranchProbToNext,
2349                                            unsigned Reg,
2350                                            BitTestCase &B,
2351                                            MachineBasicBlock *SwitchBB) {
2352   SDLoc dl = getCurSDLoc();
2353   MVT VT = BB.RegVT;
2354   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2355   SDValue Cmp;
2356   unsigned PopCount = countPopulation(B.Mask);
2357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2358   if (PopCount == 1) {
2359     // Testing for a single bit; just compare the shift count with what it
2360     // would need to be to shift a 1 bit in that position.
2361     Cmp = DAG.getSetCC(
2362         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2363         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2364         ISD::SETEQ);
2365   } else if (PopCount == BB.Range) {
2366     // There is only one zero bit in the range, test for it directly.
2367     Cmp = DAG.getSetCC(
2368         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2369         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2370         ISD::SETNE);
2371   } else {
2372     // Make desired shift
2373     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2374                                     DAG.getConstant(1, dl, VT), ShiftOp);
2375 
2376     // Emit bit tests and jumps
2377     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2378                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2379     Cmp = DAG.getSetCC(
2380         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2381         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2382   }
2383 
2384   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2385   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2386   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2387   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2388   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2389   // one as they are relative probabilities (and thus work more like weights),
2390   // and hence we need to normalize them to let the sum of them become one.
2391   SwitchBB->normalizeSuccProbs();
2392 
2393   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2394                               MVT::Other, getControlRoot(),
2395                               Cmp, DAG.getBasicBlock(B.TargetBB));
2396 
2397   // Avoid emitting unnecessary branches to the next block.
2398   if (NextMBB != NextBlock(SwitchBB))
2399     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2400                         DAG.getBasicBlock(NextMBB));
2401 
2402   DAG.setRoot(BrAnd);
2403 }
2404 
2405 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2406   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2407 
2408   // Retrieve successors. Look through artificial IR level blocks like
2409   // catchswitch for successors.
2410   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2411   const BasicBlock *EHPadBB = I.getSuccessor(1);
2412 
2413   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2414   // have to do anything here to lower funclet bundles.
2415   assert(!I.hasOperandBundlesOtherThan(
2416              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2417          "Cannot lower invokes with arbitrary operand bundles yet!");
2418 
2419   const Value *Callee(I.getCalledValue());
2420   const Function *Fn = dyn_cast<Function>(Callee);
2421   if (isa<InlineAsm>(Callee))
2422     visitInlineAsm(&I);
2423   else if (Fn && Fn->isIntrinsic()) {
2424     switch (Fn->getIntrinsicID()) {
2425     default:
2426       llvm_unreachable("Cannot invoke this intrinsic");
2427     case Intrinsic::donothing:
2428       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2429       break;
2430     case Intrinsic::experimental_patchpoint_void:
2431     case Intrinsic::experimental_patchpoint_i64:
2432       visitPatchpoint(&I, EHPadBB);
2433       break;
2434     case Intrinsic::experimental_gc_statepoint:
2435       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2436       break;
2437     }
2438   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2439     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2440     // Eventually we will support lowering the @llvm.experimental.deoptimize
2441     // intrinsic, and right now there are no plans to support other intrinsics
2442     // with deopt state.
2443     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2444   } else {
2445     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2446   }
2447 
2448   // If the value of the invoke is used outside of its defining block, make it
2449   // available as a virtual register.
2450   // We already took care of the exported value for the statepoint instruction
2451   // during call to the LowerStatepoint.
2452   if (!isStatepoint(I)) {
2453     CopyToExportRegsIfNeeded(&I);
2454   }
2455 
2456   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2457   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2458   BranchProbability EHPadBBProb =
2459       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2460           : BranchProbability::getZero();
2461   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2462 
2463   // Update successor info.
2464   addSuccessorWithProb(InvokeMBB, Return);
2465   for (auto &UnwindDest : UnwindDests) {
2466     UnwindDest.first->setIsEHPad();
2467     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2468   }
2469   InvokeMBB->normalizeSuccProbs();
2470 
2471   // Drop into normal successor.
2472   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2473                           MVT::Other, getControlRoot(),
2474                           DAG.getBasicBlock(Return)));
2475 }
2476 
2477 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2478   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2479 }
2480 
2481 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2482   assert(FuncInfo.MBB->isEHPad() &&
2483          "Call to landingpad not in landing pad!");
2484 
2485   MachineBasicBlock *MBB = FuncInfo.MBB;
2486   addLandingPadInfo(LP, *MBB);
2487 
2488   // If there aren't registers to copy the values into (e.g., during SjLj
2489   // exceptions), then don't bother to create these DAG nodes.
2490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2491   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2492   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2493       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2494     return;
2495 
2496   // If landingpad's return type is token type, we don't create DAG nodes
2497   // for its exception pointer and selector value. The extraction of exception
2498   // pointer or selector value from token type landingpads is not currently
2499   // supported.
2500   if (LP.getType()->isTokenTy())
2501     return;
2502 
2503   SmallVector<EVT, 2> ValueVTs;
2504   SDLoc dl = getCurSDLoc();
2505   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2506   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2507 
2508   // Get the two live-in registers as SDValues. The physregs have already been
2509   // copied into virtual registers.
2510   SDValue Ops[2];
2511   if (FuncInfo.ExceptionPointerVirtReg) {
2512     Ops[0] = DAG.getZExtOrTrunc(
2513         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2514                            FuncInfo.ExceptionPointerVirtReg,
2515                            TLI.getPointerTy(DAG.getDataLayout())),
2516         dl, ValueVTs[0]);
2517   } else {
2518     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2519   }
2520   Ops[1] = DAG.getZExtOrTrunc(
2521       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2522                          FuncInfo.ExceptionSelectorVirtReg,
2523                          TLI.getPointerTy(DAG.getDataLayout())),
2524       dl, ValueVTs[1]);
2525 
2526   // Merge into one.
2527   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2528                             DAG.getVTList(ValueVTs), Ops);
2529   setValue(&LP, Res);
2530 }
2531 
2532 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2533 #ifndef NDEBUG
2534   for (const CaseCluster &CC : Clusters)
2535     assert(CC.Low == CC.High && "Input clusters must be single-case");
2536 #endif
2537 
2538   llvm::sort(Clusters.begin(), Clusters.end(),
2539              [](const CaseCluster &a, const CaseCluster &b) {
2540     return a.Low->getValue().slt(b.Low->getValue());
2541   });
2542 
2543   // Merge adjacent clusters with the same destination.
2544   const unsigned N = Clusters.size();
2545   unsigned DstIndex = 0;
2546   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2547     CaseCluster &CC = Clusters[SrcIndex];
2548     const ConstantInt *CaseVal = CC.Low;
2549     MachineBasicBlock *Succ = CC.MBB;
2550 
2551     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2552         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2553       // If this case has the same successor and is a neighbour, merge it into
2554       // the previous cluster.
2555       Clusters[DstIndex - 1].High = CaseVal;
2556       Clusters[DstIndex - 1].Prob += CC.Prob;
2557     } else {
2558       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2559                    sizeof(Clusters[SrcIndex]));
2560     }
2561   }
2562   Clusters.resize(DstIndex);
2563 }
2564 
2565 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2566                                            MachineBasicBlock *Last) {
2567   // Update JTCases.
2568   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2569     if (JTCases[i].first.HeaderBB == First)
2570       JTCases[i].first.HeaderBB = Last;
2571 
2572   // Update BitTestCases.
2573   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2574     if (BitTestCases[i].Parent == First)
2575       BitTestCases[i].Parent = Last;
2576 }
2577 
2578 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2579   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2580 
2581   // Update machine-CFG edges with unique successors.
2582   SmallSet<BasicBlock*, 32> Done;
2583   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2584     BasicBlock *BB = I.getSuccessor(i);
2585     bool Inserted = Done.insert(BB).second;
2586     if (!Inserted)
2587         continue;
2588 
2589     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2590     addSuccessorWithProb(IndirectBrMBB, Succ);
2591   }
2592   IndirectBrMBB->normalizeSuccProbs();
2593 
2594   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2595                           MVT::Other, getControlRoot(),
2596                           getValue(I.getAddress())));
2597 }
2598 
2599 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2600   if (DAG.getTarget().Options.TrapUnreachable)
2601     DAG.setRoot(
2602         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2603 }
2604 
2605 void SelectionDAGBuilder::visitFSub(const User &I) {
2606   // -0.0 - X --> fneg
2607   Type *Ty = I.getType();
2608   if (isa<Constant>(I.getOperand(0)) &&
2609       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2610     SDValue Op2 = getValue(I.getOperand(1));
2611     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2612                              Op2.getValueType(), Op2));
2613     return;
2614   }
2615 
2616   visitBinary(I, ISD::FSUB);
2617 }
2618 
2619 /// Checks if the given instruction performs a vector reduction, in which case
2620 /// we have the freedom to alter the elements in the result as long as the
2621 /// reduction of them stays unchanged.
2622 static bool isVectorReductionOp(const User *I) {
2623   const Instruction *Inst = dyn_cast<Instruction>(I);
2624   if (!Inst || !Inst->getType()->isVectorTy())
2625     return false;
2626 
2627   auto OpCode = Inst->getOpcode();
2628   switch (OpCode) {
2629   case Instruction::Add:
2630   case Instruction::Mul:
2631   case Instruction::And:
2632   case Instruction::Or:
2633   case Instruction::Xor:
2634     break;
2635   case Instruction::FAdd:
2636   case Instruction::FMul:
2637     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2638       if (FPOp->getFastMathFlags().isFast())
2639         break;
2640     LLVM_FALLTHROUGH;
2641   default:
2642     return false;
2643   }
2644 
2645   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2646   unsigned ElemNumToReduce = ElemNum;
2647 
2648   // Do DFS search on the def-use chain from the given instruction. We only
2649   // allow four kinds of operations during the search until we reach the
2650   // instruction that extracts the first element from the vector:
2651   //
2652   //   1. The reduction operation of the same opcode as the given instruction.
2653   //
2654   //   2. PHI node.
2655   //
2656   //   3. ShuffleVector instruction together with a reduction operation that
2657   //      does a partial reduction.
2658   //
2659   //   4. ExtractElement that extracts the first element from the vector, and we
2660   //      stop searching the def-use chain here.
2661   //
2662   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2663   // from 1-3 to the stack to continue the DFS. The given instruction is not
2664   // a reduction operation if we meet any other instructions other than those
2665   // listed above.
2666 
2667   SmallVector<const User *, 16> UsersToVisit{Inst};
2668   SmallPtrSet<const User *, 16> Visited;
2669   bool ReduxExtracted = false;
2670 
2671   while (!UsersToVisit.empty()) {
2672     auto User = UsersToVisit.back();
2673     UsersToVisit.pop_back();
2674     if (!Visited.insert(User).second)
2675       continue;
2676 
2677     for (const auto &U : User->users()) {
2678       auto Inst = dyn_cast<Instruction>(U);
2679       if (!Inst)
2680         return false;
2681 
2682       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2683         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2684           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2685             return false;
2686         UsersToVisit.push_back(U);
2687       } else if (const ShuffleVectorInst *ShufInst =
2688                      dyn_cast<ShuffleVectorInst>(U)) {
2689         // Detect the following pattern: A ShuffleVector instruction together
2690         // with a reduction that do partial reduction on the first and second
2691         // ElemNumToReduce / 2 elements, and store the result in
2692         // ElemNumToReduce / 2 elements in another vector.
2693 
2694         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2695         if (ResultElements < ElemNum)
2696           return false;
2697 
2698         if (ElemNumToReduce == 1)
2699           return false;
2700         if (!isa<UndefValue>(U->getOperand(1)))
2701           return false;
2702         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2703           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2704             return false;
2705         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2706           if (ShufInst->getMaskValue(i) != -1)
2707             return false;
2708 
2709         // There is only one user of this ShuffleVector instruction, which
2710         // must be a reduction operation.
2711         if (!U->hasOneUse())
2712           return false;
2713 
2714         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2715         if (!U2 || U2->getOpcode() != OpCode)
2716           return false;
2717 
2718         // Check operands of the reduction operation.
2719         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2720             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2721           UsersToVisit.push_back(U2);
2722           ElemNumToReduce /= 2;
2723         } else
2724           return false;
2725       } else if (isa<ExtractElementInst>(U)) {
2726         // At this moment we should have reduced all elements in the vector.
2727         if (ElemNumToReduce != 1)
2728           return false;
2729 
2730         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2731         if (!Val || Val->getZExtValue() != 0)
2732           return false;
2733 
2734         ReduxExtracted = true;
2735       } else
2736         return false;
2737     }
2738   }
2739   return ReduxExtracted;
2740 }
2741 
2742 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2743   SDValue Op1 = getValue(I.getOperand(0));
2744   SDValue Op2 = getValue(I.getOperand(1));
2745 
2746   bool nuw = false;
2747   bool nsw = false;
2748   bool exact = false;
2749   bool vec_redux = false;
2750   FastMathFlags FMF;
2751 
2752   if (const OverflowingBinaryOperator *OFBinOp =
2753           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2754     nuw = OFBinOp->hasNoUnsignedWrap();
2755     nsw = OFBinOp->hasNoSignedWrap();
2756   }
2757   if (const PossiblyExactOperator *ExactOp =
2758           dyn_cast<const PossiblyExactOperator>(&I))
2759     exact = ExactOp->isExact();
2760   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2761     FMF = FPOp->getFastMathFlags();
2762 
2763   if (isVectorReductionOp(&I)) {
2764     vec_redux = true;
2765     DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2766   }
2767 
2768   SDNodeFlags Flags;
2769   Flags.setExact(exact);
2770   Flags.setNoSignedWrap(nsw);
2771   Flags.setNoUnsignedWrap(nuw);
2772   Flags.setVectorReduction(vec_redux);
2773   Flags.setAllowReciprocal(FMF.allowReciprocal());
2774   Flags.setAllowContract(FMF.allowContract());
2775   Flags.setNoInfs(FMF.noInfs());
2776   Flags.setNoNaNs(FMF.noNaNs());
2777   Flags.setNoSignedZeros(FMF.noSignedZeros());
2778   Flags.setApproximateFuncs(FMF.approxFunc());
2779   Flags.setAllowReassociation(FMF.allowReassoc());
2780 
2781   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2782                                      Op1, Op2, Flags);
2783   setValue(&I, BinNodeValue);
2784 }
2785 
2786 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2787   SDValue Op1 = getValue(I.getOperand(0));
2788   SDValue Op2 = getValue(I.getOperand(1));
2789 
2790   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2791       Op2.getValueType(), DAG.getDataLayout());
2792 
2793   // Coerce the shift amount to the right type if we can.
2794   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2795     unsigned ShiftSize = ShiftTy.getSizeInBits();
2796     unsigned Op2Size = Op2.getValueSizeInBits();
2797     SDLoc DL = getCurSDLoc();
2798 
2799     // If the operand is smaller than the shift count type, promote it.
2800     if (ShiftSize > Op2Size)
2801       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2802 
2803     // If the operand is larger than the shift count type but the shift
2804     // count type has enough bits to represent any shift value, truncate
2805     // it now. This is a common case and it exposes the truncate to
2806     // optimization early.
2807     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2808       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2809     // Otherwise we'll need to temporarily settle for some other convenient
2810     // type.  Type legalization will make adjustments once the shiftee is split.
2811     else
2812       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2813   }
2814 
2815   bool nuw = false;
2816   bool nsw = false;
2817   bool exact = false;
2818 
2819   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2820 
2821     if (const OverflowingBinaryOperator *OFBinOp =
2822             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2823       nuw = OFBinOp->hasNoUnsignedWrap();
2824       nsw = OFBinOp->hasNoSignedWrap();
2825     }
2826     if (const PossiblyExactOperator *ExactOp =
2827             dyn_cast<const PossiblyExactOperator>(&I))
2828       exact = ExactOp->isExact();
2829   }
2830   SDNodeFlags Flags;
2831   Flags.setExact(exact);
2832   Flags.setNoSignedWrap(nsw);
2833   Flags.setNoUnsignedWrap(nuw);
2834   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2835                             Flags);
2836   setValue(&I, Res);
2837 }
2838 
2839 void SelectionDAGBuilder::visitSDiv(const User &I) {
2840   SDValue Op1 = getValue(I.getOperand(0));
2841   SDValue Op2 = getValue(I.getOperand(1));
2842 
2843   SDNodeFlags Flags;
2844   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2845                  cast<PossiblyExactOperator>(&I)->isExact());
2846   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2847                            Op2, Flags));
2848 }
2849 
2850 void SelectionDAGBuilder::visitICmp(const User &I) {
2851   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2852   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2853     predicate = IC->getPredicate();
2854   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2855     predicate = ICmpInst::Predicate(IC->getPredicate());
2856   SDValue Op1 = getValue(I.getOperand(0));
2857   SDValue Op2 = getValue(I.getOperand(1));
2858   ISD::CondCode Opcode = getICmpCondCode(predicate);
2859 
2860   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2861                                                         I.getType());
2862   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2863 }
2864 
2865 void SelectionDAGBuilder::visitFCmp(const User &I) {
2866   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2867   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2868     predicate = FC->getPredicate();
2869   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2870     predicate = FCmpInst::Predicate(FC->getPredicate());
2871   SDValue Op1 = getValue(I.getOperand(0));
2872   SDValue Op2 = getValue(I.getOperand(1));
2873   ISD::CondCode Condition = getFCmpCondCode(predicate);
2874 
2875   // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2876   // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2877   // further optimization, but currently FMF is only applicable to binary nodes.
2878   if (TM.Options.NoNaNsFPMath)
2879     Condition = getFCmpCodeWithoutNaN(Condition);
2880   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2881                                                         I.getType());
2882   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2883 }
2884 
2885 // Check if the condition of the select has one use or two users that are both
2886 // selects with the same condition.
2887 static bool hasOnlySelectUsers(const Value *Cond) {
2888   return llvm::all_of(Cond->users(), [](const Value *V) {
2889     return isa<SelectInst>(V);
2890   });
2891 }
2892 
2893 void SelectionDAGBuilder::visitSelect(const User &I) {
2894   SmallVector<EVT, 4> ValueVTs;
2895   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2896                   ValueVTs);
2897   unsigned NumValues = ValueVTs.size();
2898   if (NumValues == 0) return;
2899 
2900   SmallVector<SDValue, 4> Values(NumValues);
2901   SDValue Cond     = getValue(I.getOperand(0));
2902   SDValue LHSVal   = getValue(I.getOperand(1));
2903   SDValue RHSVal   = getValue(I.getOperand(2));
2904   auto BaseOps = {Cond};
2905   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2906     ISD::VSELECT : ISD::SELECT;
2907 
2908   // Min/max matching is only viable if all output VTs are the same.
2909   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2910     EVT VT = ValueVTs[0];
2911     LLVMContext &Ctx = *DAG.getContext();
2912     auto &TLI = DAG.getTargetLoweringInfo();
2913 
2914     // We care about the legality of the operation after it has been type
2915     // legalized.
2916     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2917            VT != TLI.getTypeToTransformTo(Ctx, VT))
2918       VT = TLI.getTypeToTransformTo(Ctx, VT);
2919 
2920     // If the vselect is legal, assume we want to leave this as a vector setcc +
2921     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2922     // min/max is legal on the scalar type.
2923     bool UseScalarMinMax = VT.isVector() &&
2924       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2925 
2926     Value *LHS, *RHS;
2927     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2928     ISD::NodeType Opc = ISD::DELETED_NODE;
2929     switch (SPR.Flavor) {
2930     case SPF_UMAX:    Opc = ISD::UMAX; break;
2931     case SPF_UMIN:    Opc = ISD::UMIN; break;
2932     case SPF_SMAX:    Opc = ISD::SMAX; break;
2933     case SPF_SMIN:    Opc = ISD::SMIN; break;
2934     case SPF_FMINNUM:
2935       switch (SPR.NaNBehavior) {
2936       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2937       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2938       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2939       case SPNB_RETURNS_ANY: {
2940         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2941           Opc = ISD::FMINNUM;
2942         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2943           Opc = ISD::FMINNAN;
2944         else if (UseScalarMinMax)
2945           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2946             ISD::FMINNUM : ISD::FMINNAN;
2947         break;
2948       }
2949       }
2950       break;
2951     case SPF_FMAXNUM:
2952       switch (SPR.NaNBehavior) {
2953       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2954       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2955       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2956       case SPNB_RETURNS_ANY:
2957 
2958         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2959           Opc = ISD::FMAXNUM;
2960         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2961           Opc = ISD::FMAXNAN;
2962         else if (UseScalarMinMax)
2963           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2964             ISD::FMAXNUM : ISD::FMAXNAN;
2965         break;
2966       }
2967       break;
2968     default: break;
2969     }
2970 
2971     if (Opc != ISD::DELETED_NODE &&
2972         (TLI.isOperationLegalOrCustom(Opc, VT) ||
2973          (UseScalarMinMax &&
2974           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2975         // If the underlying comparison instruction is used by any other
2976         // instruction, the consumed instructions won't be destroyed, so it is
2977         // not profitable to convert to a min/max.
2978         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
2979       OpCode = Opc;
2980       LHSVal = getValue(LHS);
2981       RHSVal = getValue(RHS);
2982       BaseOps = {};
2983     }
2984   }
2985 
2986   for (unsigned i = 0; i != NumValues; ++i) {
2987     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2988     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2989     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2990     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2991                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2992                             Ops);
2993   }
2994 
2995   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2996                            DAG.getVTList(ValueVTs), Values));
2997 }
2998 
2999 void SelectionDAGBuilder::visitTrunc(const User &I) {
3000   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3001   SDValue N = getValue(I.getOperand(0));
3002   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3003                                                         I.getType());
3004   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3005 }
3006 
3007 void SelectionDAGBuilder::visitZExt(const User &I) {
3008   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3009   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3010   SDValue N = getValue(I.getOperand(0));
3011   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3012                                                         I.getType());
3013   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3014 }
3015 
3016 void SelectionDAGBuilder::visitSExt(const User &I) {
3017   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3018   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3019   SDValue N = getValue(I.getOperand(0));
3020   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3021                                                         I.getType());
3022   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3023 }
3024 
3025 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3026   // FPTrunc is never a no-op cast, no need to check
3027   SDValue N = getValue(I.getOperand(0));
3028   SDLoc dl = getCurSDLoc();
3029   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3030   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3031   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3032                            DAG.getTargetConstant(
3033                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3034 }
3035 
3036 void SelectionDAGBuilder::visitFPExt(const User &I) {
3037   // FPExt is never a no-op cast, no need to check
3038   SDValue N = getValue(I.getOperand(0));
3039   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3040                                                         I.getType());
3041   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3042 }
3043 
3044 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3045   // FPToUI is never a no-op cast, no need to check
3046   SDValue N = getValue(I.getOperand(0));
3047   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3048                                                         I.getType());
3049   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3050 }
3051 
3052 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3053   // FPToSI is never a no-op cast, no need to check
3054   SDValue N = getValue(I.getOperand(0));
3055   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3056                                                         I.getType());
3057   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3058 }
3059 
3060 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3061   // UIToFP is never a no-op cast, no need to check
3062   SDValue N = getValue(I.getOperand(0));
3063   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3064                                                         I.getType());
3065   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3066 }
3067 
3068 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3069   // SIToFP is never a no-op cast, no need to check
3070   SDValue N = getValue(I.getOperand(0));
3071   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3072                                                         I.getType());
3073   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3074 }
3075 
3076 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3077   // What to do depends on the size of the integer and the size of the pointer.
3078   // We can either truncate, zero extend, or no-op, accordingly.
3079   SDValue N = getValue(I.getOperand(0));
3080   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3081                                                         I.getType());
3082   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3083 }
3084 
3085 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3086   // What to do depends on the size of the integer and the size of the pointer.
3087   // We can either truncate, zero extend, or no-op, accordingly.
3088   SDValue N = getValue(I.getOperand(0));
3089   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3090                                                         I.getType());
3091   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3092 }
3093 
3094 void SelectionDAGBuilder::visitBitCast(const User &I) {
3095   SDValue N = getValue(I.getOperand(0));
3096   SDLoc dl = getCurSDLoc();
3097   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3098                                                         I.getType());
3099 
3100   // BitCast assures us that source and destination are the same size so this is
3101   // either a BITCAST or a no-op.
3102   if (DestVT != N.getValueType())
3103     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3104                              DestVT, N)); // convert types.
3105   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3106   // might fold any kind of constant expression to an integer constant and that
3107   // is not what we are looking for. Only recognize a bitcast of a genuine
3108   // constant integer as an opaque constant.
3109   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3110     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3111                                  /*isOpaque*/true));
3112   else
3113     setValue(&I, N);            // noop cast.
3114 }
3115 
3116 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3118   const Value *SV = I.getOperand(0);
3119   SDValue N = getValue(SV);
3120   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3121 
3122   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3123   unsigned DestAS = I.getType()->getPointerAddressSpace();
3124 
3125   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3126     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3127 
3128   setValue(&I, N);
3129 }
3130 
3131 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3132   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3133   SDValue InVec = getValue(I.getOperand(0));
3134   SDValue InVal = getValue(I.getOperand(1));
3135   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3136                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3137   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3138                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3139                            InVec, InVal, InIdx));
3140 }
3141 
3142 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3144   SDValue InVec = getValue(I.getOperand(0));
3145   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3146                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3147   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3148                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3149                            InVec, InIdx));
3150 }
3151 
3152 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3153   SDValue Src1 = getValue(I.getOperand(0));
3154   SDValue Src2 = getValue(I.getOperand(1));
3155   SDLoc DL = getCurSDLoc();
3156 
3157   SmallVector<int, 8> Mask;
3158   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3159   unsigned MaskNumElts = Mask.size();
3160 
3161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3162   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3163   EVT SrcVT = Src1.getValueType();
3164   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3165 
3166   if (SrcNumElts == MaskNumElts) {
3167     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3168     return;
3169   }
3170 
3171   // Normalize the shuffle vector since mask and vector length don't match.
3172   if (SrcNumElts < MaskNumElts) {
3173     // Mask is longer than the source vectors. We can use concatenate vector to
3174     // make the mask and vectors lengths match.
3175 
3176     if (MaskNumElts % SrcNumElts == 0) {
3177       // Mask length is a multiple of the source vector length.
3178       // Check if the shuffle is some kind of concatenation of the input
3179       // vectors.
3180       unsigned NumConcat = MaskNumElts / SrcNumElts;
3181       bool IsConcat = true;
3182       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3183       for (unsigned i = 0; i != MaskNumElts; ++i) {
3184         int Idx = Mask[i];
3185         if (Idx < 0)
3186           continue;
3187         // Ensure the indices in each SrcVT sized piece are sequential and that
3188         // the same source is used for the whole piece.
3189         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3190             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3191              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3192           IsConcat = false;
3193           break;
3194         }
3195         // Remember which source this index came from.
3196         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3197       }
3198 
3199       // The shuffle is concatenating multiple vectors together. Just emit
3200       // a CONCAT_VECTORS operation.
3201       if (IsConcat) {
3202         SmallVector<SDValue, 8> ConcatOps;
3203         for (auto Src : ConcatSrcs) {
3204           if (Src < 0)
3205             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3206           else if (Src == 0)
3207             ConcatOps.push_back(Src1);
3208           else
3209             ConcatOps.push_back(Src2);
3210         }
3211         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3212         return;
3213       }
3214     }
3215 
3216     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3217     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3218     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3219                                     PaddedMaskNumElts);
3220 
3221     // Pad both vectors with undefs to make them the same length as the mask.
3222     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3223 
3224     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3225     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3226     MOps1[0] = Src1;
3227     MOps2[0] = Src2;
3228 
3229     Src1 = Src1.isUndef()
3230                ? DAG.getUNDEF(PaddedVT)
3231                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3232     Src2 = Src2.isUndef()
3233                ? DAG.getUNDEF(PaddedVT)
3234                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3235 
3236     // Readjust mask for new input vector length.
3237     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3238     for (unsigned i = 0; i != MaskNumElts; ++i) {
3239       int Idx = Mask[i];
3240       if (Idx >= (int)SrcNumElts)
3241         Idx -= SrcNumElts - PaddedMaskNumElts;
3242       MappedOps[i] = Idx;
3243     }
3244 
3245     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3246 
3247     // If the concatenated vector was padded, extract a subvector with the
3248     // correct number of elements.
3249     if (MaskNumElts != PaddedMaskNumElts)
3250       Result = DAG.getNode(
3251           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3252           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3253 
3254     setValue(&I, Result);
3255     return;
3256   }
3257 
3258   if (SrcNumElts > MaskNumElts) {
3259     // Analyze the access pattern of the vector to see if we can extract
3260     // two subvectors and do the shuffle.
3261     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3262     bool CanExtract = true;
3263     for (int Idx : Mask) {
3264       unsigned Input = 0;
3265       if (Idx < 0)
3266         continue;
3267 
3268       if (Idx >= (int)SrcNumElts) {
3269         Input = 1;
3270         Idx -= SrcNumElts;
3271       }
3272 
3273       // If all the indices come from the same MaskNumElts sized portion of
3274       // the sources we can use extract. Also make sure the extract wouldn't
3275       // extract past the end of the source.
3276       int NewStartIdx = alignDown(Idx, MaskNumElts);
3277       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3278           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3279         CanExtract = false;
3280       // Make sure we always update StartIdx as we use it to track if all
3281       // elements are undef.
3282       StartIdx[Input] = NewStartIdx;
3283     }
3284 
3285     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3286       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3287       return;
3288     }
3289     if (CanExtract) {
3290       // Extract appropriate subvector and generate a vector shuffle
3291       for (unsigned Input = 0; Input < 2; ++Input) {
3292         SDValue &Src = Input == 0 ? Src1 : Src2;
3293         if (StartIdx[Input] < 0)
3294           Src = DAG.getUNDEF(VT);
3295         else {
3296           Src = DAG.getNode(
3297               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3298               DAG.getConstant(StartIdx[Input], DL,
3299                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3300         }
3301       }
3302 
3303       // Calculate new mask.
3304       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3305       for (int &Idx : MappedOps) {
3306         if (Idx >= (int)SrcNumElts)
3307           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3308         else if (Idx >= 0)
3309           Idx -= StartIdx[0];
3310       }
3311 
3312       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3313       return;
3314     }
3315   }
3316 
3317   // We can't use either concat vectors or extract subvectors so fall back to
3318   // replacing the shuffle with extract and build vector.
3319   // to insert and build vector.
3320   EVT EltVT = VT.getVectorElementType();
3321   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3322   SmallVector<SDValue,8> Ops;
3323   for (int Idx : Mask) {
3324     SDValue Res;
3325 
3326     if (Idx < 0) {
3327       Res = DAG.getUNDEF(EltVT);
3328     } else {
3329       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3330       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3331 
3332       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3333                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3334     }
3335 
3336     Ops.push_back(Res);
3337   }
3338 
3339   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3340 }
3341 
3342 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3343   ArrayRef<unsigned> Indices;
3344   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3345     Indices = IV->getIndices();
3346   else
3347     Indices = cast<ConstantExpr>(&I)->getIndices();
3348 
3349   const Value *Op0 = I.getOperand(0);
3350   const Value *Op1 = I.getOperand(1);
3351   Type *AggTy = I.getType();
3352   Type *ValTy = Op1->getType();
3353   bool IntoUndef = isa<UndefValue>(Op0);
3354   bool FromUndef = isa<UndefValue>(Op1);
3355 
3356   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3357 
3358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3359   SmallVector<EVT, 4> AggValueVTs;
3360   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3361   SmallVector<EVT, 4> ValValueVTs;
3362   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3363 
3364   unsigned NumAggValues = AggValueVTs.size();
3365   unsigned NumValValues = ValValueVTs.size();
3366   SmallVector<SDValue, 4> Values(NumAggValues);
3367 
3368   // Ignore an insertvalue that produces an empty object
3369   if (!NumAggValues) {
3370     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3371     return;
3372   }
3373 
3374   SDValue Agg = getValue(Op0);
3375   unsigned i = 0;
3376   // Copy the beginning value(s) from the original aggregate.
3377   for (; i != LinearIndex; ++i)
3378     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3379                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3380   // Copy values from the inserted value(s).
3381   if (NumValValues) {
3382     SDValue Val = getValue(Op1);
3383     for (; i != LinearIndex + NumValValues; ++i)
3384       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3385                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3386   }
3387   // Copy remaining value(s) from the original aggregate.
3388   for (; i != NumAggValues; ++i)
3389     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3390                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3391 
3392   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3393                            DAG.getVTList(AggValueVTs), Values));
3394 }
3395 
3396 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3397   ArrayRef<unsigned> Indices;
3398   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3399     Indices = EV->getIndices();
3400   else
3401     Indices = cast<ConstantExpr>(&I)->getIndices();
3402 
3403   const Value *Op0 = I.getOperand(0);
3404   Type *AggTy = Op0->getType();
3405   Type *ValTy = I.getType();
3406   bool OutOfUndef = isa<UndefValue>(Op0);
3407 
3408   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3409 
3410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3411   SmallVector<EVT, 4> ValValueVTs;
3412   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3413 
3414   unsigned NumValValues = ValValueVTs.size();
3415 
3416   // Ignore a extractvalue that produces an empty object
3417   if (!NumValValues) {
3418     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3419     return;
3420   }
3421 
3422   SmallVector<SDValue, 4> Values(NumValValues);
3423 
3424   SDValue Agg = getValue(Op0);
3425   // Copy out the selected value(s).
3426   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3427     Values[i - LinearIndex] =
3428       OutOfUndef ?
3429         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3430         SDValue(Agg.getNode(), Agg.getResNo() + i);
3431 
3432   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3433                            DAG.getVTList(ValValueVTs), Values));
3434 }
3435 
3436 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3437   Value *Op0 = I.getOperand(0);
3438   // Note that the pointer operand may be a vector of pointers. Take the scalar
3439   // element which holds a pointer.
3440   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3441   SDValue N = getValue(Op0);
3442   SDLoc dl = getCurSDLoc();
3443 
3444   // Normalize Vector GEP - all scalar operands should be converted to the
3445   // splat vector.
3446   unsigned VectorWidth = I.getType()->isVectorTy() ?
3447     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3448 
3449   if (VectorWidth && !N.getValueType().isVector()) {
3450     LLVMContext &Context = *DAG.getContext();
3451     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3452     N = DAG.getSplatBuildVector(VT, dl, N);
3453   }
3454 
3455   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3456        GTI != E; ++GTI) {
3457     const Value *Idx = GTI.getOperand();
3458     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3459       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3460       if (Field) {
3461         // N = N + Offset
3462         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3463 
3464         // In an inbounds GEP with an offset that is nonnegative even when
3465         // interpreted as signed, assume there is no unsigned overflow.
3466         SDNodeFlags Flags;
3467         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3468           Flags.setNoUnsignedWrap(true);
3469 
3470         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3471                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3472       }
3473     } else {
3474       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3475       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3476       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3477 
3478       // If this is a scalar constant or a splat vector of constants,
3479       // handle it quickly.
3480       const auto *CI = dyn_cast<ConstantInt>(Idx);
3481       if (!CI && isa<ConstantDataVector>(Idx) &&
3482           cast<ConstantDataVector>(Idx)->getSplatValue())
3483         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3484 
3485       if (CI) {
3486         if (CI->isZero())
3487           continue;
3488         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3489         LLVMContext &Context = *DAG.getContext();
3490         SDValue OffsVal = VectorWidth ?
3491           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3492           DAG.getConstant(Offs, dl, IdxTy);
3493 
3494         // In an inbouds GEP with an offset that is nonnegative even when
3495         // interpreted as signed, assume there is no unsigned overflow.
3496         SDNodeFlags Flags;
3497         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3498           Flags.setNoUnsignedWrap(true);
3499 
3500         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3501         continue;
3502       }
3503 
3504       // N = N + Idx * ElementSize;
3505       SDValue IdxN = getValue(Idx);
3506 
3507       if (!IdxN.getValueType().isVector() && VectorWidth) {
3508         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3509         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3510       }
3511 
3512       // If the index is smaller or larger than intptr_t, truncate or extend
3513       // it.
3514       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3515 
3516       // If this is a multiply by a power of two, turn it into a shl
3517       // immediately.  This is a very common case.
3518       if (ElementSize != 1) {
3519         if (ElementSize.isPowerOf2()) {
3520           unsigned Amt = ElementSize.logBase2();
3521           IdxN = DAG.getNode(ISD::SHL, dl,
3522                              N.getValueType(), IdxN,
3523                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3524         } else {
3525           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3526           IdxN = DAG.getNode(ISD::MUL, dl,
3527                              N.getValueType(), IdxN, Scale);
3528         }
3529       }
3530 
3531       N = DAG.getNode(ISD::ADD, dl,
3532                       N.getValueType(), N, IdxN);
3533     }
3534   }
3535 
3536   setValue(&I, N);
3537 }
3538 
3539 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3540   // If this is a fixed sized alloca in the entry block of the function,
3541   // allocate it statically on the stack.
3542   if (FuncInfo.StaticAllocaMap.count(&I))
3543     return;   // getValue will auto-populate this.
3544 
3545   SDLoc dl = getCurSDLoc();
3546   Type *Ty = I.getAllocatedType();
3547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3548   auto &DL = DAG.getDataLayout();
3549   uint64_t TySize = DL.getTypeAllocSize(Ty);
3550   unsigned Align =
3551       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3552 
3553   SDValue AllocSize = getValue(I.getArraySize());
3554 
3555   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3556   if (AllocSize.getValueType() != IntPtr)
3557     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3558 
3559   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3560                           AllocSize,
3561                           DAG.getConstant(TySize, dl, IntPtr));
3562 
3563   // Handle alignment.  If the requested alignment is less than or equal to
3564   // the stack alignment, ignore it.  If the size is greater than or equal to
3565   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3566   unsigned StackAlign =
3567       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3568   if (Align <= StackAlign)
3569     Align = 0;
3570 
3571   // Round the size of the allocation up to the stack alignment size
3572   // by add SA-1 to the size. This doesn't overflow because we're computing
3573   // an address inside an alloca.
3574   SDNodeFlags Flags;
3575   Flags.setNoUnsignedWrap(true);
3576   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3577                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3578 
3579   // Mask out the low bits for alignment purposes.
3580   AllocSize =
3581       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3582                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3583 
3584   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3585   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3586   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3587   setValue(&I, DSA);
3588   DAG.setRoot(DSA.getValue(1));
3589 
3590   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3591 }
3592 
3593 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3594   if (I.isAtomic())
3595     return visitAtomicLoad(I);
3596 
3597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3598   const Value *SV = I.getOperand(0);
3599   if (TLI.supportSwiftError()) {
3600     // Swifterror values can come from either a function parameter with
3601     // swifterror attribute or an alloca with swifterror attribute.
3602     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3603       if (Arg->hasSwiftErrorAttr())
3604         return visitLoadFromSwiftError(I);
3605     }
3606 
3607     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3608       if (Alloca->isSwiftError())
3609         return visitLoadFromSwiftError(I);
3610     }
3611   }
3612 
3613   SDValue Ptr = getValue(SV);
3614 
3615   Type *Ty = I.getType();
3616 
3617   bool isVolatile = I.isVolatile();
3618   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3619   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3620   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3621   unsigned Alignment = I.getAlignment();
3622 
3623   AAMDNodes AAInfo;
3624   I.getAAMetadata(AAInfo);
3625   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3626 
3627   SmallVector<EVT, 4> ValueVTs;
3628   SmallVector<uint64_t, 4> Offsets;
3629   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3630   unsigned NumValues = ValueVTs.size();
3631   if (NumValues == 0)
3632     return;
3633 
3634   SDValue Root;
3635   bool ConstantMemory = false;
3636   if (isVolatile || NumValues > MaxParallelChains)
3637     // Serialize volatile loads with other side effects.
3638     Root = getRoot();
3639   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3640                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3641     // Do not serialize (non-volatile) loads of constant memory with anything.
3642     Root = DAG.getEntryNode();
3643     ConstantMemory = true;
3644   } else {
3645     // Do not serialize non-volatile loads against each other.
3646     Root = DAG.getRoot();
3647   }
3648 
3649   SDLoc dl = getCurSDLoc();
3650 
3651   if (isVolatile)
3652     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3653 
3654   // An aggregate load cannot wrap around the address space, so offsets to its
3655   // parts don't wrap either.
3656   SDNodeFlags Flags;
3657   Flags.setNoUnsignedWrap(true);
3658 
3659   SmallVector<SDValue, 4> Values(NumValues);
3660   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3661   EVT PtrVT = Ptr.getValueType();
3662   unsigned ChainI = 0;
3663   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3664     // Serializing loads here may result in excessive register pressure, and
3665     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3666     // could recover a bit by hoisting nodes upward in the chain by recognizing
3667     // they are side-effect free or do not alias. The optimizer should really
3668     // avoid this case by converting large object/array copies to llvm.memcpy
3669     // (MaxParallelChains should always remain as failsafe).
3670     if (ChainI == MaxParallelChains) {
3671       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3672       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3673                                   makeArrayRef(Chains.data(), ChainI));
3674       Root = Chain;
3675       ChainI = 0;
3676     }
3677     SDValue A = DAG.getNode(ISD::ADD, dl,
3678                             PtrVT, Ptr,
3679                             DAG.getConstant(Offsets[i], dl, PtrVT),
3680                             Flags);
3681     auto MMOFlags = MachineMemOperand::MONone;
3682     if (isVolatile)
3683       MMOFlags |= MachineMemOperand::MOVolatile;
3684     if (isNonTemporal)
3685       MMOFlags |= MachineMemOperand::MONonTemporal;
3686     if (isInvariant)
3687       MMOFlags |= MachineMemOperand::MOInvariant;
3688     if (isDereferenceable)
3689       MMOFlags |= MachineMemOperand::MODereferenceable;
3690     MMOFlags |= TLI.getMMOFlags(I);
3691 
3692     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3693                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3694                             MMOFlags, AAInfo, Ranges);
3695 
3696     Values[i] = L;
3697     Chains[ChainI] = L.getValue(1);
3698   }
3699 
3700   if (!ConstantMemory) {
3701     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3702                                 makeArrayRef(Chains.data(), ChainI));
3703     if (isVolatile)
3704       DAG.setRoot(Chain);
3705     else
3706       PendingLoads.push_back(Chain);
3707   }
3708 
3709   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3710                            DAG.getVTList(ValueVTs), Values));
3711 }
3712 
3713 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3714   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3715          "call visitStoreToSwiftError when backend supports swifterror");
3716 
3717   SmallVector<EVT, 4> ValueVTs;
3718   SmallVector<uint64_t, 4> Offsets;
3719   const Value *SrcV = I.getOperand(0);
3720   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3721                   SrcV->getType(), ValueVTs, &Offsets);
3722   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3723          "expect a single EVT for swifterror");
3724 
3725   SDValue Src = getValue(SrcV);
3726   // Create a virtual register, then update the virtual register.
3727   unsigned VReg; bool CreatedVReg;
3728   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3729   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3730   // Chain can be getRoot or getControlRoot.
3731   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3732                                       SDValue(Src.getNode(), Src.getResNo()));
3733   DAG.setRoot(CopyNode);
3734   if (CreatedVReg)
3735     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3736 }
3737 
3738 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3739   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3740          "call visitLoadFromSwiftError when backend supports swifterror");
3741 
3742   assert(!I.isVolatile() &&
3743          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3744          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3745          "Support volatile, non temporal, invariant for load_from_swift_error");
3746 
3747   const Value *SV = I.getOperand(0);
3748   Type *Ty = I.getType();
3749   AAMDNodes AAInfo;
3750   I.getAAMetadata(AAInfo);
3751   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3752              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3753          "load_from_swift_error should not be constant memory");
3754 
3755   SmallVector<EVT, 4> ValueVTs;
3756   SmallVector<uint64_t, 4> Offsets;
3757   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3758                   ValueVTs, &Offsets);
3759   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3760          "expect a single EVT for swifterror");
3761 
3762   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3763   SDValue L = DAG.getCopyFromReg(
3764       getRoot(), getCurSDLoc(),
3765       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3766       ValueVTs[0]);
3767 
3768   setValue(&I, L);
3769 }
3770 
3771 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3772   if (I.isAtomic())
3773     return visitAtomicStore(I);
3774 
3775   const Value *SrcV = I.getOperand(0);
3776   const Value *PtrV = I.getOperand(1);
3777 
3778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3779   if (TLI.supportSwiftError()) {
3780     // Swifterror values can come from either a function parameter with
3781     // swifterror attribute or an alloca with swifterror attribute.
3782     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3783       if (Arg->hasSwiftErrorAttr())
3784         return visitStoreToSwiftError(I);
3785     }
3786 
3787     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3788       if (Alloca->isSwiftError())
3789         return visitStoreToSwiftError(I);
3790     }
3791   }
3792 
3793   SmallVector<EVT, 4> ValueVTs;
3794   SmallVector<uint64_t, 4> Offsets;
3795   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3796                   SrcV->getType(), ValueVTs, &Offsets);
3797   unsigned NumValues = ValueVTs.size();
3798   if (NumValues == 0)
3799     return;
3800 
3801   // Get the lowered operands. Note that we do this after
3802   // checking if NumResults is zero, because with zero results
3803   // the operands won't have values in the map.
3804   SDValue Src = getValue(SrcV);
3805   SDValue Ptr = getValue(PtrV);
3806 
3807   SDValue Root = getRoot();
3808   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3809   SDLoc dl = getCurSDLoc();
3810   EVT PtrVT = Ptr.getValueType();
3811   unsigned Alignment = I.getAlignment();
3812   AAMDNodes AAInfo;
3813   I.getAAMetadata(AAInfo);
3814 
3815   auto MMOFlags = MachineMemOperand::MONone;
3816   if (I.isVolatile())
3817     MMOFlags |= MachineMemOperand::MOVolatile;
3818   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3819     MMOFlags |= MachineMemOperand::MONonTemporal;
3820   MMOFlags |= TLI.getMMOFlags(I);
3821 
3822   // An aggregate load cannot wrap around the address space, so offsets to its
3823   // parts don't wrap either.
3824   SDNodeFlags Flags;
3825   Flags.setNoUnsignedWrap(true);
3826 
3827   unsigned ChainI = 0;
3828   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3829     // See visitLoad comments.
3830     if (ChainI == MaxParallelChains) {
3831       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3832                                   makeArrayRef(Chains.data(), ChainI));
3833       Root = Chain;
3834       ChainI = 0;
3835     }
3836     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3837                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3838     SDValue St = DAG.getStore(
3839         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3840         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3841     Chains[ChainI] = St;
3842   }
3843 
3844   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3845                                   makeArrayRef(Chains.data(), ChainI));
3846   DAG.setRoot(StoreNode);
3847 }
3848 
3849 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3850                                            bool IsCompressing) {
3851   SDLoc sdl = getCurSDLoc();
3852 
3853   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3854                            unsigned& Alignment) {
3855     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3856     Src0 = I.getArgOperand(0);
3857     Ptr = I.getArgOperand(1);
3858     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3859     Mask = I.getArgOperand(3);
3860   };
3861   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3862                            unsigned& Alignment) {
3863     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3864     Src0 = I.getArgOperand(0);
3865     Ptr = I.getArgOperand(1);
3866     Mask = I.getArgOperand(2);
3867     Alignment = 0;
3868   };
3869 
3870   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3871   unsigned Alignment;
3872   if (IsCompressing)
3873     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3874   else
3875     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3876 
3877   SDValue Ptr = getValue(PtrOperand);
3878   SDValue Src0 = getValue(Src0Operand);
3879   SDValue Mask = getValue(MaskOperand);
3880 
3881   EVT VT = Src0.getValueType();
3882   if (!Alignment)
3883     Alignment = DAG.getEVTAlignment(VT);
3884 
3885   AAMDNodes AAInfo;
3886   I.getAAMetadata(AAInfo);
3887 
3888   MachineMemOperand *MMO =
3889     DAG.getMachineFunction().
3890     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3891                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3892                           Alignment, AAInfo);
3893   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3894                                          MMO, false /* Truncating */,
3895                                          IsCompressing);
3896   DAG.setRoot(StoreNode);
3897   setValue(&I, StoreNode);
3898 }
3899 
3900 // Get a uniform base for the Gather/Scatter intrinsic.
3901 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3902 // We try to represent it as a base pointer + vector of indices.
3903 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3904 // The first operand of the GEP may be a single pointer or a vector of pointers
3905 // Example:
3906 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3907 //  or
3908 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3909 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3910 //
3911 // When the first GEP operand is a single pointer - it is the uniform base we
3912 // are looking for. If first operand of the GEP is a splat vector - we
3913 // extract the splat value and use it as a uniform base.
3914 // In all other cases the function returns 'false'.
3915 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3916                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3917   SelectionDAG& DAG = SDB->DAG;
3918   LLVMContext &Context = *DAG.getContext();
3919 
3920   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3921   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3922   if (!GEP)
3923     return false;
3924 
3925   const Value *GEPPtr = GEP->getPointerOperand();
3926   if (!GEPPtr->getType()->isVectorTy())
3927     Ptr = GEPPtr;
3928   else if (!(Ptr = getSplatValue(GEPPtr)))
3929     return false;
3930 
3931   unsigned FinalIndex = GEP->getNumOperands() - 1;
3932   Value *IndexVal = GEP->getOperand(FinalIndex);
3933 
3934   // Ensure all the other indices are 0.
3935   for (unsigned i = 1; i < FinalIndex; ++i) {
3936     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3937     if (!C || !C->isZero())
3938       return false;
3939   }
3940 
3941   // The operands of the GEP may be defined in another basic block.
3942   // In this case we'll not find nodes for the operands.
3943   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3944     return false;
3945 
3946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3947   const DataLayout &DL = DAG.getDataLayout();
3948   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3949                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3950   Base = SDB->getValue(Ptr);
3951   Index = SDB->getValue(IndexVal);
3952 
3953   if (!Index.getValueType().isVector()) {
3954     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3955     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3956     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3957   }
3958   return true;
3959 }
3960 
3961 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3962   SDLoc sdl = getCurSDLoc();
3963 
3964   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3965   const Value *Ptr = I.getArgOperand(1);
3966   SDValue Src0 = getValue(I.getArgOperand(0));
3967   SDValue Mask = getValue(I.getArgOperand(3));
3968   EVT VT = Src0.getValueType();
3969   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3970   if (!Alignment)
3971     Alignment = DAG.getEVTAlignment(VT);
3972   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3973 
3974   AAMDNodes AAInfo;
3975   I.getAAMetadata(AAInfo);
3976 
3977   SDValue Base;
3978   SDValue Index;
3979   SDValue Scale;
3980   const Value *BasePtr = Ptr;
3981   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
3982 
3983   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3984   MachineMemOperand *MMO = DAG.getMachineFunction().
3985     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3986                          MachineMemOperand::MOStore,  VT.getStoreSize(),
3987                          Alignment, AAInfo);
3988   if (!UniformBase) {
3989     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3990     Index = getValue(Ptr);
3991     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3992   }
3993   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
3994   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3995                                          Ops, MMO);
3996   DAG.setRoot(Scatter);
3997   setValue(&I, Scatter);
3998 }
3999 
4000 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4001   SDLoc sdl = getCurSDLoc();
4002 
4003   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4004                            unsigned& Alignment) {
4005     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4006     Ptr = I.getArgOperand(0);
4007     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4008     Mask = I.getArgOperand(2);
4009     Src0 = I.getArgOperand(3);
4010   };
4011   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4012                            unsigned& Alignment) {
4013     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4014     Ptr = I.getArgOperand(0);
4015     Alignment = 0;
4016     Mask = I.getArgOperand(1);
4017     Src0 = I.getArgOperand(2);
4018   };
4019 
4020   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4021   unsigned Alignment;
4022   if (IsExpanding)
4023     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4024   else
4025     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4026 
4027   SDValue Ptr = getValue(PtrOperand);
4028   SDValue Src0 = getValue(Src0Operand);
4029   SDValue Mask = getValue(MaskOperand);
4030 
4031   EVT VT = Src0.getValueType();
4032   if (!Alignment)
4033     Alignment = DAG.getEVTAlignment(VT);
4034 
4035   AAMDNodes AAInfo;
4036   I.getAAMetadata(AAInfo);
4037   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4038 
4039   // Do not serialize masked loads of constant memory with anything.
4040   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
4041       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
4042   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4043 
4044   MachineMemOperand *MMO =
4045     DAG.getMachineFunction().
4046     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4047                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4048                           Alignment, AAInfo, Ranges);
4049 
4050   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4051                                    ISD::NON_EXTLOAD, IsExpanding);
4052   if (AddToChain) {
4053     SDValue OutChain = Load.getValue(1);
4054     DAG.setRoot(OutChain);
4055   }
4056   setValue(&I, Load);
4057 }
4058 
4059 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4060   SDLoc sdl = getCurSDLoc();
4061 
4062   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4063   const Value *Ptr = I.getArgOperand(0);
4064   SDValue Src0 = getValue(I.getArgOperand(3));
4065   SDValue Mask = getValue(I.getArgOperand(2));
4066 
4067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4068   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4069   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4070   if (!Alignment)
4071     Alignment = DAG.getEVTAlignment(VT);
4072 
4073   AAMDNodes AAInfo;
4074   I.getAAMetadata(AAInfo);
4075   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4076 
4077   SDValue Root = DAG.getRoot();
4078   SDValue Base;
4079   SDValue Index;
4080   SDValue Scale;
4081   const Value *BasePtr = Ptr;
4082   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4083   bool ConstantMemory = false;
4084   if (UniformBase &&
4085       AA && AA->pointsToConstantMemory(MemoryLocation(
4086           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4087           AAInfo))) {
4088     // Do not serialize (non-volatile) loads of constant memory with anything.
4089     Root = DAG.getEntryNode();
4090     ConstantMemory = true;
4091   }
4092 
4093   MachineMemOperand *MMO =
4094     DAG.getMachineFunction().
4095     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4096                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4097                          Alignment, AAInfo, Ranges);
4098 
4099   if (!UniformBase) {
4100     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4101     Index = getValue(Ptr);
4102     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4103   }
4104   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4105   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4106                                        Ops, MMO);
4107 
4108   SDValue OutChain = Gather.getValue(1);
4109   if (!ConstantMemory)
4110     PendingLoads.push_back(OutChain);
4111   setValue(&I, Gather);
4112 }
4113 
4114 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4115   SDLoc dl = getCurSDLoc();
4116   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4117   AtomicOrdering FailureOrder = I.getFailureOrdering();
4118   SyncScope::ID SSID = I.getSyncScopeID();
4119 
4120   SDValue InChain = getRoot();
4121 
4122   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4123   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4124   SDValue L = DAG.getAtomicCmpSwap(
4125       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4126       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4127       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4128       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4129 
4130   SDValue OutChain = L.getValue(2);
4131 
4132   setValue(&I, L);
4133   DAG.setRoot(OutChain);
4134 }
4135 
4136 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4137   SDLoc dl = getCurSDLoc();
4138   ISD::NodeType NT;
4139   switch (I.getOperation()) {
4140   default: llvm_unreachable("Unknown atomicrmw operation");
4141   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4142   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4143   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4144   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4145   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4146   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4147   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4148   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4149   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4150   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4151   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4152   }
4153   AtomicOrdering Order = I.getOrdering();
4154   SyncScope::ID SSID = I.getSyncScopeID();
4155 
4156   SDValue InChain = getRoot();
4157 
4158   SDValue L =
4159     DAG.getAtomic(NT, dl,
4160                   getValue(I.getValOperand()).getSimpleValueType(),
4161                   InChain,
4162                   getValue(I.getPointerOperand()),
4163                   getValue(I.getValOperand()),
4164                   I.getPointerOperand(),
4165                   /* Alignment=*/ 0, Order, SSID);
4166 
4167   SDValue OutChain = L.getValue(1);
4168 
4169   setValue(&I, L);
4170   DAG.setRoot(OutChain);
4171 }
4172 
4173 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4174   SDLoc dl = getCurSDLoc();
4175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4176   SDValue Ops[3];
4177   Ops[0] = getRoot();
4178   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4179                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4180   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4181                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4182   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4183 }
4184 
4185 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4186   SDLoc dl = getCurSDLoc();
4187   AtomicOrdering Order = I.getOrdering();
4188   SyncScope::ID SSID = I.getSyncScopeID();
4189 
4190   SDValue InChain = getRoot();
4191 
4192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4193   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4194 
4195   if (!TLI.supportsUnalignedAtomics() &&
4196       I.getAlignment() < VT.getStoreSize())
4197     report_fatal_error("Cannot generate unaligned atomic load");
4198 
4199   MachineMemOperand *MMO =
4200       DAG.getMachineFunction().
4201       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4202                            MachineMemOperand::MOVolatile |
4203                            MachineMemOperand::MOLoad,
4204                            VT.getStoreSize(),
4205                            I.getAlignment() ? I.getAlignment() :
4206                                               DAG.getEVTAlignment(VT),
4207                            AAMDNodes(), nullptr, SSID, Order);
4208 
4209   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4210   SDValue L =
4211       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4212                     getValue(I.getPointerOperand()), MMO);
4213 
4214   SDValue OutChain = L.getValue(1);
4215 
4216   setValue(&I, L);
4217   DAG.setRoot(OutChain);
4218 }
4219 
4220 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4221   SDLoc dl = getCurSDLoc();
4222 
4223   AtomicOrdering Order = I.getOrdering();
4224   SyncScope::ID SSID = I.getSyncScopeID();
4225 
4226   SDValue InChain = getRoot();
4227 
4228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4229   EVT VT =
4230       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4231 
4232   if (I.getAlignment() < VT.getStoreSize())
4233     report_fatal_error("Cannot generate unaligned atomic store");
4234 
4235   SDValue OutChain =
4236     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4237                   InChain,
4238                   getValue(I.getPointerOperand()),
4239                   getValue(I.getValueOperand()),
4240                   I.getPointerOperand(), I.getAlignment(),
4241                   Order, SSID);
4242 
4243   DAG.setRoot(OutChain);
4244 }
4245 
4246 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4247 /// node.
4248 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4249                                                unsigned Intrinsic) {
4250   // Ignore the callsite's attributes. A specific call site may be marked with
4251   // readnone, but the lowering code will expect the chain based on the
4252   // definition.
4253   const Function *F = I.getCalledFunction();
4254   bool HasChain = !F->doesNotAccessMemory();
4255   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4256 
4257   // Build the operand list.
4258   SmallVector<SDValue, 8> Ops;
4259   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4260     if (OnlyLoad) {
4261       // We don't need to serialize loads against other loads.
4262       Ops.push_back(DAG.getRoot());
4263     } else {
4264       Ops.push_back(getRoot());
4265     }
4266   }
4267 
4268   // Info is set by getTgtMemInstrinsic
4269   TargetLowering::IntrinsicInfo Info;
4270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4271   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4272                                                DAG.getMachineFunction(),
4273                                                Intrinsic);
4274 
4275   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4276   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4277       Info.opc == ISD::INTRINSIC_W_CHAIN)
4278     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4279                                         TLI.getPointerTy(DAG.getDataLayout())));
4280 
4281   // Add all operands of the call to the operand list.
4282   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4283     SDValue Op = getValue(I.getArgOperand(i));
4284     Ops.push_back(Op);
4285   }
4286 
4287   SmallVector<EVT, 4> ValueVTs;
4288   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4289 
4290   if (HasChain)
4291     ValueVTs.push_back(MVT::Other);
4292 
4293   SDVTList VTs = DAG.getVTList(ValueVTs);
4294 
4295   // Create the node.
4296   SDValue Result;
4297   if (IsTgtIntrinsic) {
4298     // This is target intrinsic that touches memory
4299     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4300       Ops, Info.memVT,
4301       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4302       Info.flags, Info.size);
4303   } else if (!HasChain) {
4304     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4305   } else if (!I.getType()->isVoidTy()) {
4306     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4307   } else {
4308     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4309   }
4310 
4311   if (HasChain) {
4312     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4313     if (OnlyLoad)
4314       PendingLoads.push_back(Chain);
4315     else
4316       DAG.setRoot(Chain);
4317   }
4318 
4319   if (!I.getType()->isVoidTy()) {
4320     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4321       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4322       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4323     } else
4324       Result = lowerRangeToAssertZExt(DAG, I, Result);
4325 
4326     setValue(&I, Result);
4327   }
4328 }
4329 
4330 /// GetSignificand - Get the significand and build it into a floating-point
4331 /// number with exponent of 1:
4332 ///
4333 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4334 ///
4335 /// where Op is the hexadecimal representation of floating point value.
4336 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4337   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4338                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4339   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4340                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4341   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4342 }
4343 
4344 /// GetExponent - Get the exponent:
4345 ///
4346 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4347 ///
4348 /// where Op is the hexadecimal representation of floating point value.
4349 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4350                            const TargetLowering &TLI, const SDLoc &dl) {
4351   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4352                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4353   SDValue t1 = DAG.getNode(
4354       ISD::SRL, dl, MVT::i32, t0,
4355       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4356   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4357                            DAG.getConstant(127, dl, MVT::i32));
4358   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4359 }
4360 
4361 /// getF32Constant - Get 32-bit floating point constant.
4362 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4363                               const SDLoc &dl) {
4364   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4365                            MVT::f32);
4366 }
4367 
4368 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4369                                        SelectionDAG &DAG) {
4370   // TODO: What fast-math-flags should be set on the floating-point nodes?
4371 
4372   //   IntegerPartOfX = ((int32_t)(t0);
4373   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4374 
4375   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4376   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4377   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4378 
4379   //   IntegerPartOfX <<= 23;
4380   IntegerPartOfX = DAG.getNode(
4381       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4382       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4383                                   DAG.getDataLayout())));
4384 
4385   SDValue TwoToFractionalPartOfX;
4386   if (LimitFloatPrecision <= 6) {
4387     // For floating-point precision of 6:
4388     //
4389     //   TwoToFractionalPartOfX =
4390     //     0.997535578f +
4391     //       (0.735607626f + 0.252464424f * x) * x;
4392     //
4393     // error 0.0144103317, which is 6 bits
4394     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4395                              getF32Constant(DAG, 0x3e814304, dl));
4396     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4397                              getF32Constant(DAG, 0x3f3c50c8, dl));
4398     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4399     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4400                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4401   } else if (LimitFloatPrecision <= 12) {
4402     // For floating-point precision of 12:
4403     //
4404     //   TwoToFractionalPartOfX =
4405     //     0.999892986f +
4406     //       (0.696457318f +
4407     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4408     //
4409     // error 0.000107046256, which is 13 to 14 bits
4410     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4411                              getF32Constant(DAG, 0x3da235e3, dl));
4412     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4413                              getF32Constant(DAG, 0x3e65b8f3, dl));
4414     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4415     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4416                              getF32Constant(DAG, 0x3f324b07, dl));
4417     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4418     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4419                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4420   } else { // LimitFloatPrecision <= 18
4421     // For floating-point precision of 18:
4422     //
4423     //   TwoToFractionalPartOfX =
4424     //     0.999999982f +
4425     //       (0.693148872f +
4426     //         (0.240227044f +
4427     //           (0.554906021e-1f +
4428     //             (0.961591928e-2f +
4429     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4430     // error 2.47208000*10^(-7), which is better than 18 bits
4431     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4432                              getF32Constant(DAG, 0x3924b03e, dl));
4433     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4434                              getF32Constant(DAG, 0x3ab24b87, dl));
4435     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4436     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4437                              getF32Constant(DAG, 0x3c1d8c17, dl));
4438     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4439     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4440                              getF32Constant(DAG, 0x3d634a1d, dl));
4441     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4442     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4443                              getF32Constant(DAG, 0x3e75fe14, dl));
4444     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4445     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4446                               getF32Constant(DAG, 0x3f317234, dl));
4447     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4448     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4449                                          getF32Constant(DAG, 0x3f800000, dl));
4450   }
4451 
4452   // Add the exponent into the result in integer domain.
4453   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4454   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4455                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4456 }
4457 
4458 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4459 /// limited-precision mode.
4460 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4461                          const TargetLowering &TLI) {
4462   if (Op.getValueType() == MVT::f32 &&
4463       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4464 
4465     // Put the exponent in the right bit position for later addition to the
4466     // final result:
4467     //
4468     //   #define LOG2OFe 1.4426950f
4469     //   t0 = Op * LOG2OFe
4470 
4471     // TODO: What fast-math-flags should be set here?
4472     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4473                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4474     return getLimitedPrecisionExp2(t0, dl, DAG);
4475   }
4476 
4477   // No special expansion.
4478   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4479 }
4480 
4481 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4482 /// limited-precision mode.
4483 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4484                          const TargetLowering &TLI) {
4485   // TODO: What fast-math-flags should be set on the floating-point nodes?
4486 
4487   if (Op.getValueType() == MVT::f32 &&
4488       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4489     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4490 
4491     // Scale the exponent by log(2) [0.69314718f].
4492     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4493     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4494                                         getF32Constant(DAG, 0x3f317218, dl));
4495 
4496     // Get the significand and build it into a floating-point number with
4497     // exponent of 1.
4498     SDValue X = GetSignificand(DAG, Op1, dl);
4499 
4500     SDValue LogOfMantissa;
4501     if (LimitFloatPrecision <= 6) {
4502       // For floating-point precision of 6:
4503       //
4504       //   LogofMantissa =
4505       //     -1.1609546f +
4506       //       (1.4034025f - 0.23903021f * x) * x;
4507       //
4508       // error 0.0034276066, which is better than 8 bits
4509       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4510                                getF32Constant(DAG, 0xbe74c456, dl));
4511       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4512                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4513       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4514       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4515                                   getF32Constant(DAG, 0x3f949a29, dl));
4516     } else if (LimitFloatPrecision <= 12) {
4517       // For floating-point precision of 12:
4518       //
4519       //   LogOfMantissa =
4520       //     -1.7417939f +
4521       //       (2.8212026f +
4522       //         (-1.4699568f +
4523       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4524       //
4525       // error 0.000061011436, which is 14 bits
4526       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4527                                getF32Constant(DAG, 0xbd67b6d6, dl));
4528       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4529                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4530       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4531       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4532                                getF32Constant(DAG, 0x3fbc278b, dl));
4533       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4534       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4535                                getF32Constant(DAG, 0x40348e95, dl));
4536       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4537       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4538                                   getF32Constant(DAG, 0x3fdef31a, dl));
4539     } else { // LimitFloatPrecision <= 18
4540       // For floating-point precision of 18:
4541       //
4542       //   LogOfMantissa =
4543       //     -2.1072184f +
4544       //       (4.2372794f +
4545       //         (-3.7029485f +
4546       //           (2.2781945f +
4547       //             (-0.87823314f +
4548       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4549       //
4550       // error 0.0000023660568, which is better than 18 bits
4551       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4552                                getF32Constant(DAG, 0xbc91e5ac, dl));
4553       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4554                                getF32Constant(DAG, 0x3e4350aa, dl));
4555       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4556       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4557                                getF32Constant(DAG, 0x3f60d3e3, dl));
4558       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4559       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4560                                getF32Constant(DAG, 0x4011cdf0, dl));
4561       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4562       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4563                                getF32Constant(DAG, 0x406cfd1c, dl));
4564       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4565       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4566                                getF32Constant(DAG, 0x408797cb, dl));
4567       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4568       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4569                                   getF32Constant(DAG, 0x4006dcab, dl));
4570     }
4571 
4572     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4573   }
4574 
4575   // No special expansion.
4576   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4577 }
4578 
4579 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4580 /// limited-precision mode.
4581 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4582                           const TargetLowering &TLI) {
4583   // TODO: What fast-math-flags should be set on the floating-point nodes?
4584 
4585   if (Op.getValueType() == MVT::f32 &&
4586       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4587     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4588 
4589     // Get the exponent.
4590     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4591 
4592     // Get the significand and build it into a floating-point number with
4593     // exponent of 1.
4594     SDValue X = GetSignificand(DAG, Op1, dl);
4595 
4596     // Different possible minimax approximations of significand in
4597     // floating-point for various degrees of accuracy over [1,2].
4598     SDValue Log2ofMantissa;
4599     if (LimitFloatPrecision <= 6) {
4600       // For floating-point precision of 6:
4601       //
4602       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4603       //
4604       // error 0.0049451742, which is more than 7 bits
4605       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4606                                getF32Constant(DAG, 0xbeb08fe0, dl));
4607       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4608                                getF32Constant(DAG, 0x40019463, dl));
4609       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4610       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4611                                    getF32Constant(DAG, 0x3fd6633d, dl));
4612     } else if (LimitFloatPrecision <= 12) {
4613       // For floating-point precision of 12:
4614       //
4615       //   Log2ofMantissa =
4616       //     -2.51285454f +
4617       //       (4.07009056f +
4618       //         (-2.12067489f +
4619       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4620       //
4621       // error 0.0000876136000, which is better than 13 bits
4622       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4623                                getF32Constant(DAG, 0xbda7262e, dl));
4624       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4625                                getF32Constant(DAG, 0x3f25280b, dl));
4626       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4627       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4628                                getF32Constant(DAG, 0x4007b923, dl));
4629       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4630       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4631                                getF32Constant(DAG, 0x40823e2f, dl));
4632       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4633       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4634                                    getF32Constant(DAG, 0x4020d29c, dl));
4635     } else { // LimitFloatPrecision <= 18
4636       // For floating-point precision of 18:
4637       //
4638       //   Log2ofMantissa =
4639       //     -3.0400495f +
4640       //       (6.1129976f +
4641       //         (-5.3420409f +
4642       //           (3.2865683f +
4643       //             (-1.2669343f +
4644       //               (0.27515199f -
4645       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4646       //
4647       // error 0.0000018516, which is better than 18 bits
4648       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4649                                getF32Constant(DAG, 0xbcd2769e, dl));
4650       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4651                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4652       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4653       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4654                                getF32Constant(DAG, 0x3fa22ae7, dl));
4655       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4656       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4657                                getF32Constant(DAG, 0x40525723, dl));
4658       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4659       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4660                                getF32Constant(DAG, 0x40aaf200, dl));
4661       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4662       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4663                                getF32Constant(DAG, 0x40c39dad, dl));
4664       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4665       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4666                                    getF32Constant(DAG, 0x4042902c, dl));
4667     }
4668 
4669     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4670   }
4671 
4672   // No special expansion.
4673   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4674 }
4675 
4676 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4677 /// limited-precision mode.
4678 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4679                            const TargetLowering &TLI) {
4680   // TODO: What fast-math-flags should be set on the floating-point nodes?
4681 
4682   if (Op.getValueType() == MVT::f32 &&
4683       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4684     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4685 
4686     // Scale the exponent by log10(2) [0.30102999f].
4687     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4688     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4689                                         getF32Constant(DAG, 0x3e9a209a, dl));
4690 
4691     // Get the significand and build it into a floating-point number with
4692     // exponent of 1.
4693     SDValue X = GetSignificand(DAG, Op1, dl);
4694 
4695     SDValue Log10ofMantissa;
4696     if (LimitFloatPrecision <= 6) {
4697       // For floating-point precision of 6:
4698       //
4699       //   Log10ofMantissa =
4700       //     -0.50419619f +
4701       //       (0.60948995f - 0.10380950f * x) * x;
4702       //
4703       // error 0.0014886165, which is 6 bits
4704       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4705                                getF32Constant(DAG, 0xbdd49a13, dl));
4706       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4707                                getF32Constant(DAG, 0x3f1c0789, dl));
4708       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4709       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4710                                     getF32Constant(DAG, 0x3f011300, dl));
4711     } else if (LimitFloatPrecision <= 12) {
4712       // For floating-point precision of 12:
4713       //
4714       //   Log10ofMantissa =
4715       //     -0.64831180f +
4716       //       (0.91751397f +
4717       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4718       //
4719       // error 0.00019228036, which is better than 12 bits
4720       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4721                                getF32Constant(DAG, 0x3d431f31, dl));
4722       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4723                                getF32Constant(DAG, 0x3ea21fb2, dl));
4724       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4725       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4726                                getF32Constant(DAG, 0x3f6ae232, dl));
4727       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4728       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4729                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4730     } else { // LimitFloatPrecision <= 18
4731       // For floating-point precision of 18:
4732       //
4733       //   Log10ofMantissa =
4734       //     -0.84299375f +
4735       //       (1.5327582f +
4736       //         (-1.0688956f +
4737       //           (0.49102474f +
4738       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4739       //
4740       // error 0.0000037995730, which is better than 18 bits
4741       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4742                                getF32Constant(DAG, 0x3c5d51ce, dl));
4743       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4744                                getF32Constant(DAG, 0x3e00685a, dl));
4745       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4746       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4747                                getF32Constant(DAG, 0x3efb6798, dl));
4748       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4749       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4750                                getF32Constant(DAG, 0x3f88d192, dl));
4751       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4752       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4753                                getF32Constant(DAG, 0x3fc4316c, dl));
4754       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4755       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4756                                     getF32Constant(DAG, 0x3f57ce70, dl));
4757     }
4758 
4759     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4760   }
4761 
4762   // No special expansion.
4763   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4764 }
4765 
4766 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4767 /// limited-precision mode.
4768 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4769                           const TargetLowering &TLI) {
4770   if (Op.getValueType() == MVT::f32 &&
4771       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4772     return getLimitedPrecisionExp2(Op, dl, DAG);
4773 
4774   // No special expansion.
4775   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4776 }
4777 
4778 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4779 /// limited-precision mode with x == 10.0f.
4780 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4781                          SelectionDAG &DAG, const TargetLowering &TLI) {
4782   bool IsExp10 = false;
4783   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4784       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4785     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4786       APFloat Ten(10.0f);
4787       IsExp10 = LHSC->isExactlyValue(Ten);
4788     }
4789   }
4790 
4791   // TODO: What fast-math-flags should be set on the FMUL node?
4792   if (IsExp10) {
4793     // Put the exponent in the right bit position for later addition to the
4794     // final result:
4795     //
4796     //   #define LOG2OF10 3.3219281f
4797     //   t0 = Op * LOG2OF10;
4798     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4799                              getF32Constant(DAG, 0x40549a78, dl));
4800     return getLimitedPrecisionExp2(t0, dl, DAG);
4801   }
4802 
4803   // No special expansion.
4804   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4805 }
4806 
4807 /// ExpandPowI - Expand a llvm.powi intrinsic.
4808 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4809                           SelectionDAG &DAG) {
4810   // If RHS is a constant, we can expand this out to a multiplication tree,
4811   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4812   // optimizing for size, we only want to do this if the expansion would produce
4813   // a small number of multiplies, otherwise we do the full expansion.
4814   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4815     // Get the exponent as a positive value.
4816     unsigned Val = RHSC->getSExtValue();
4817     if ((int)Val < 0) Val = -Val;
4818 
4819     // powi(x, 0) -> 1.0
4820     if (Val == 0)
4821       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4822 
4823     const Function &F = DAG.getMachineFunction().getFunction();
4824     if (!F.optForSize() ||
4825         // If optimizing for size, don't insert too many multiplies.
4826         // This inserts up to 5 multiplies.
4827         countPopulation(Val) + Log2_32(Val) < 7) {
4828       // We use the simple binary decomposition method to generate the multiply
4829       // sequence.  There are more optimal ways to do this (for example,
4830       // powi(x,15) generates one more multiply than it should), but this has
4831       // the benefit of being both really simple and much better than a libcall.
4832       SDValue Res;  // Logically starts equal to 1.0
4833       SDValue CurSquare = LHS;
4834       // TODO: Intrinsics should have fast-math-flags that propagate to these
4835       // nodes.
4836       while (Val) {
4837         if (Val & 1) {
4838           if (Res.getNode())
4839             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4840           else
4841             Res = CurSquare;  // 1.0*CurSquare.
4842         }
4843 
4844         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4845                                 CurSquare, CurSquare);
4846         Val >>= 1;
4847       }
4848 
4849       // If the original was negative, invert the result, producing 1/(x*x*x).
4850       if (RHSC->getSExtValue() < 0)
4851         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4852                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4853       return Res;
4854     }
4855   }
4856 
4857   // Otherwise, expand to a libcall.
4858   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4859 }
4860 
4861 // getUnderlyingArgReg - Find underlying register used for a truncated or
4862 // bitcasted argument.
4863 static unsigned getUnderlyingArgReg(const SDValue &N) {
4864   switch (N.getOpcode()) {
4865   case ISD::CopyFromReg:
4866     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4867   case ISD::BITCAST:
4868   case ISD::AssertZext:
4869   case ISD::AssertSext:
4870   case ISD::TRUNCATE:
4871     return getUnderlyingArgReg(N.getOperand(0));
4872   default:
4873     return 0;
4874   }
4875 }
4876 
4877 /// If the DbgValueInst is a dbg_value of a function argument, create the
4878 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4879 /// instruction selection, they will be inserted to the entry BB.
4880 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4881     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4882     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4883   const Argument *Arg = dyn_cast<Argument>(V);
4884   if (!Arg)
4885     return false;
4886 
4887   MachineFunction &MF = DAG.getMachineFunction();
4888   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4889 
4890   bool IsIndirect = false;
4891   Optional<MachineOperand> Op;
4892   // Some arguments' frame index is recorded during argument lowering.
4893   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4894   if (FI != std::numeric_limits<int>::max())
4895     Op = MachineOperand::CreateFI(FI);
4896 
4897   if (!Op && N.getNode()) {
4898     unsigned Reg = getUnderlyingArgReg(N);
4899     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4900       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4901       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4902       if (PR)
4903         Reg = PR;
4904     }
4905     if (Reg) {
4906       Op = MachineOperand::CreateReg(Reg, false);
4907       IsIndirect = IsDbgDeclare;
4908     }
4909   }
4910 
4911   if (!Op && N.getNode())
4912     // Check if frame index is available.
4913     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4914       if (FrameIndexSDNode *FINode =
4915           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4916         Op = MachineOperand::CreateFI(FINode->getIndex());
4917 
4918   if (!Op) {
4919     // Check if ValueMap has reg number.
4920     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4921     if (VMI != FuncInfo.ValueMap.end()) {
4922       const auto &TLI = DAG.getTargetLoweringInfo();
4923       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4924                        V->getType(), isABIRegCopy(V));
4925       if (RFV.occupiesMultipleRegs()) {
4926         unsigned Offset = 0;
4927         for (auto RegAndSize : RFV.getRegsAndSizes()) {
4928           Op = MachineOperand::CreateReg(RegAndSize.first, false);
4929           auto FragmentExpr = DIExpression::createFragmentExpression(
4930               Expr, Offset, RegAndSize.second);
4931           if (!FragmentExpr)
4932             continue;
4933           FuncInfo.ArgDbgValues.push_back(
4934               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4935                       Op->getReg(), Variable, *FragmentExpr));
4936           Offset += RegAndSize.second;
4937         }
4938         return true;
4939       }
4940       Op = MachineOperand::CreateReg(VMI->second, false);
4941       IsIndirect = IsDbgDeclare;
4942     }
4943   }
4944 
4945   if (!Op)
4946     return false;
4947 
4948   assert(Variable->isValidLocationForIntrinsic(DL) &&
4949          "Expected inlined-at fields to agree");
4950   if (Op->isReg())
4951     FuncInfo.ArgDbgValues.push_back(
4952         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4953                 Op->getReg(), Variable, Expr));
4954   else
4955     FuncInfo.ArgDbgValues.push_back(
4956         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4957             .add(*Op)
4958             .addImm(0)
4959             .addMetadata(Variable)
4960             .addMetadata(Expr));
4961 
4962   return true;
4963 }
4964 
4965 /// Return the appropriate SDDbgValue based on N.
4966 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4967                                              DILocalVariable *Variable,
4968                                              DIExpression *Expr,
4969                                              const DebugLoc &dl,
4970                                              unsigned DbgSDNodeOrder) {
4971   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
4972     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
4973     // stack slot locations as such instead of as indirectly addressed
4974     // locations.
4975     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
4976                                      DbgSDNodeOrder);
4977   }
4978   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
4979                          DbgSDNodeOrder);
4980 }
4981 
4982 // VisualStudio defines setjmp as _setjmp
4983 #if defined(_MSC_VER) && defined(setjmp) && \
4984                          !defined(setjmp_undefined_for_msvc)
4985 #  pragma push_macro("setjmp")
4986 #  undef setjmp
4987 #  define setjmp_undefined_for_msvc
4988 #endif
4989 
4990 /// Lower the call to the specified intrinsic function. If we want to emit this
4991 /// as a call to a named external function, return the name. Otherwise, lower it
4992 /// and return null.
4993 const char *
4994 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4996   SDLoc sdl = getCurSDLoc();
4997   DebugLoc dl = getCurDebugLoc();
4998   SDValue Res;
4999 
5000   switch (Intrinsic) {
5001   default:
5002     // By default, turn this into a target intrinsic node.
5003     visitTargetIntrinsic(I, Intrinsic);
5004     return nullptr;
5005   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5006   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5007   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5008   case Intrinsic::returnaddress:
5009     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5010                              TLI.getPointerTy(DAG.getDataLayout()),
5011                              getValue(I.getArgOperand(0))));
5012     return nullptr;
5013   case Intrinsic::addressofreturnaddress:
5014     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5015                              TLI.getPointerTy(DAG.getDataLayout())));
5016     return nullptr;
5017   case Intrinsic::frameaddress:
5018     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5019                              TLI.getPointerTy(DAG.getDataLayout()),
5020                              getValue(I.getArgOperand(0))));
5021     return nullptr;
5022   case Intrinsic::read_register: {
5023     Value *Reg = I.getArgOperand(0);
5024     SDValue Chain = getRoot();
5025     SDValue RegName =
5026         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5027     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5028     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5029       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5030     setValue(&I, Res);
5031     DAG.setRoot(Res.getValue(1));
5032     return nullptr;
5033   }
5034   case Intrinsic::write_register: {
5035     Value *Reg = I.getArgOperand(0);
5036     Value *RegValue = I.getArgOperand(1);
5037     SDValue Chain = getRoot();
5038     SDValue RegName =
5039         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5040     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5041                             RegName, getValue(RegValue)));
5042     return nullptr;
5043   }
5044   case Intrinsic::setjmp:
5045     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5046   case Intrinsic::longjmp:
5047     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5048   case Intrinsic::memcpy: {
5049     const auto &MCI = cast<MemCpyInst>(I);
5050     SDValue Op1 = getValue(I.getArgOperand(0));
5051     SDValue Op2 = getValue(I.getArgOperand(1));
5052     SDValue Op3 = getValue(I.getArgOperand(2));
5053     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5054     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5055     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5056     unsigned Align = MinAlign(DstAlign, SrcAlign);
5057     bool isVol = MCI.isVolatile();
5058     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5059     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5060     // node.
5061     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5062                                false, isTC,
5063                                MachinePointerInfo(I.getArgOperand(0)),
5064                                MachinePointerInfo(I.getArgOperand(1)));
5065     updateDAGForMaybeTailCall(MC);
5066     return nullptr;
5067   }
5068   case Intrinsic::memset: {
5069     const auto &MSI = cast<MemSetInst>(I);
5070     SDValue Op1 = getValue(I.getArgOperand(0));
5071     SDValue Op2 = getValue(I.getArgOperand(1));
5072     SDValue Op3 = getValue(I.getArgOperand(2));
5073     // @llvm.memset defines 0 and 1 to both mean no alignment.
5074     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5075     bool isVol = MSI.isVolatile();
5076     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5077     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5078                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5079     updateDAGForMaybeTailCall(MS);
5080     return nullptr;
5081   }
5082   case Intrinsic::memmove: {
5083     const auto &MMI = cast<MemMoveInst>(I);
5084     SDValue Op1 = getValue(I.getArgOperand(0));
5085     SDValue Op2 = getValue(I.getArgOperand(1));
5086     SDValue Op3 = getValue(I.getArgOperand(2));
5087     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5088     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5089     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5090     unsigned Align = MinAlign(DstAlign, SrcAlign);
5091     bool isVol = MMI.isVolatile();
5092     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5093     // FIXME: Support passing different dest/src alignments to the memmove DAG
5094     // node.
5095     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5096                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5097                                 MachinePointerInfo(I.getArgOperand(1)));
5098     updateDAGForMaybeTailCall(MM);
5099     return nullptr;
5100   }
5101   case Intrinsic::memcpy_element_unordered_atomic: {
5102     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5103     SDValue Dst = getValue(MI.getRawDest());
5104     SDValue Src = getValue(MI.getRawSource());
5105     SDValue Length = getValue(MI.getLength());
5106 
5107     unsigned DstAlign = MI.getDestAlignment();
5108     unsigned SrcAlign = MI.getSourceAlignment();
5109     Type *LengthTy = MI.getLength()->getType();
5110     unsigned ElemSz = MI.getElementSizeInBytes();
5111     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5112     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5113                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5114                                      MachinePointerInfo(MI.getRawDest()),
5115                                      MachinePointerInfo(MI.getRawSource()));
5116     updateDAGForMaybeTailCall(MC);
5117     return nullptr;
5118   }
5119   case Intrinsic::memmove_element_unordered_atomic: {
5120     auto &MI = cast<AtomicMemMoveInst>(I);
5121     SDValue Dst = getValue(MI.getRawDest());
5122     SDValue Src = getValue(MI.getRawSource());
5123     SDValue Length = getValue(MI.getLength());
5124 
5125     unsigned DstAlign = MI.getDestAlignment();
5126     unsigned SrcAlign = MI.getSourceAlignment();
5127     Type *LengthTy = MI.getLength()->getType();
5128     unsigned ElemSz = MI.getElementSizeInBytes();
5129     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5130     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5131                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5132                                       MachinePointerInfo(MI.getRawDest()),
5133                                       MachinePointerInfo(MI.getRawSource()));
5134     updateDAGForMaybeTailCall(MC);
5135     return nullptr;
5136   }
5137   case Intrinsic::memset_element_unordered_atomic: {
5138     auto &MI = cast<AtomicMemSetInst>(I);
5139     SDValue Dst = getValue(MI.getRawDest());
5140     SDValue Val = getValue(MI.getValue());
5141     SDValue Length = getValue(MI.getLength());
5142 
5143     unsigned DstAlign = MI.getDestAlignment();
5144     Type *LengthTy = MI.getLength()->getType();
5145     unsigned ElemSz = MI.getElementSizeInBytes();
5146     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5147     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5148                                      LengthTy, ElemSz, isTC,
5149                                      MachinePointerInfo(MI.getRawDest()));
5150     updateDAGForMaybeTailCall(MC);
5151     return nullptr;
5152   }
5153   case Intrinsic::dbg_addr:
5154   case Intrinsic::dbg_declare: {
5155     const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
5156     DILocalVariable *Variable = DI.getVariable();
5157     DIExpression *Expression = DI.getExpression();
5158     dropDanglingDebugInfo(Variable, Expression);
5159     assert(Variable && "Missing variable");
5160 
5161     // Check if address has undef value.
5162     const Value *Address = DI.getVariableLocation();
5163     if (!Address || isa<UndefValue>(Address) ||
5164         (Address->use_empty() && !isa<Argument>(Address))) {
5165       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5166       return nullptr;
5167     }
5168 
5169     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5170 
5171     // Check if this variable can be described by a frame index, typically
5172     // either as a static alloca or a byval parameter.
5173     int FI = std::numeric_limits<int>::max();
5174     if (const auto *AI =
5175             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5176       if (AI->isStaticAlloca()) {
5177         auto I = FuncInfo.StaticAllocaMap.find(AI);
5178         if (I != FuncInfo.StaticAllocaMap.end())
5179           FI = I->second;
5180       }
5181     } else if (const auto *Arg = dyn_cast<Argument>(
5182                    Address->stripInBoundsConstantOffsets())) {
5183       FI = FuncInfo.getArgumentFrameIndex(Arg);
5184     }
5185 
5186     // llvm.dbg.addr is control dependent and always generates indirect
5187     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5188     // the MachineFunction variable table.
5189     if (FI != std::numeric_limits<int>::max()) {
5190       if (Intrinsic == Intrinsic::dbg_addr) {
5191          SDDbgValue *SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5192                                                      FI, dl, SDNodeOrder);
5193          DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5194       }
5195       return nullptr;
5196     }
5197 
5198     SDValue &N = NodeMap[Address];
5199     if (!N.getNode() && isa<Argument>(Address))
5200       // Check unused arguments map.
5201       N = UnusedArgNodeMap[Address];
5202     SDDbgValue *SDV;
5203     if (N.getNode()) {
5204       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5205         Address = BCI->getOperand(0);
5206       // Parameters are handled specially.
5207       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5208       if (isParameter && FINode) {
5209         // Byval parameter. We have a frame index at this point.
5210         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5211                                         FINode->getIndex(), dl, SDNodeOrder);
5212       } else if (isa<Argument>(Address)) {
5213         // Address is an argument, so try to emit its dbg value using
5214         // virtual register info from the FuncInfo.ValueMap.
5215         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5216         return nullptr;
5217       } else {
5218         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5219                               true, dl, SDNodeOrder);
5220       }
5221       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5222     } else {
5223       // If Address is an argument then try to emit its dbg value using
5224       // virtual register info from the FuncInfo.ValueMap.
5225       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5226                                     N)) {
5227         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5228       }
5229     }
5230     return nullptr;
5231   }
5232   case Intrinsic::dbg_label: {
5233     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5234     DILabel *Label = DI.getLabel();
5235     assert(Label && "Missing label");
5236 
5237     SDDbgLabel *SDV;
5238     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5239     DAG.AddDbgLabel(SDV);
5240     return nullptr;
5241   }
5242   case Intrinsic::dbg_value: {
5243     const DbgValueInst &DI = cast<DbgValueInst>(I);
5244     assert(DI.getVariable() && "Missing variable");
5245 
5246     DILocalVariable *Variable = DI.getVariable();
5247     DIExpression *Expression = DI.getExpression();
5248     dropDanglingDebugInfo(Variable, Expression);
5249     const Value *V = DI.getValue();
5250     if (!V)
5251       return nullptr;
5252 
5253     SDDbgValue *SDV;
5254     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5255       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5256       DAG.AddDbgValue(SDV, nullptr, false);
5257       return nullptr;
5258     }
5259 
5260     // Do not use getValue() in here; we don't want to generate code at
5261     // this point if it hasn't been done yet.
5262     SDValue N = NodeMap[V];
5263     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5264       N = UnusedArgNodeMap[V];
5265     if (N.getNode()) {
5266       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5267         return nullptr;
5268       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5269       DAG.AddDbgValue(SDV, N.getNode(), false);
5270       return nullptr;
5271     }
5272 
5273     // PHI nodes have already been selected, so we should know which VReg that
5274     // is assigns to already.
5275     if (isa<PHINode>(V)) {
5276       auto VMI = FuncInfo.ValueMap.find(V);
5277       if (VMI != FuncInfo.ValueMap.end()) {
5278         unsigned Reg = VMI->second;
5279         // The PHI node may be split up into several MI PHI nodes (in
5280         // FunctionLoweringInfo::set).
5281         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5282                          V->getType(), false);
5283         if (RFV.occupiesMultipleRegs()) {
5284           unsigned Offset = 0;
5285           unsigned BitsToDescribe = 0;
5286           if (auto VarSize = Variable->getSizeInBits())
5287             BitsToDescribe = *VarSize;
5288           if (auto Fragment = Expression->getFragmentInfo())
5289             BitsToDescribe = Fragment->SizeInBits;
5290           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5291             unsigned RegisterSize = RegAndSize.second;
5292             // Bail out if all bits are described already.
5293             if (Offset >= BitsToDescribe)
5294               break;
5295             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5296                 ? BitsToDescribe - Offset
5297                 : RegisterSize;
5298             auto FragmentExpr = DIExpression::createFragmentExpression(
5299                 Expression, Offset, FragmentSize);
5300             if (!FragmentExpr)
5301                 continue;
5302             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5303                                       false, dl, SDNodeOrder);
5304             DAG.AddDbgValue(SDV, nullptr, false);
5305             Offset += RegisterSize;
5306           }
5307         } else {
5308           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5309                                     SDNodeOrder);
5310           DAG.AddDbgValue(SDV, nullptr, false);
5311         }
5312         return nullptr;
5313       }
5314     }
5315 
5316     // TODO: When we get here we will either drop the dbg.value completely, or
5317     // we try to move it forward by letting it dangle for awhile. So we should
5318     // probably add an extra DbgValue to the DAG here, with a reference to
5319     // "noreg", to indicate that we have lost the debug location for the
5320     // variable.
5321 
5322     if (!V->use_empty() ) {
5323       // Do not call getValue(V) yet, as we don't want to generate code.
5324       // Remember it for later.
5325       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
5326       DanglingDebugInfoMap[V].push_back(DDI);
5327       return nullptr;
5328     }
5329 
5330     DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5331     DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5332     return nullptr;
5333   }
5334 
5335   case Intrinsic::eh_typeid_for: {
5336     // Find the type id for the given typeinfo.
5337     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5338     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5339     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5340     setValue(&I, Res);
5341     return nullptr;
5342   }
5343 
5344   case Intrinsic::eh_return_i32:
5345   case Intrinsic::eh_return_i64:
5346     DAG.getMachineFunction().setCallsEHReturn(true);
5347     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5348                             MVT::Other,
5349                             getControlRoot(),
5350                             getValue(I.getArgOperand(0)),
5351                             getValue(I.getArgOperand(1))));
5352     return nullptr;
5353   case Intrinsic::eh_unwind_init:
5354     DAG.getMachineFunction().setCallsUnwindInit(true);
5355     return nullptr;
5356   case Intrinsic::eh_dwarf_cfa:
5357     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5358                              TLI.getPointerTy(DAG.getDataLayout()),
5359                              getValue(I.getArgOperand(0))));
5360     return nullptr;
5361   case Intrinsic::eh_sjlj_callsite: {
5362     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5363     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5364     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5365     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5366 
5367     MMI.setCurrentCallSite(CI->getZExtValue());
5368     return nullptr;
5369   }
5370   case Intrinsic::eh_sjlj_functioncontext: {
5371     // Get and store the index of the function context.
5372     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5373     AllocaInst *FnCtx =
5374       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5375     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5376     MFI.setFunctionContextIndex(FI);
5377     return nullptr;
5378   }
5379   case Intrinsic::eh_sjlj_setjmp: {
5380     SDValue Ops[2];
5381     Ops[0] = getRoot();
5382     Ops[1] = getValue(I.getArgOperand(0));
5383     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5384                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5385     setValue(&I, Op.getValue(0));
5386     DAG.setRoot(Op.getValue(1));
5387     return nullptr;
5388   }
5389   case Intrinsic::eh_sjlj_longjmp:
5390     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5391                             getRoot(), getValue(I.getArgOperand(0))));
5392     return nullptr;
5393   case Intrinsic::eh_sjlj_setup_dispatch:
5394     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5395                             getRoot()));
5396     return nullptr;
5397   case Intrinsic::masked_gather:
5398     visitMaskedGather(I);
5399     return nullptr;
5400   case Intrinsic::masked_load:
5401     visitMaskedLoad(I);
5402     return nullptr;
5403   case Intrinsic::masked_scatter:
5404     visitMaskedScatter(I);
5405     return nullptr;
5406   case Intrinsic::masked_store:
5407     visitMaskedStore(I);
5408     return nullptr;
5409   case Intrinsic::masked_expandload:
5410     visitMaskedLoad(I, true /* IsExpanding */);
5411     return nullptr;
5412   case Intrinsic::masked_compressstore:
5413     visitMaskedStore(I, true /* IsCompressing */);
5414     return nullptr;
5415   case Intrinsic::x86_mmx_pslli_w:
5416   case Intrinsic::x86_mmx_pslli_d:
5417   case Intrinsic::x86_mmx_pslli_q:
5418   case Intrinsic::x86_mmx_psrli_w:
5419   case Intrinsic::x86_mmx_psrli_d:
5420   case Intrinsic::x86_mmx_psrli_q:
5421   case Intrinsic::x86_mmx_psrai_w:
5422   case Intrinsic::x86_mmx_psrai_d: {
5423     SDValue ShAmt = getValue(I.getArgOperand(1));
5424     if (isa<ConstantSDNode>(ShAmt)) {
5425       visitTargetIntrinsic(I, Intrinsic);
5426       return nullptr;
5427     }
5428     unsigned NewIntrinsic = 0;
5429     EVT ShAmtVT = MVT::v2i32;
5430     switch (Intrinsic) {
5431     case Intrinsic::x86_mmx_pslli_w:
5432       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5433       break;
5434     case Intrinsic::x86_mmx_pslli_d:
5435       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5436       break;
5437     case Intrinsic::x86_mmx_pslli_q:
5438       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5439       break;
5440     case Intrinsic::x86_mmx_psrli_w:
5441       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5442       break;
5443     case Intrinsic::x86_mmx_psrli_d:
5444       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5445       break;
5446     case Intrinsic::x86_mmx_psrli_q:
5447       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5448       break;
5449     case Intrinsic::x86_mmx_psrai_w:
5450       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5451       break;
5452     case Intrinsic::x86_mmx_psrai_d:
5453       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5454       break;
5455     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5456     }
5457 
5458     // The vector shift intrinsics with scalars uses 32b shift amounts but
5459     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5460     // to be zero.
5461     // We must do this early because v2i32 is not a legal type.
5462     SDValue ShOps[2];
5463     ShOps[0] = ShAmt;
5464     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5465     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5466     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5467     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5468     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5469                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5470                        getValue(I.getArgOperand(0)), ShAmt);
5471     setValue(&I, Res);
5472     return nullptr;
5473   }
5474   case Intrinsic::powi:
5475     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5476                             getValue(I.getArgOperand(1)), DAG));
5477     return nullptr;
5478   case Intrinsic::log:
5479     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5480     return nullptr;
5481   case Intrinsic::log2:
5482     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5483     return nullptr;
5484   case Intrinsic::log10:
5485     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5486     return nullptr;
5487   case Intrinsic::exp:
5488     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5489     return nullptr;
5490   case Intrinsic::exp2:
5491     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5492     return nullptr;
5493   case Intrinsic::pow:
5494     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5495                            getValue(I.getArgOperand(1)), DAG, TLI));
5496     return nullptr;
5497   case Intrinsic::sqrt:
5498   case Intrinsic::fabs:
5499   case Intrinsic::sin:
5500   case Intrinsic::cos:
5501   case Intrinsic::floor:
5502   case Intrinsic::ceil:
5503   case Intrinsic::trunc:
5504   case Intrinsic::rint:
5505   case Intrinsic::nearbyint:
5506   case Intrinsic::round:
5507   case Intrinsic::canonicalize: {
5508     unsigned Opcode;
5509     switch (Intrinsic) {
5510     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5511     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5512     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5513     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5514     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5515     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5516     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5517     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5518     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5519     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5520     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5521     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5522     }
5523 
5524     setValue(&I, DAG.getNode(Opcode, sdl,
5525                              getValue(I.getArgOperand(0)).getValueType(),
5526                              getValue(I.getArgOperand(0))));
5527     return nullptr;
5528   }
5529   case Intrinsic::minnum: {
5530     auto VT = getValue(I.getArgOperand(0)).getValueType();
5531     unsigned Opc =
5532         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5533             ? ISD::FMINNAN
5534             : ISD::FMINNUM;
5535     setValue(&I, DAG.getNode(Opc, sdl, VT,
5536                              getValue(I.getArgOperand(0)),
5537                              getValue(I.getArgOperand(1))));
5538     return nullptr;
5539   }
5540   case Intrinsic::maxnum: {
5541     auto VT = getValue(I.getArgOperand(0)).getValueType();
5542     unsigned Opc =
5543         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5544             ? ISD::FMAXNAN
5545             : ISD::FMAXNUM;
5546     setValue(&I, DAG.getNode(Opc, sdl, VT,
5547                              getValue(I.getArgOperand(0)),
5548                              getValue(I.getArgOperand(1))));
5549     return nullptr;
5550   }
5551   case Intrinsic::copysign:
5552     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5553                              getValue(I.getArgOperand(0)).getValueType(),
5554                              getValue(I.getArgOperand(0)),
5555                              getValue(I.getArgOperand(1))));
5556     return nullptr;
5557   case Intrinsic::fma:
5558     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5559                              getValue(I.getArgOperand(0)).getValueType(),
5560                              getValue(I.getArgOperand(0)),
5561                              getValue(I.getArgOperand(1)),
5562                              getValue(I.getArgOperand(2))));
5563     return nullptr;
5564   case Intrinsic::experimental_constrained_fadd:
5565   case Intrinsic::experimental_constrained_fsub:
5566   case Intrinsic::experimental_constrained_fmul:
5567   case Intrinsic::experimental_constrained_fdiv:
5568   case Intrinsic::experimental_constrained_frem:
5569   case Intrinsic::experimental_constrained_fma:
5570   case Intrinsic::experimental_constrained_sqrt:
5571   case Intrinsic::experimental_constrained_pow:
5572   case Intrinsic::experimental_constrained_powi:
5573   case Intrinsic::experimental_constrained_sin:
5574   case Intrinsic::experimental_constrained_cos:
5575   case Intrinsic::experimental_constrained_exp:
5576   case Intrinsic::experimental_constrained_exp2:
5577   case Intrinsic::experimental_constrained_log:
5578   case Intrinsic::experimental_constrained_log10:
5579   case Intrinsic::experimental_constrained_log2:
5580   case Intrinsic::experimental_constrained_rint:
5581   case Intrinsic::experimental_constrained_nearbyint:
5582     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5583     return nullptr;
5584   case Intrinsic::fmuladd: {
5585     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5586     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5587         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5588       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5589                                getValue(I.getArgOperand(0)).getValueType(),
5590                                getValue(I.getArgOperand(0)),
5591                                getValue(I.getArgOperand(1)),
5592                                getValue(I.getArgOperand(2))));
5593     } else {
5594       // TODO: Intrinsic calls should have fast-math-flags.
5595       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5596                                 getValue(I.getArgOperand(0)).getValueType(),
5597                                 getValue(I.getArgOperand(0)),
5598                                 getValue(I.getArgOperand(1)));
5599       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5600                                 getValue(I.getArgOperand(0)).getValueType(),
5601                                 Mul,
5602                                 getValue(I.getArgOperand(2)));
5603       setValue(&I, Add);
5604     }
5605     return nullptr;
5606   }
5607   case Intrinsic::convert_to_fp16:
5608     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5609                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5610                                          getValue(I.getArgOperand(0)),
5611                                          DAG.getTargetConstant(0, sdl,
5612                                                                MVT::i32))));
5613     return nullptr;
5614   case Intrinsic::convert_from_fp16:
5615     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5616                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5617                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5618                                          getValue(I.getArgOperand(0)))));
5619     return nullptr;
5620   case Intrinsic::pcmarker: {
5621     SDValue Tmp = getValue(I.getArgOperand(0));
5622     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5623     return nullptr;
5624   }
5625   case Intrinsic::readcyclecounter: {
5626     SDValue Op = getRoot();
5627     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5628                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5629     setValue(&I, Res);
5630     DAG.setRoot(Res.getValue(1));
5631     return nullptr;
5632   }
5633   case Intrinsic::bitreverse:
5634     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5635                              getValue(I.getArgOperand(0)).getValueType(),
5636                              getValue(I.getArgOperand(0))));
5637     return nullptr;
5638   case Intrinsic::bswap:
5639     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5640                              getValue(I.getArgOperand(0)).getValueType(),
5641                              getValue(I.getArgOperand(0))));
5642     return nullptr;
5643   case Intrinsic::cttz: {
5644     SDValue Arg = getValue(I.getArgOperand(0));
5645     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5646     EVT Ty = Arg.getValueType();
5647     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5648                              sdl, Ty, Arg));
5649     return nullptr;
5650   }
5651   case Intrinsic::ctlz: {
5652     SDValue Arg = getValue(I.getArgOperand(0));
5653     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5654     EVT Ty = Arg.getValueType();
5655     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5656                              sdl, Ty, Arg));
5657     return nullptr;
5658   }
5659   case Intrinsic::ctpop: {
5660     SDValue Arg = getValue(I.getArgOperand(0));
5661     EVT Ty = Arg.getValueType();
5662     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5663     return nullptr;
5664   }
5665   case Intrinsic::stacksave: {
5666     SDValue Op = getRoot();
5667     Res = DAG.getNode(
5668         ISD::STACKSAVE, sdl,
5669         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5670     setValue(&I, Res);
5671     DAG.setRoot(Res.getValue(1));
5672     return nullptr;
5673   }
5674   case Intrinsic::stackrestore:
5675     Res = getValue(I.getArgOperand(0));
5676     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5677     return nullptr;
5678   case Intrinsic::get_dynamic_area_offset: {
5679     SDValue Op = getRoot();
5680     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5681     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5682     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5683     // target.
5684     if (PtrTy != ResTy)
5685       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5686                          " intrinsic!");
5687     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5688                       Op);
5689     DAG.setRoot(Op);
5690     setValue(&I, Res);
5691     return nullptr;
5692   }
5693   case Intrinsic::stackguard: {
5694     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5695     MachineFunction &MF = DAG.getMachineFunction();
5696     const Module &M = *MF.getFunction().getParent();
5697     SDValue Chain = getRoot();
5698     if (TLI.useLoadStackGuardNode()) {
5699       Res = getLoadStackGuard(DAG, sdl, Chain);
5700     } else {
5701       const Value *Global = TLI.getSDagStackGuard(M);
5702       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5703       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5704                         MachinePointerInfo(Global, 0), Align,
5705                         MachineMemOperand::MOVolatile);
5706     }
5707     if (TLI.useStackGuardXorFP())
5708       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5709     DAG.setRoot(Chain);
5710     setValue(&I, Res);
5711     return nullptr;
5712   }
5713   case Intrinsic::stackprotector: {
5714     // Emit code into the DAG to store the stack guard onto the stack.
5715     MachineFunction &MF = DAG.getMachineFunction();
5716     MachineFrameInfo &MFI = MF.getFrameInfo();
5717     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5718     SDValue Src, Chain = getRoot();
5719 
5720     if (TLI.useLoadStackGuardNode())
5721       Src = getLoadStackGuard(DAG, sdl, Chain);
5722     else
5723       Src = getValue(I.getArgOperand(0));   // The guard's value.
5724 
5725     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5726 
5727     int FI = FuncInfo.StaticAllocaMap[Slot];
5728     MFI.setStackProtectorIndex(FI);
5729 
5730     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5731 
5732     // Store the stack protector onto the stack.
5733     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5734                                                  DAG.getMachineFunction(), FI),
5735                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5736     setValue(&I, Res);
5737     DAG.setRoot(Res);
5738     return nullptr;
5739   }
5740   case Intrinsic::objectsize: {
5741     // If we don't know by now, we're never going to know.
5742     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5743 
5744     assert(CI && "Non-constant type in __builtin_object_size?");
5745 
5746     SDValue Arg = getValue(I.getCalledValue());
5747     EVT Ty = Arg.getValueType();
5748 
5749     if (CI->isZero())
5750       Res = DAG.getConstant(-1ULL, sdl, Ty);
5751     else
5752       Res = DAG.getConstant(0, sdl, Ty);
5753 
5754     setValue(&I, Res);
5755     return nullptr;
5756   }
5757   case Intrinsic::annotation:
5758   case Intrinsic::ptr_annotation:
5759   case Intrinsic::launder_invariant_group:
5760     // Drop the intrinsic, but forward the value
5761     setValue(&I, getValue(I.getOperand(0)));
5762     return nullptr;
5763   case Intrinsic::assume:
5764   case Intrinsic::var_annotation:
5765   case Intrinsic::sideeffect:
5766     // Discard annotate attributes, assumptions, and artificial side-effects.
5767     return nullptr;
5768 
5769   case Intrinsic::codeview_annotation: {
5770     // Emit a label associated with this metadata.
5771     MachineFunction &MF = DAG.getMachineFunction();
5772     MCSymbol *Label =
5773         MF.getMMI().getContext().createTempSymbol("annotation", true);
5774     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5775     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5776     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5777     DAG.setRoot(Res);
5778     return nullptr;
5779   }
5780 
5781   case Intrinsic::init_trampoline: {
5782     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5783 
5784     SDValue Ops[6];
5785     Ops[0] = getRoot();
5786     Ops[1] = getValue(I.getArgOperand(0));
5787     Ops[2] = getValue(I.getArgOperand(1));
5788     Ops[3] = getValue(I.getArgOperand(2));
5789     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5790     Ops[5] = DAG.getSrcValue(F);
5791 
5792     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5793 
5794     DAG.setRoot(Res);
5795     return nullptr;
5796   }
5797   case Intrinsic::adjust_trampoline:
5798     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5799                              TLI.getPointerTy(DAG.getDataLayout()),
5800                              getValue(I.getArgOperand(0))));
5801     return nullptr;
5802   case Intrinsic::gcroot: {
5803     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5804            "only valid in functions with gc specified, enforced by Verifier");
5805     assert(GFI && "implied by previous");
5806     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5807     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5808 
5809     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5810     GFI->addStackRoot(FI->getIndex(), TypeMap);
5811     return nullptr;
5812   }
5813   case Intrinsic::gcread:
5814   case Intrinsic::gcwrite:
5815     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5816   case Intrinsic::flt_rounds:
5817     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5818     return nullptr;
5819 
5820   case Intrinsic::expect:
5821     // Just replace __builtin_expect(exp, c) with EXP.
5822     setValue(&I, getValue(I.getArgOperand(0)));
5823     return nullptr;
5824 
5825   case Intrinsic::debugtrap:
5826   case Intrinsic::trap: {
5827     StringRef TrapFuncName =
5828         I.getAttributes()
5829             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5830             .getValueAsString();
5831     if (TrapFuncName.empty()) {
5832       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5833         ISD::TRAP : ISD::DEBUGTRAP;
5834       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5835       return nullptr;
5836     }
5837     TargetLowering::ArgListTy Args;
5838 
5839     TargetLowering::CallLoweringInfo CLI(DAG);
5840     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5841         CallingConv::C, I.getType(),
5842         DAG.getExternalSymbol(TrapFuncName.data(),
5843                               TLI.getPointerTy(DAG.getDataLayout())),
5844         std::move(Args));
5845 
5846     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5847     DAG.setRoot(Result.second);
5848     return nullptr;
5849   }
5850 
5851   case Intrinsic::uadd_with_overflow:
5852   case Intrinsic::sadd_with_overflow:
5853   case Intrinsic::usub_with_overflow:
5854   case Intrinsic::ssub_with_overflow:
5855   case Intrinsic::umul_with_overflow:
5856   case Intrinsic::smul_with_overflow: {
5857     ISD::NodeType Op;
5858     switch (Intrinsic) {
5859     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5860     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5861     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5862     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5863     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5864     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5865     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5866     }
5867     SDValue Op1 = getValue(I.getArgOperand(0));
5868     SDValue Op2 = getValue(I.getArgOperand(1));
5869 
5870     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5871     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5872     return nullptr;
5873   }
5874   case Intrinsic::prefetch: {
5875     SDValue Ops[5];
5876     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5877     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
5878     Ops[0] = DAG.getRoot();
5879     Ops[1] = getValue(I.getArgOperand(0));
5880     Ops[2] = getValue(I.getArgOperand(1));
5881     Ops[3] = getValue(I.getArgOperand(2));
5882     Ops[4] = getValue(I.getArgOperand(3));
5883     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5884                                              DAG.getVTList(MVT::Other), Ops,
5885                                              EVT::getIntegerVT(*Context, 8),
5886                                              MachinePointerInfo(I.getArgOperand(0)),
5887                                              0, /* align */
5888                                              Flags);
5889 
5890     // Chain the prefetch in parallell with any pending loads, to stay out of
5891     // the way of later optimizations.
5892     PendingLoads.push_back(Result);
5893     Result = getRoot();
5894     DAG.setRoot(Result);
5895     return nullptr;
5896   }
5897   case Intrinsic::lifetime_start:
5898   case Intrinsic::lifetime_end: {
5899     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5900     // Stack coloring is not enabled in O0, discard region information.
5901     if (TM.getOptLevel() == CodeGenOpt::None)
5902       return nullptr;
5903 
5904     SmallVector<Value *, 4> Allocas;
5905     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5906 
5907     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5908            E = Allocas.end(); Object != E; ++Object) {
5909       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5910 
5911       // Could not find an Alloca.
5912       if (!LifetimeObject)
5913         continue;
5914 
5915       // First check that the Alloca is static, otherwise it won't have a
5916       // valid frame index.
5917       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5918       if (SI == FuncInfo.StaticAllocaMap.end())
5919         return nullptr;
5920 
5921       int FI = SI->second;
5922 
5923       SDValue Ops[2];
5924       Ops[0] = getRoot();
5925       Ops[1] =
5926           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
5927       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5928 
5929       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5930       DAG.setRoot(Res);
5931     }
5932     return nullptr;
5933   }
5934   case Intrinsic::invariant_start:
5935     // Discard region information.
5936     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5937     return nullptr;
5938   case Intrinsic::invariant_end:
5939     // Discard region information.
5940     return nullptr;
5941   case Intrinsic::clear_cache:
5942     return TLI.getClearCacheBuiltinName();
5943   case Intrinsic::donothing:
5944     // ignore
5945     return nullptr;
5946   case Intrinsic::experimental_stackmap:
5947     visitStackmap(I);
5948     return nullptr;
5949   case Intrinsic::experimental_patchpoint_void:
5950   case Intrinsic::experimental_patchpoint_i64:
5951     visitPatchpoint(&I);
5952     return nullptr;
5953   case Intrinsic::experimental_gc_statepoint:
5954     LowerStatepoint(ImmutableStatepoint(&I));
5955     return nullptr;
5956   case Intrinsic::experimental_gc_result:
5957     visitGCResult(cast<GCResultInst>(I));
5958     return nullptr;
5959   case Intrinsic::experimental_gc_relocate:
5960     visitGCRelocate(cast<GCRelocateInst>(I));
5961     return nullptr;
5962   case Intrinsic::instrprof_increment:
5963     llvm_unreachable("instrprof failed to lower an increment");
5964   case Intrinsic::instrprof_value_profile:
5965     llvm_unreachable("instrprof failed to lower a value profiling call");
5966   case Intrinsic::localescape: {
5967     MachineFunction &MF = DAG.getMachineFunction();
5968     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5969 
5970     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5971     // is the same on all targets.
5972     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5973       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5974       if (isa<ConstantPointerNull>(Arg))
5975         continue; // Skip null pointers. They represent a hole in index space.
5976       AllocaInst *Slot = cast<AllocaInst>(Arg);
5977       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5978              "can only escape static allocas");
5979       int FI = FuncInfo.StaticAllocaMap[Slot];
5980       MCSymbol *FrameAllocSym =
5981           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5982               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
5983       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5984               TII->get(TargetOpcode::LOCAL_ESCAPE))
5985           .addSym(FrameAllocSym)
5986           .addFrameIndex(FI);
5987     }
5988 
5989     return nullptr;
5990   }
5991 
5992   case Intrinsic::localrecover: {
5993     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5994     MachineFunction &MF = DAG.getMachineFunction();
5995     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5996 
5997     // Get the symbol that defines the frame offset.
5998     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5999     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6000     unsigned IdxVal =
6001         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6002     MCSymbol *FrameAllocSym =
6003         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6004             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6005 
6006     // Create a MCSymbol for the label to avoid any target lowering
6007     // that would make this PC relative.
6008     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6009     SDValue OffsetVal =
6010         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6011 
6012     // Add the offset to the FP.
6013     Value *FP = I.getArgOperand(1);
6014     SDValue FPVal = getValue(FP);
6015     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6016     setValue(&I, Add);
6017 
6018     return nullptr;
6019   }
6020 
6021   case Intrinsic::eh_exceptionpointer:
6022   case Intrinsic::eh_exceptioncode: {
6023     // Get the exception pointer vreg, copy from it, and resize it to fit.
6024     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6025     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6026     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6027     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6028     SDValue N =
6029         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6030     if (Intrinsic == Intrinsic::eh_exceptioncode)
6031       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6032     setValue(&I, N);
6033     return nullptr;
6034   }
6035   case Intrinsic::xray_customevent: {
6036     // Here we want to make sure that the intrinsic behaves as if it has a
6037     // specific calling convention, and only for x86_64.
6038     // FIXME: Support other platforms later.
6039     const auto &Triple = DAG.getTarget().getTargetTriple();
6040     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6041       return nullptr;
6042 
6043     SDLoc DL = getCurSDLoc();
6044     SmallVector<SDValue, 8> Ops;
6045 
6046     // We want to say that we always want the arguments in registers.
6047     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6048     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6049     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6050     SDValue Chain = getRoot();
6051     Ops.push_back(LogEntryVal);
6052     Ops.push_back(StrSizeVal);
6053     Ops.push_back(Chain);
6054 
6055     // We need to enforce the calling convention for the callsite, so that
6056     // argument ordering is enforced correctly, and that register allocation can
6057     // see that some registers may be assumed clobbered and have to preserve
6058     // them across calls to the intrinsic.
6059     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6060                                            DL, NodeTys, Ops);
6061     SDValue patchableNode = SDValue(MN, 0);
6062     DAG.setRoot(patchableNode);
6063     setValue(&I, patchableNode);
6064     return nullptr;
6065   }
6066   case Intrinsic::xray_typedevent: {
6067     // Here we want to make sure that the intrinsic behaves as if it has a
6068     // specific calling convention, and only for x86_64.
6069     // FIXME: Support other platforms later.
6070     const auto &Triple = DAG.getTarget().getTargetTriple();
6071     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6072       return nullptr;
6073 
6074     SDLoc DL = getCurSDLoc();
6075     SmallVector<SDValue, 8> Ops;
6076 
6077     // We want to say that we always want the arguments in registers.
6078     // It's unclear to me how manipulating the selection DAG here forces callers
6079     // to provide arguments in registers instead of on the stack.
6080     SDValue LogTypeId = getValue(I.getArgOperand(0));
6081     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6082     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6083     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6084     SDValue Chain = getRoot();
6085     Ops.push_back(LogTypeId);
6086     Ops.push_back(LogEntryVal);
6087     Ops.push_back(StrSizeVal);
6088     Ops.push_back(Chain);
6089 
6090     // We need to enforce the calling convention for the callsite, so that
6091     // argument ordering is enforced correctly, and that register allocation can
6092     // see that some registers may be assumed clobbered and have to preserve
6093     // them across calls to the intrinsic.
6094     MachineSDNode *MN = DAG.getMachineNode(
6095         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6096     SDValue patchableNode = SDValue(MN, 0);
6097     DAG.setRoot(patchableNode);
6098     setValue(&I, patchableNode);
6099     return nullptr;
6100   }
6101   case Intrinsic::experimental_deoptimize:
6102     LowerDeoptimizeCall(&I);
6103     return nullptr;
6104 
6105   case Intrinsic::experimental_vector_reduce_fadd:
6106   case Intrinsic::experimental_vector_reduce_fmul:
6107   case Intrinsic::experimental_vector_reduce_add:
6108   case Intrinsic::experimental_vector_reduce_mul:
6109   case Intrinsic::experimental_vector_reduce_and:
6110   case Intrinsic::experimental_vector_reduce_or:
6111   case Intrinsic::experimental_vector_reduce_xor:
6112   case Intrinsic::experimental_vector_reduce_smax:
6113   case Intrinsic::experimental_vector_reduce_smin:
6114   case Intrinsic::experimental_vector_reduce_umax:
6115   case Intrinsic::experimental_vector_reduce_umin:
6116   case Intrinsic::experimental_vector_reduce_fmax:
6117   case Intrinsic::experimental_vector_reduce_fmin:
6118     visitVectorReduce(I, Intrinsic);
6119     return nullptr;
6120 
6121   case Intrinsic::icall_branch_funnel: {
6122     SmallVector<SDValue, 16> Ops;
6123     Ops.push_back(DAG.getRoot());
6124     Ops.push_back(getValue(I.getArgOperand(0)));
6125 
6126     int64_t Offset;
6127     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6128         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6129     if (!Base)
6130       report_fatal_error(
6131           "llvm.icall.branch.funnel operand must be a GlobalValue");
6132     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6133 
6134     struct BranchFunnelTarget {
6135       int64_t Offset;
6136       SDValue Target;
6137     };
6138     SmallVector<BranchFunnelTarget, 8> Targets;
6139 
6140     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6141       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6142           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6143       if (ElemBase != Base)
6144         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6145                            "to the same GlobalValue");
6146 
6147       SDValue Val = getValue(I.getArgOperand(Op + 1));
6148       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6149       if (!GA)
6150         report_fatal_error(
6151             "llvm.icall.branch.funnel operand must be a GlobalValue");
6152       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6153                                      GA->getGlobal(), getCurSDLoc(),
6154                                      Val.getValueType(), GA->getOffset())});
6155     }
6156     llvm::sort(Targets.begin(), Targets.end(),
6157                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6158                  return T1.Offset < T2.Offset;
6159                });
6160 
6161     for (auto &T : Targets) {
6162       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6163       Ops.push_back(T.Target);
6164     }
6165 
6166     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6167                                  getCurSDLoc(), MVT::Other, Ops),
6168               0);
6169     DAG.setRoot(N);
6170     setValue(&I, N);
6171     HasTailCall = true;
6172     return nullptr;
6173   }
6174   }
6175 }
6176 
6177 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6178     const ConstrainedFPIntrinsic &FPI) {
6179   SDLoc sdl = getCurSDLoc();
6180   unsigned Opcode;
6181   switch (FPI.getIntrinsicID()) {
6182   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6183   case Intrinsic::experimental_constrained_fadd:
6184     Opcode = ISD::STRICT_FADD;
6185     break;
6186   case Intrinsic::experimental_constrained_fsub:
6187     Opcode = ISD::STRICT_FSUB;
6188     break;
6189   case Intrinsic::experimental_constrained_fmul:
6190     Opcode = ISD::STRICT_FMUL;
6191     break;
6192   case Intrinsic::experimental_constrained_fdiv:
6193     Opcode = ISD::STRICT_FDIV;
6194     break;
6195   case Intrinsic::experimental_constrained_frem:
6196     Opcode = ISD::STRICT_FREM;
6197     break;
6198   case Intrinsic::experimental_constrained_fma:
6199     Opcode = ISD::STRICT_FMA;
6200     break;
6201   case Intrinsic::experimental_constrained_sqrt:
6202     Opcode = ISD::STRICT_FSQRT;
6203     break;
6204   case Intrinsic::experimental_constrained_pow:
6205     Opcode = ISD::STRICT_FPOW;
6206     break;
6207   case Intrinsic::experimental_constrained_powi:
6208     Opcode = ISD::STRICT_FPOWI;
6209     break;
6210   case Intrinsic::experimental_constrained_sin:
6211     Opcode = ISD::STRICT_FSIN;
6212     break;
6213   case Intrinsic::experimental_constrained_cos:
6214     Opcode = ISD::STRICT_FCOS;
6215     break;
6216   case Intrinsic::experimental_constrained_exp:
6217     Opcode = ISD::STRICT_FEXP;
6218     break;
6219   case Intrinsic::experimental_constrained_exp2:
6220     Opcode = ISD::STRICT_FEXP2;
6221     break;
6222   case Intrinsic::experimental_constrained_log:
6223     Opcode = ISD::STRICT_FLOG;
6224     break;
6225   case Intrinsic::experimental_constrained_log10:
6226     Opcode = ISD::STRICT_FLOG10;
6227     break;
6228   case Intrinsic::experimental_constrained_log2:
6229     Opcode = ISD::STRICT_FLOG2;
6230     break;
6231   case Intrinsic::experimental_constrained_rint:
6232     Opcode = ISD::STRICT_FRINT;
6233     break;
6234   case Intrinsic::experimental_constrained_nearbyint:
6235     Opcode = ISD::STRICT_FNEARBYINT;
6236     break;
6237   }
6238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6239   SDValue Chain = getRoot();
6240   SmallVector<EVT, 4> ValueVTs;
6241   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6242   ValueVTs.push_back(MVT::Other); // Out chain
6243 
6244   SDVTList VTs = DAG.getVTList(ValueVTs);
6245   SDValue Result;
6246   if (FPI.isUnaryOp())
6247     Result = DAG.getNode(Opcode, sdl, VTs,
6248                          { Chain, getValue(FPI.getArgOperand(0)) });
6249   else if (FPI.isTernaryOp())
6250     Result = DAG.getNode(Opcode, sdl, VTs,
6251                          { Chain, getValue(FPI.getArgOperand(0)),
6252                                   getValue(FPI.getArgOperand(1)),
6253                                   getValue(FPI.getArgOperand(2)) });
6254   else
6255     Result = DAG.getNode(Opcode, sdl, VTs,
6256                          { Chain, getValue(FPI.getArgOperand(0)),
6257                            getValue(FPI.getArgOperand(1))  });
6258 
6259   assert(Result.getNode()->getNumValues() == 2);
6260   SDValue OutChain = Result.getValue(1);
6261   DAG.setRoot(OutChain);
6262   SDValue FPResult = Result.getValue(0);
6263   setValue(&FPI, FPResult);
6264 }
6265 
6266 std::pair<SDValue, SDValue>
6267 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6268                                     const BasicBlock *EHPadBB) {
6269   MachineFunction &MF = DAG.getMachineFunction();
6270   MachineModuleInfo &MMI = MF.getMMI();
6271   MCSymbol *BeginLabel = nullptr;
6272 
6273   if (EHPadBB) {
6274     // Insert a label before the invoke call to mark the try range.  This can be
6275     // used to detect deletion of the invoke via the MachineModuleInfo.
6276     BeginLabel = MMI.getContext().createTempSymbol();
6277 
6278     // For SjLj, keep track of which landing pads go with which invokes
6279     // so as to maintain the ordering of pads in the LSDA.
6280     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6281     if (CallSiteIndex) {
6282       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6283       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6284 
6285       // Now that the call site is handled, stop tracking it.
6286       MMI.setCurrentCallSite(0);
6287     }
6288 
6289     // Both PendingLoads and PendingExports must be flushed here;
6290     // this call might not return.
6291     (void)getRoot();
6292     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6293 
6294     CLI.setChain(getRoot());
6295   }
6296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6297   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6298 
6299   assert((CLI.IsTailCall || Result.second.getNode()) &&
6300          "Non-null chain expected with non-tail call!");
6301   assert((Result.second.getNode() || !Result.first.getNode()) &&
6302          "Null value expected with tail call!");
6303 
6304   if (!Result.second.getNode()) {
6305     // As a special case, a null chain means that a tail call has been emitted
6306     // and the DAG root is already updated.
6307     HasTailCall = true;
6308 
6309     // Since there's no actual continuation from this block, nothing can be
6310     // relying on us setting vregs for them.
6311     PendingExports.clear();
6312   } else {
6313     DAG.setRoot(Result.second);
6314   }
6315 
6316   if (EHPadBB) {
6317     // Insert a label at the end of the invoke call to mark the try range.  This
6318     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6319     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6320     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6321 
6322     // Inform MachineModuleInfo of range.
6323     if (MF.hasEHFunclets()) {
6324       assert(CLI.CS);
6325       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6326       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6327                                 BeginLabel, EndLabel);
6328     } else {
6329       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6330     }
6331   }
6332 
6333   return Result;
6334 }
6335 
6336 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6337                                       bool isTailCall,
6338                                       const BasicBlock *EHPadBB) {
6339   auto &DL = DAG.getDataLayout();
6340   FunctionType *FTy = CS.getFunctionType();
6341   Type *RetTy = CS.getType();
6342 
6343   TargetLowering::ArgListTy Args;
6344   Args.reserve(CS.arg_size());
6345 
6346   const Value *SwiftErrorVal = nullptr;
6347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6348 
6349   // We can't tail call inside a function with a swifterror argument. Lowering
6350   // does not support this yet. It would have to move into the swifterror
6351   // register before the call.
6352   auto *Caller = CS.getInstruction()->getParent()->getParent();
6353   if (TLI.supportSwiftError() &&
6354       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6355     isTailCall = false;
6356 
6357   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6358        i != e; ++i) {
6359     TargetLowering::ArgListEntry Entry;
6360     const Value *V = *i;
6361 
6362     // Skip empty types
6363     if (V->getType()->isEmptyTy())
6364       continue;
6365 
6366     SDValue ArgNode = getValue(V);
6367     Entry.Node = ArgNode; Entry.Ty = V->getType();
6368 
6369     Entry.setAttributes(&CS, i - CS.arg_begin());
6370 
6371     // Use swifterror virtual register as input to the call.
6372     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6373       SwiftErrorVal = V;
6374       // We find the virtual register for the actual swifterror argument.
6375       // Instead of using the Value, we use the virtual register instead.
6376       Entry.Node = DAG.getRegister(FuncInfo
6377                                        .getOrCreateSwiftErrorVRegUseAt(
6378                                            CS.getInstruction(), FuncInfo.MBB, V)
6379                                        .first,
6380                                    EVT(TLI.getPointerTy(DL)));
6381     }
6382 
6383     Args.push_back(Entry);
6384 
6385     // If we have an explicit sret argument that is an Instruction, (i.e., it
6386     // might point to function-local memory), we can't meaningfully tail-call.
6387     if (Entry.IsSRet && isa<Instruction>(V))
6388       isTailCall = false;
6389   }
6390 
6391   // Check if target-independent constraints permit a tail call here.
6392   // Target-dependent constraints are checked within TLI->LowerCallTo.
6393   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6394     isTailCall = false;
6395 
6396   // Disable tail calls if there is an swifterror argument. Targets have not
6397   // been updated to support tail calls.
6398   if (TLI.supportSwiftError() && SwiftErrorVal)
6399     isTailCall = false;
6400 
6401   TargetLowering::CallLoweringInfo CLI(DAG);
6402   CLI.setDebugLoc(getCurSDLoc())
6403       .setChain(getRoot())
6404       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6405       .setTailCall(isTailCall)
6406       .setConvergent(CS.isConvergent());
6407   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6408 
6409   if (Result.first.getNode()) {
6410     const Instruction *Inst = CS.getInstruction();
6411     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6412     setValue(Inst, Result.first);
6413   }
6414 
6415   // The last element of CLI.InVals has the SDValue for swifterror return.
6416   // Here we copy it to a virtual register and update SwiftErrorMap for
6417   // book-keeping.
6418   if (SwiftErrorVal && TLI.supportSwiftError()) {
6419     // Get the last element of InVals.
6420     SDValue Src = CLI.InVals.back();
6421     unsigned VReg; bool CreatedVReg;
6422     std::tie(VReg, CreatedVReg) =
6423         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6424     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6425     // We update the virtual register for the actual swifterror argument.
6426     if (CreatedVReg)
6427       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6428     DAG.setRoot(CopyNode);
6429   }
6430 }
6431 
6432 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6433                              SelectionDAGBuilder &Builder) {
6434   // Check to see if this load can be trivially constant folded, e.g. if the
6435   // input is from a string literal.
6436   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6437     // Cast pointer to the type we really want to load.
6438     Type *LoadTy =
6439         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6440     if (LoadVT.isVector())
6441       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6442 
6443     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6444                                          PointerType::getUnqual(LoadTy));
6445 
6446     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6447             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6448       return Builder.getValue(LoadCst);
6449   }
6450 
6451   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6452   // still constant memory, the input chain can be the entry node.
6453   SDValue Root;
6454   bool ConstantMemory = false;
6455 
6456   // Do not serialize (non-volatile) loads of constant memory with anything.
6457   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6458     Root = Builder.DAG.getEntryNode();
6459     ConstantMemory = true;
6460   } else {
6461     // Do not serialize non-volatile loads against each other.
6462     Root = Builder.DAG.getRoot();
6463   }
6464 
6465   SDValue Ptr = Builder.getValue(PtrVal);
6466   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6467                                         Ptr, MachinePointerInfo(PtrVal),
6468                                         /* Alignment = */ 1);
6469 
6470   if (!ConstantMemory)
6471     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6472   return LoadVal;
6473 }
6474 
6475 /// Record the value for an instruction that produces an integer result,
6476 /// converting the type where necessary.
6477 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6478                                                   SDValue Value,
6479                                                   bool IsSigned) {
6480   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6481                                                     I.getType(), true);
6482   if (IsSigned)
6483     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6484   else
6485     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6486   setValue(&I, Value);
6487 }
6488 
6489 /// See if we can lower a memcmp call into an optimized form. If so, return
6490 /// true and lower it. Otherwise return false, and it will be lowered like a
6491 /// normal call.
6492 /// The caller already checked that \p I calls the appropriate LibFunc with a
6493 /// correct prototype.
6494 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6495   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6496   const Value *Size = I.getArgOperand(2);
6497   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6498   if (CSize && CSize->getZExtValue() == 0) {
6499     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6500                                                           I.getType(), true);
6501     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6502     return true;
6503   }
6504 
6505   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6506   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6507       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6508       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6509   if (Res.first.getNode()) {
6510     processIntegerCallValue(I, Res.first, true);
6511     PendingLoads.push_back(Res.second);
6512     return true;
6513   }
6514 
6515   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6516   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6517   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6518     return false;
6519 
6520   // If the target has a fast compare for the given size, it will return a
6521   // preferred load type for that size. Require that the load VT is legal and
6522   // that the target supports unaligned loads of that type. Otherwise, return
6523   // INVALID.
6524   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6525     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6526     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6527     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6528       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6529       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6530       // TODO: Check alignment of src and dest ptrs.
6531       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6532       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6533       if (!TLI.isTypeLegal(LVT) ||
6534           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6535           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6536         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6537     }
6538 
6539     return LVT;
6540   };
6541 
6542   // This turns into unaligned loads. We only do this if the target natively
6543   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6544   // we'll only produce a small number of byte loads.
6545   MVT LoadVT;
6546   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6547   switch (NumBitsToCompare) {
6548   default:
6549     return false;
6550   case 16:
6551     LoadVT = MVT::i16;
6552     break;
6553   case 32:
6554     LoadVT = MVT::i32;
6555     break;
6556   case 64:
6557   case 128:
6558   case 256:
6559     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6560     break;
6561   }
6562 
6563   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6564     return false;
6565 
6566   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6567   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6568 
6569   // Bitcast to a wide integer type if the loads are vectors.
6570   if (LoadVT.isVector()) {
6571     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6572     LoadL = DAG.getBitcast(CmpVT, LoadL);
6573     LoadR = DAG.getBitcast(CmpVT, LoadR);
6574   }
6575 
6576   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6577   processIntegerCallValue(I, Cmp, false);
6578   return true;
6579 }
6580 
6581 /// See if we can lower a memchr call into an optimized form. If so, return
6582 /// true and lower it. Otherwise return false, and it will be lowered like a
6583 /// normal call.
6584 /// The caller already checked that \p I calls the appropriate LibFunc with a
6585 /// correct prototype.
6586 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6587   const Value *Src = I.getArgOperand(0);
6588   const Value *Char = I.getArgOperand(1);
6589   const Value *Length = I.getArgOperand(2);
6590 
6591   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6592   std::pair<SDValue, SDValue> Res =
6593     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6594                                 getValue(Src), getValue(Char), getValue(Length),
6595                                 MachinePointerInfo(Src));
6596   if (Res.first.getNode()) {
6597     setValue(&I, Res.first);
6598     PendingLoads.push_back(Res.second);
6599     return true;
6600   }
6601 
6602   return false;
6603 }
6604 
6605 /// See if we can lower a mempcpy call into an optimized form. If so, return
6606 /// true and lower it. Otherwise return false, and it will be lowered like a
6607 /// normal call.
6608 /// The caller already checked that \p I calls the appropriate LibFunc with a
6609 /// correct prototype.
6610 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6611   SDValue Dst = getValue(I.getArgOperand(0));
6612   SDValue Src = getValue(I.getArgOperand(1));
6613   SDValue Size = getValue(I.getArgOperand(2));
6614 
6615   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6616   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6617   unsigned Align = std::min(DstAlign, SrcAlign);
6618   if (Align == 0) // Alignment of one or both could not be inferred.
6619     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6620 
6621   bool isVol = false;
6622   SDLoc sdl = getCurSDLoc();
6623 
6624   // In the mempcpy context we need to pass in a false value for isTailCall
6625   // because the return pointer needs to be adjusted by the size of
6626   // the copied memory.
6627   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6628                              false, /*isTailCall=*/false,
6629                              MachinePointerInfo(I.getArgOperand(0)),
6630                              MachinePointerInfo(I.getArgOperand(1)));
6631   assert(MC.getNode() != nullptr &&
6632          "** memcpy should not be lowered as TailCall in mempcpy context **");
6633   DAG.setRoot(MC);
6634 
6635   // Check if Size needs to be truncated or extended.
6636   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6637 
6638   // Adjust return pointer to point just past the last dst byte.
6639   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6640                                     Dst, Size);
6641   setValue(&I, DstPlusSize);
6642   return true;
6643 }
6644 
6645 /// See if we can lower a strcpy call into an optimized form.  If so, return
6646 /// true and lower it, otherwise return false and it will be lowered like a
6647 /// normal call.
6648 /// The caller already checked that \p I calls the appropriate LibFunc with a
6649 /// correct prototype.
6650 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6651   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6652 
6653   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6654   std::pair<SDValue, SDValue> Res =
6655     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6656                                 getValue(Arg0), getValue(Arg1),
6657                                 MachinePointerInfo(Arg0),
6658                                 MachinePointerInfo(Arg1), isStpcpy);
6659   if (Res.first.getNode()) {
6660     setValue(&I, Res.first);
6661     DAG.setRoot(Res.second);
6662     return true;
6663   }
6664 
6665   return false;
6666 }
6667 
6668 /// See if we can lower a strcmp call into an optimized form.  If so, return
6669 /// true and lower it, otherwise return false and it will be lowered like a
6670 /// normal call.
6671 /// The caller already checked that \p I calls the appropriate LibFunc with a
6672 /// correct prototype.
6673 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6674   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6675 
6676   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6677   std::pair<SDValue, SDValue> Res =
6678     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6679                                 getValue(Arg0), getValue(Arg1),
6680                                 MachinePointerInfo(Arg0),
6681                                 MachinePointerInfo(Arg1));
6682   if (Res.first.getNode()) {
6683     processIntegerCallValue(I, Res.first, true);
6684     PendingLoads.push_back(Res.second);
6685     return true;
6686   }
6687 
6688   return false;
6689 }
6690 
6691 /// See if we can lower a strlen call into an optimized form.  If so, return
6692 /// true and lower it, otherwise return false and it will be lowered like a
6693 /// normal call.
6694 /// The caller already checked that \p I calls the appropriate LibFunc with a
6695 /// correct prototype.
6696 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6697   const Value *Arg0 = I.getArgOperand(0);
6698 
6699   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6700   std::pair<SDValue, SDValue> Res =
6701     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6702                                 getValue(Arg0), MachinePointerInfo(Arg0));
6703   if (Res.first.getNode()) {
6704     processIntegerCallValue(I, Res.first, false);
6705     PendingLoads.push_back(Res.second);
6706     return true;
6707   }
6708 
6709   return false;
6710 }
6711 
6712 /// See if we can lower a strnlen call into an optimized form.  If so, return
6713 /// true and lower it, otherwise return false and it will be lowered like a
6714 /// normal call.
6715 /// The caller already checked that \p I calls the appropriate LibFunc with a
6716 /// correct prototype.
6717 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6718   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6719 
6720   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6721   std::pair<SDValue, SDValue> Res =
6722     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6723                                  getValue(Arg0), getValue(Arg1),
6724                                  MachinePointerInfo(Arg0));
6725   if (Res.first.getNode()) {
6726     processIntegerCallValue(I, Res.first, false);
6727     PendingLoads.push_back(Res.second);
6728     return true;
6729   }
6730 
6731   return false;
6732 }
6733 
6734 /// See if we can lower a unary floating-point operation into an SDNode with
6735 /// the specified Opcode.  If so, return true and lower it, otherwise return
6736 /// false and it will be lowered like a normal call.
6737 /// The caller already checked that \p I calls the appropriate LibFunc with a
6738 /// correct prototype.
6739 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6740                                               unsigned Opcode) {
6741   // We already checked this call's prototype; verify it doesn't modify errno.
6742   if (!I.onlyReadsMemory())
6743     return false;
6744 
6745   SDValue Tmp = getValue(I.getArgOperand(0));
6746   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6747   return true;
6748 }
6749 
6750 /// See if we can lower a binary floating-point operation into an SDNode with
6751 /// the specified Opcode. If so, return true and lower it. Otherwise return
6752 /// false, and it will be lowered like a normal call.
6753 /// The caller already checked that \p I calls the appropriate LibFunc with a
6754 /// correct prototype.
6755 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6756                                                unsigned Opcode) {
6757   // We already checked this call's prototype; verify it doesn't modify errno.
6758   if (!I.onlyReadsMemory())
6759     return false;
6760 
6761   SDValue Tmp0 = getValue(I.getArgOperand(0));
6762   SDValue Tmp1 = getValue(I.getArgOperand(1));
6763   EVT VT = Tmp0.getValueType();
6764   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6765   return true;
6766 }
6767 
6768 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6769   // Handle inline assembly differently.
6770   if (isa<InlineAsm>(I.getCalledValue())) {
6771     visitInlineAsm(&I);
6772     return;
6773   }
6774 
6775   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6776   computeUsesVAFloatArgument(I, MMI);
6777 
6778   const char *RenameFn = nullptr;
6779   if (Function *F = I.getCalledFunction()) {
6780     if (F->isDeclaration()) {
6781       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6782         if (unsigned IID = II->getIntrinsicID(F)) {
6783           RenameFn = visitIntrinsicCall(I, IID);
6784           if (!RenameFn)
6785             return;
6786         }
6787       }
6788       if (Intrinsic::ID IID = F->getIntrinsicID()) {
6789         RenameFn = visitIntrinsicCall(I, IID);
6790         if (!RenameFn)
6791           return;
6792       }
6793     }
6794 
6795     // Check for well-known libc/libm calls.  If the function is internal, it
6796     // can't be a library call.  Don't do the check if marked as nobuiltin for
6797     // some reason or the call site requires strict floating point semantics.
6798     LibFunc Func;
6799     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6800         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6801         LibInfo->hasOptimizedCodeGen(Func)) {
6802       switch (Func) {
6803       default: break;
6804       case LibFunc_copysign:
6805       case LibFunc_copysignf:
6806       case LibFunc_copysignl:
6807         // We already checked this call's prototype; verify it doesn't modify
6808         // errno.
6809         if (I.onlyReadsMemory()) {
6810           SDValue LHS = getValue(I.getArgOperand(0));
6811           SDValue RHS = getValue(I.getArgOperand(1));
6812           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6813                                    LHS.getValueType(), LHS, RHS));
6814           return;
6815         }
6816         break;
6817       case LibFunc_fabs:
6818       case LibFunc_fabsf:
6819       case LibFunc_fabsl:
6820         if (visitUnaryFloatCall(I, ISD::FABS))
6821           return;
6822         break;
6823       case LibFunc_fmin:
6824       case LibFunc_fminf:
6825       case LibFunc_fminl:
6826         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6827           return;
6828         break;
6829       case LibFunc_fmax:
6830       case LibFunc_fmaxf:
6831       case LibFunc_fmaxl:
6832         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6833           return;
6834         break;
6835       case LibFunc_sin:
6836       case LibFunc_sinf:
6837       case LibFunc_sinl:
6838         if (visitUnaryFloatCall(I, ISD::FSIN))
6839           return;
6840         break;
6841       case LibFunc_cos:
6842       case LibFunc_cosf:
6843       case LibFunc_cosl:
6844         if (visitUnaryFloatCall(I, ISD::FCOS))
6845           return;
6846         break;
6847       case LibFunc_sqrt:
6848       case LibFunc_sqrtf:
6849       case LibFunc_sqrtl:
6850       case LibFunc_sqrt_finite:
6851       case LibFunc_sqrtf_finite:
6852       case LibFunc_sqrtl_finite:
6853         if (visitUnaryFloatCall(I, ISD::FSQRT))
6854           return;
6855         break;
6856       case LibFunc_floor:
6857       case LibFunc_floorf:
6858       case LibFunc_floorl:
6859         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6860           return;
6861         break;
6862       case LibFunc_nearbyint:
6863       case LibFunc_nearbyintf:
6864       case LibFunc_nearbyintl:
6865         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6866           return;
6867         break;
6868       case LibFunc_ceil:
6869       case LibFunc_ceilf:
6870       case LibFunc_ceill:
6871         if (visitUnaryFloatCall(I, ISD::FCEIL))
6872           return;
6873         break;
6874       case LibFunc_rint:
6875       case LibFunc_rintf:
6876       case LibFunc_rintl:
6877         if (visitUnaryFloatCall(I, ISD::FRINT))
6878           return;
6879         break;
6880       case LibFunc_round:
6881       case LibFunc_roundf:
6882       case LibFunc_roundl:
6883         if (visitUnaryFloatCall(I, ISD::FROUND))
6884           return;
6885         break;
6886       case LibFunc_trunc:
6887       case LibFunc_truncf:
6888       case LibFunc_truncl:
6889         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6890           return;
6891         break;
6892       case LibFunc_log2:
6893       case LibFunc_log2f:
6894       case LibFunc_log2l:
6895         if (visitUnaryFloatCall(I, ISD::FLOG2))
6896           return;
6897         break;
6898       case LibFunc_exp2:
6899       case LibFunc_exp2f:
6900       case LibFunc_exp2l:
6901         if (visitUnaryFloatCall(I, ISD::FEXP2))
6902           return;
6903         break;
6904       case LibFunc_memcmp:
6905         if (visitMemCmpCall(I))
6906           return;
6907         break;
6908       case LibFunc_mempcpy:
6909         if (visitMemPCpyCall(I))
6910           return;
6911         break;
6912       case LibFunc_memchr:
6913         if (visitMemChrCall(I))
6914           return;
6915         break;
6916       case LibFunc_strcpy:
6917         if (visitStrCpyCall(I, false))
6918           return;
6919         break;
6920       case LibFunc_stpcpy:
6921         if (visitStrCpyCall(I, true))
6922           return;
6923         break;
6924       case LibFunc_strcmp:
6925         if (visitStrCmpCall(I))
6926           return;
6927         break;
6928       case LibFunc_strlen:
6929         if (visitStrLenCall(I))
6930           return;
6931         break;
6932       case LibFunc_strnlen:
6933         if (visitStrNLenCall(I))
6934           return;
6935         break;
6936       }
6937     }
6938   }
6939 
6940   SDValue Callee;
6941   if (!RenameFn)
6942     Callee = getValue(I.getCalledValue());
6943   else
6944     Callee = DAG.getExternalSymbol(
6945         RenameFn,
6946         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6947 
6948   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6949   // have to do anything here to lower funclet bundles.
6950   assert(!I.hasOperandBundlesOtherThan(
6951              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6952          "Cannot lower calls with arbitrary operand bundles!");
6953 
6954   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6955     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6956   else
6957     // Check if we can potentially perform a tail call. More detailed checking
6958     // is be done within LowerCallTo, after more information about the call is
6959     // known.
6960     LowerCallTo(&I, Callee, I.isTailCall());
6961 }
6962 
6963 namespace {
6964 
6965 /// AsmOperandInfo - This contains information for each constraint that we are
6966 /// lowering.
6967 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6968 public:
6969   /// CallOperand - If this is the result output operand or a clobber
6970   /// this is null, otherwise it is the incoming operand to the CallInst.
6971   /// This gets modified as the asm is processed.
6972   SDValue CallOperand;
6973 
6974   /// AssignedRegs - If this is a register or register class operand, this
6975   /// contains the set of register corresponding to the operand.
6976   RegsForValue AssignedRegs;
6977 
6978   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6979     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
6980   }
6981 
6982   /// Whether or not this operand accesses memory
6983   bool hasMemory(const TargetLowering &TLI) const {
6984     // Indirect operand accesses access memory.
6985     if (isIndirect)
6986       return true;
6987 
6988     for (const auto &Code : Codes)
6989       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
6990         return true;
6991 
6992     return false;
6993   }
6994 
6995   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6996   /// corresponds to.  If there is no Value* for this operand, it returns
6997   /// MVT::Other.
6998   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6999                            const DataLayout &DL) const {
7000     if (!CallOperandVal) return MVT::Other;
7001 
7002     if (isa<BasicBlock>(CallOperandVal))
7003       return TLI.getPointerTy(DL);
7004 
7005     llvm::Type *OpTy = CallOperandVal->getType();
7006 
7007     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7008     // If this is an indirect operand, the operand is a pointer to the
7009     // accessed type.
7010     if (isIndirect) {
7011       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7012       if (!PtrTy)
7013         report_fatal_error("Indirect operand for inline asm not a pointer!");
7014       OpTy = PtrTy->getElementType();
7015     }
7016 
7017     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7018     if (StructType *STy = dyn_cast<StructType>(OpTy))
7019       if (STy->getNumElements() == 1)
7020         OpTy = STy->getElementType(0);
7021 
7022     // If OpTy is not a single value, it may be a struct/union that we
7023     // can tile with integers.
7024     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7025       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7026       switch (BitSize) {
7027       default: break;
7028       case 1:
7029       case 8:
7030       case 16:
7031       case 32:
7032       case 64:
7033       case 128:
7034         OpTy = IntegerType::get(Context, BitSize);
7035         break;
7036       }
7037     }
7038 
7039     return TLI.getValueType(DL, OpTy, true);
7040   }
7041 };
7042 
7043 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7044 
7045 } // end anonymous namespace
7046 
7047 /// Make sure that the output operand \p OpInfo and its corresponding input
7048 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7049 /// out).
7050 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7051                                SDISelAsmOperandInfo &MatchingOpInfo,
7052                                SelectionDAG &DAG) {
7053   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7054     return;
7055 
7056   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7057   const auto &TLI = DAG.getTargetLoweringInfo();
7058 
7059   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7060       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7061                                        OpInfo.ConstraintVT);
7062   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7063       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7064                                        MatchingOpInfo.ConstraintVT);
7065   if ((OpInfo.ConstraintVT.isInteger() !=
7066        MatchingOpInfo.ConstraintVT.isInteger()) ||
7067       (MatchRC.second != InputRC.second)) {
7068     // FIXME: error out in a more elegant fashion
7069     report_fatal_error("Unsupported asm: input constraint"
7070                        " with a matching output constraint of"
7071                        " incompatible type!");
7072   }
7073   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7074 }
7075 
7076 /// Get a direct memory input to behave well as an indirect operand.
7077 /// This may introduce stores, hence the need for a \p Chain.
7078 /// \return The (possibly updated) chain.
7079 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7080                                         SDISelAsmOperandInfo &OpInfo,
7081                                         SelectionDAG &DAG) {
7082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7083 
7084   // If we don't have an indirect input, put it in the constpool if we can,
7085   // otherwise spill it to a stack slot.
7086   // TODO: This isn't quite right. We need to handle these according to
7087   // the addressing mode that the constraint wants. Also, this may take
7088   // an additional register for the computation and we don't want that
7089   // either.
7090 
7091   // If the operand is a float, integer, or vector constant, spill to a
7092   // constant pool entry to get its address.
7093   const Value *OpVal = OpInfo.CallOperandVal;
7094   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7095       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7096     OpInfo.CallOperand = DAG.getConstantPool(
7097         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7098     return Chain;
7099   }
7100 
7101   // Otherwise, create a stack slot and emit a store to it before the asm.
7102   Type *Ty = OpVal->getType();
7103   auto &DL = DAG.getDataLayout();
7104   uint64_t TySize = DL.getTypeAllocSize(Ty);
7105   unsigned Align = DL.getPrefTypeAlignment(Ty);
7106   MachineFunction &MF = DAG.getMachineFunction();
7107   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7108   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7109   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7110                        MachinePointerInfo::getFixedStack(MF, SSFI));
7111   OpInfo.CallOperand = StackSlot;
7112 
7113   return Chain;
7114 }
7115 
7116 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7117 /// specified operand.  We prefer to assign virtual registers, to allow the
7118 /// register allocator to handle the assignment process.  However, if the asm
7119 /// uses features that we can't model on machineinstrs, we have SDISel do the
7120 /// allocation.  This produces generally horrible, but correct, code.
7121 ///
7122 ///   OpInfo describes the operand.
7123 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
7124                                  const SDLoc &DL,
7125                                  SDISelAsmOperandInfo &OpInfo) {
7126   LLVMContext &Context = *DAG.getContext();
7127 
7128   MachineFunction &MF = DAG.getMachineFunction();
7129   SmallVector<unsigned, 4> Regs;
7130   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7131 
7132   // If this is a constraint for a single physreg, or a constraint for a
7133   // register class, find it.
7134   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7135       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
7136                                        OpInfo.ConstraintVT);
7137 
7138   unsigned NumRegs = 1;
7139   if (OpInfo.ConstraintVT != MVT::Other) {
7140     // If this is a FP input in an integer register (or visa versa) insert a bit
7141     // cast of the input value.  More generally, handle any case where the input
7142     // value disagrees with the register class we plan to stick this in.
7143     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
7144         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7145       // Try to convert to the first EVT that the reg class contains.  If the
7146       // types are identical size, use a bitcast to convert (e.g. two differing
7147       // vector types).
7148       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7149       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
7150         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7151                                          RegVT, OpInfo.CallOperand);
7152         OpInfo.ConstraintVT = RegVT;
7153       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7154         // If the input is a FP value and we want it in FP registers, do a
7155         // bitcast to the corresponding integer type.  This turns an f64 value
7156         // into i64, which can be passed with two i32 values on a 32-bit
7157         // machine.
7158         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7159         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7160                                          RegVT, OpInfo.CallOperand);
7161         OpInfo.ConstraintVT = RegVT;
7162       }
7163     }
7164 
7165     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7166   }
7167 
7168   MVT RegVT;
7169   EVT ValueVT = OpInfo.ConstraintVT;
7170 
7171   // If this is a constraint for a specific physical register, like {r17},
7172   // assign it now.
7173   if (unsigned AssignedReg = PhysReg.first) {
7174     const TargetRegisterClass *RC = PhysReg.second;
7175     if (OpInfo.ConstraintVT == MVT::Other)
7176       ValueVT = *TRI.legalclasstypes_begin(*RC);
7177 
7178     // Get the actual register value type.  This is important, because the user
7179     // may have asked for (e.g.) the AX register in i32 type.  We need to
7180     // remember that AX is actually i16 to get the right extension.
7181     RegVT = *TRI.legalclasstypes_begin(*RC);
7182 
7183     // This is a explicit reference to a physical register.
7184     Regs.push_back(AssignedReg);
7185 
7186     // If this is an expanded reference, add the rest of the regs to Regs.
7187     if (NumRegs != 1) {
7188       TargetRegisterClass::iterator I = RC->begin();
7189       for (; *I != AssignedReg; ++I)
7190         assert(I != RC->end() && "Didn't find reg!");
7191 
7192       // Already added the first reg.
7193       --NumRegs; ++I;
7194       for (; NumRegs; --NumRegs, ++I) {
7195         assert(I != RC->end() && "Ran out of registers to allocate!");
7196         Regs.push_back(*I);
7197       }
7198     }
7199 
7200     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7201     return;
7202   }
7203 
7204   // Otherwise, if this was a reference to an LLVM register class, create vregs
7205   // for this reference.
7206   if (const TargetRegisterClass *RC = PhysReg.second) {
7207     RegVT = *TRI.legalclasstypes_begin(*RC);
7208     if (OpInfo.ConstraintVT == MVT::Other)
7209       ValueVT = RegVT;
7210 
7211     // Create the appropriate number of virtual registers.
7212     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7213     for (; NumRegs; --NumRegs)
7214       Regs.push_back(RegInfo.createVirtualRegister(RC));
7215 
7216     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7217     return;
7218   }
7219 
7220   // Otherwise, we couldn't allocate enough registers for this.
7221 }
7222 
7223 static unsigned
7224 findMatchingInlineAsmOperand(unsigned OperandNo,
7225                              const std::vector<SDValue> &AsmNodeOperands) {
7226   // Scan until we find the definition we already emitted of this operand.
7227   unsigned CurOp = InlineAsm::Op_FirstOperand;
7228   for (; OperandNo; --OperandNo) {
7229     // Advance to the next operand.
7230     unsigned OpFlag =
7231         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7232     assert((InlineAsm::isRegDefKind(OpFlag) ||
7233             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7234             InlineAsm::isMemKind(OpFlag)) &&
7235            "Skipped past definitions?");
7236     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7237   }
7238   return CurOp;
7239 }
7240 
7241 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7242 /// \return true if it has succeeded, false otherwise
7243 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7244                               MVT RegVT, SelectionDAG &DAG) {
7245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7246   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7247   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7248     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7249       Regs.push_back(RegInfo.createVirtualRegister(RC));
7250     else
7251       return false;
7252   }
7253   return true;
7254 }
7255 
7256 namespace {
7257 
7258 class ExtraFlags {
7259   unsigned Flags = 0;
7260 
7261 public:
7262   explicit ExtraFlags(ImmutableCallSite CS) {
7263     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7264     if (IA->hasSideEffects())
7265       Flags |= InlineAsm::Extra_HasSideEffects;
7266     if (IA->isAlignStack())
7267       Flags |= InlineAsm::Extra_IsAlignStack;
7268     if (CS.isConvergent())
7269       Flags |= InlineAsm::Extra_IsConvergent;
7270     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7271   }
7272 
7273   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7274     // Ideally, we would only check against memory constraints.  However, the
7275     // meaning of an Other constraint can be target-specific and we can't easily
7276     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7277     // for Other constraints as well.
7278     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7279         OpInfo.ConstraintType == TargetLowering::C_Other) {
7280       if (OpInfo.Type == InlineAsm::isInput)
7281         Flags |= InlineAsm::Extra_MayLoad;
7282       else if (OpInfo.Type == InlineAsm::isOutput)
7283         Flags |= InlineAsm::Extra_MayStore;
7284       else if (OpInfo.Type == InlineAsm::isClobber)
7285         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7286     }
7287   }
7288 
7289   unsigned get() const { return Flags; }
7290 };
7291 
7292 } // end anonymous namespace
7293 
7294 /// visitInlineAsm - Handle a call to an InlineAsm object.
7295 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7296   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7297 
7298   /// ConstraintOperands - Information about all of the constraints.
7299   SDISelAsmOperandInfoVector ConstraintOperands;
7300 
7301   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7302   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7303       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7304 
7305   bool hasMemory = false;
7306 
7307   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7308   ExtraFlags ExtraInfo(CS);
7309 
7310   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7311   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7312   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7313     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7314     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7315 
7316     MVT OpVT = MVT::Other;
7317 
7318     // Compute the value type for each operand.
7319     if (OpInfo.Type == InlineAsm::isInput ||
7320         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7321       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7322 
7323       // Process the call argument. BasicBlocks are labels, currently appearing
7324       // only in asm's.
7325       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7326         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7327       } else {
7328         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7329       }
7330 
7331       OpVT =
7332           OpInfo
7333               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7334               .getSimpleVT();
7335     }
7336 
7337     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7338       // The return value of the call is this value.  As such, there is no
7339       // corresponding argument.
7340       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7341       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7342         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7343                                       STy->getElementType(ResNo));
7344       } else {
7345         assert(ResNo == 0 && "Asm only has one result!");
7346         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7347       }
7348       ++ResNo;
7349     }
7350 
7351     OpInfo.ConstraintVT = OpVT;
7352 
7353     if (!hasMemory)
7354       hasMemory = OpInfo.hasMemory(TLI);
7355 
7356     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7357     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7358     auto TargetConstraint = TargetConstraints[i];
7359 
7360     // Compute the constraint code and ConstraintType to use.
7361     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7362 
7363     ExtraInfo.update(TargetConstraint);
7364   }
7365 
7366   SDValue Chain, Flag;
7367 
7368   // We won't need to flush pending loads if this asm doesn't touch
7369   // memory and is nonvolatile.
7370   if (hasMemory || IA->hasSideEffects())
7371     Chain = getRoot();
7372   else
7373     Chain = DAG.getRoot();
7374 
7375   // Second pass over the constraints: compute which constraint option to use
7376   // and assign registers to constraints that want a specific physreg.
7377   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7378     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7379 
7380     // If this is an output operand with a matching input operand, look up the
7381     // matching input. If their types mismatch, e.g. one is an integer, the
7382     // other is floating point, or their sizes are different, flag it as an
7383     // error.
7384     if (OpInfo.hasMatchingInput()) {
7385       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7386       patchMatchingInput(OpInfo, Input, DAG);
7387     }
7388 
7389     // Compute the constraint code and ConstraintType to use.
7390     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7391 
7392     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7393         OpInfo.Type == InlineAsm::isClobber)
7394       continue;
7395 
7396     // If this is a memory input, and if the operand is not indirect, do what we
7397     // need to provide an address for the memory input.
7398     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7399         !OpInfo.isIndirect) {
7400       assert((OpInfo.isMultipleAlternative ||
7401               (OpInfo.Type == InlineAsm::isInput)) &&
7402              "Can only indirectify direct input operands!");
7403 
7404       // Memory operands really want the address of the value.
7405       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7406 
7407       // There is no longer a Value* corresponding to this operand.
7408       OpInfo.CallOperandVal = nullptr;
7409 
7410       // It is now an indirect operand.
7411       OpInfo.isIndirect = true;
7412     }
7413 
7414     // If this constraint is for a specific register, allocate it before
7415     // anything else.
7416     if (OpInfo.ConstraintType == TargetLowering::C_Register)
7417       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7418   }
7419 
7420   // Third pass - Loop over all of the operands, assigning virtual or physregs
7421   // to register class operands.
7422   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7423     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7424 
7425     // C_Register operands have already been allocated, Other/Memory don't need
7426     // to be.
7427     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7428       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7429   }
7430 
7431   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7432   std::vector<SDValue> AsmNodeOperands;
7433   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7434   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7435       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7436 
7437   // If we have a !srcloc metadata node associated with it, we want to attach
7438   // this to the ultimately generated inline asm machineinstr.  To do this, we
7439   // pass in the third operand as this (potentially null) inline asm MDNode.
7440   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7441   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7442 
7443   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7444   // bits as operand 3.
7445   AsmNodeOperands.push_back(DAG.getTargetConstant(
7446       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7447 
7448   // Loop over all of the inputs, copying the operand values into the
7449   // appropriate registers and processing the output regs.
7450   RegsForValue RetValRegs;
7451 
7452   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7453   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7454 
7455   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7456     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7457 
7458     switch (OpInfo.Type) {
7459     case InlineAsm::isOutput:
7460       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7461           OpInfo.ConstraintType != TargetLowering::C_Register) {
7462         // Memory output, or 'other' output (e.g. 'X' constraint).
7463         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7464 
7465         unsigned ConstraintID =
7466             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7467         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7468                "Failed to convert memory constraint code to constraint id.");
7469 
7470         // Add information to the INLINEASM node to know about this output.
7471         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7472         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7473         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7474                                                         MVT::i32));
7475         AsmNodeOperands.push_back(OpInfo.CallOperand);
7476         break;
7477       }
7478 
7479       // Otherwise, this is a register or register class output.
7480 
7481       // Copy the output from the appropriate register.  Find a register that
7482       // we can use.
7483       if (OpInfo.AssignedRegs.Regs.empty()) {
7484         emitInlineAsmError(
7485             CS, "couldn't allocate output register for constraint '" +
7486                     Twine(OpInfo.ConstraintCode) + "'");
7487         return;
7488       }
7489 
7490       // If this is an indirect operand, store through the pointer after the
7491       // asm.
7492       if (OpInfo.isIndirect) {
7493         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7494                                                       OpInfo.CallOperandVal));
7495       } else {
7496         // This is the result value of the call.
7497         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7498         // Concatenate this output onto the outputs list.
7499         RetValRegs.append(OpInfo.AssignedRegs);
7500       }
7501 
7502       // Add information to the INLINEASM node to know that this register is
7503       // set.
7504       OpInfo.AssignedRegs
7505           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7506                                     ? InlineAsm::Kind_RegDefEarlyClobber
7507                                     : InlineAsm::Kind_RegDef,
7508                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7509       break;
7510 
7511     case InlineAsm::isInput: {
7512       SDValue InOperandVal = OpInfo.CallOperand;
7513 
7514       if (OpInfo.isMatchingInputConstraint()) {
7515         // If this is required to match an output register we have already set,
7516         // just use its register.
7517         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7518                                                   AsmNodeOperands);
7519         unsigned OpFlag =
7520           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7521         if (InlineAsm::isRegDefKind(OpFlag) ||
7522             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7523           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7524           if (OpInfo.isIndirect) {
7525             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7526             emitInlineAsmError(CS, "inline asm not supported yet:"
7527                                    " don't know how to handle tied "
7528                                    "indirect register inputs");
7529             return;
7530           }
7531 
7532           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7533           SmallVector<unsigned, 4> Regs;
7534 
7535           if (!createVirtualRegs(Regs,
7536                                  InlineAsm::getNumOperandRegisters(OpFlag),
7537                                  RegVT, DAG)) {
7538             emitInlineAsmError(CS, "inline asm error: This value type register "
7539                                    "class is not natively supported!");
7540             return;
7541           }
7542 
7543           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7544 
7545           SDLoc dl = getCurSDLoc();
7546           // Use the produced MatchedRegs object to
7547           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7548                                     CS.getInstruction());
7549           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7550                                            true, OpInfo.getMatchedOperand(), dl,
7551                                            DAG, AsmNodeOperands);
7552           break;
7553         }
7554 
7555         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7556         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7557                "Unexpected number of operands");
7558         // Add information to the INLINEASM node to know about this input.
7559         // See InlineAsm.h isUseOperandTiedToDef.
7560         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7561         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7562                                                     OpInfo.getMatchedOperand());
7563         AsmNodeOperands.push_back(DAG.getTargetConstant(
7564             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7565         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7566         break;
7567       }
7568 
7569       // Treat indirect 'X' constraint as memory.
7570       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7571           OpInfo.isIndirect)
7572         OpInfo.ConstraintType = TargetLowering::C_Memory;
7573 
7574       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7575         std::vector<SDValue> Ops;
7576         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7577                                           Ops, DAG);
7578         if (Ops.empty()) {
7579           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7580                                      Twine(OpInfo.ConstraintCode) + "'");
7581           return;
7582         }
7583 
7584         // Add information to the INLINEASM node to know about this input.
7585         unsigned ResOpType =
7586           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7587         AsmNodeOperands.push_back(DAG.getTargetConstant(
7588             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7589         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7590         break;
7591       }
7592 
7593       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7594         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7595         assert(InOperandVal.getValueType() ==
7596                    TLI.getPointerTy(DAG.getDataLayout()) &&
7597                "Memory operands expect pointer values");
7598 
7599         unsigned ConstraintID =
7600             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7601         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7602                "Failed to convert memory constraint code to constraint id.");
7603 
7604         // Add information to the INLINEASM node to know about this input.
7605         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7606         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7607         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7608                                                         getCurSDLoc(),
7609                                                         MVT::i32));
7610         AsmNodeOperands.push_back(InOperandVal);
7611         break;
7612       }
7613 
7614       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7615               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7616              "Unknown constraint type!");
7617 
7618       // TODO: Support this.
7619       if (OpInfo.isIndirect) {
7620         emitInlineAsmError(
7621             CS, "Don't know how to handle indirect register inputs yet "
7622                 "for constraint '" +
7623                     Twine(OpInfo.ConstraintCode) + "'");
7624         return;
7625       }
7626 
7627       // Copy the input into the appropriate registers.
7628       if (OpInfo.AssignedRegs.Regs.empty()) {
7629         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7630                                    Twine(OpInfo.ConstraintCode) + "'");
7631         return;
7632       }
7633 
7634       SDLoc dl = getCurSDLoc();
7635 
7636       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7637                                         Chain, &Flag, CS.getInstruction());
7638 
7639       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7640                                                dl, DAG, AsmNodeOperands);
7641       break;
7642     }
7643     case InlineAsm::isClobber:
7644       // Add the clobbered value to the operand list, so that the register
7645       // allocator is aware that the physreg got clobbered.
7646       if (!OpInfo.AssignedRegs.Regs.empty())
7647         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7648                                                  false, 0, getCurSDLoc(), DAG,
7649                                                  AsmNodeOperands);
7650       break;
7651     }
7652   }
7653 
7654   // Finish up input operands.  Set the input chain and add the flag last.
7655   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7656   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7657 
7658   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7659                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7660   Flag = Chain.getValue(1);
7661 
7662   // If this asm returns a register value, copy the result from that register
7663   // and set it as the value of the call.
7664   if (!RetValRegs.Regs.empty()) {
7665     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7666                                              Chain, &Flag, CS.getInstruction());
7667 
7668     // FIXME: Why don't we do this for inline asms with MRVs?
7669     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
7670       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7671 
7672       // If any of the results of the inline asm is a vector, it may have the
7673       // wrong width/num elts.  This can happen for register classes that can
7674       // contain multiple different value types.  The preg or vreg allocated may
7675       // not have the same VT as was expected.  Convert it to the right type
7676       // with bit_convert.
7677       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
7678         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
7679                           ResultType, Val);
7680 
7681       } else if (ResultType != Val.getValueType() &&
7682                  ResultType.isInteger() && Val.getValueType().isInteger()) {
7683         // If a result value was tied to an input value, the computed result may
7684         // have a wider width than the expected result.  Extract the relevant
7685         // portion.
7686         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
7687       }
7688 
7689       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
7690     }
7691 
7692     setValue(CS.getInstruction(), Val);
7693     // Don't need to use this as a chain in this case.
7694     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7695       return;
7696   }
7697 
7698   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7699 
7700   // Process indirect outputs, first output all of the flagged copies out of
7701   // physregs.
7702   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7703     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7704     const Value *Ptr = IndirectStoresToEmit[i].second;
7705     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7706                                              Chain, &Flag, IA);
7707     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7708   }
7709 
7710   // Emit the non-flagged stores from the physregs.
7711   SmallVector<SDValue, 8> OutChains;
7712   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7713     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7714                                getValue(StoresToEmit[i].second),
7715                                MachinePointerInfo(StoresToEmit[i].second));
7716     OutChains.push_back(Val);
7717   }
7718 
7719   if (!OutChains.empty())
7720     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7721 
7722   DAG.setRoot(Chain);
7723 }
7724 
7725 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7726                                              const Twine &Message) {
7727   LLVMContext &Ctx = *DAG.getContext();
7728   Ctx.emitError(CS.getInstruction(), Message);
7729 
7730   // Make sure we leave the DAG in a valid state
7731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7732   auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7733   setValue(CS.getInstruction(), DAG.getUNDEF(VT));
7734 }
7735 
7736 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7737   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7738                           MVT::Other, getRoot(),
7739                           getValue(I.getArgOperand(0)),
7740                           DAG.getSrcValue(I.getArgOperand(0))));
7741 }
7742 
7743 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7745   const DataLayout &DL = DAG.getDataLayout();
7746   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7747                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7748                            DAG.getSrcValue(I.getOperand(0)),
7749                            DL.getABITypeAlignment(I.getType()));
7750   setValue(&I, V);
7751   DAG.setRoot(V.getValue(1));
7752 }
7753 
7754 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7755   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7756                           MVT::Other, getRoot(),
7757                           getValue(I.getArgOperand(0)),
7758                           DAG.getSrcValue(I.getArgOperand(0))));
7759 }
7760 
7761 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7762   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7763                           MVT::Other, getRoot(),
7764                           getValue(I.getArgOperand(0)),
7765                           getValue(I.getArgOperand(1)),
7766                           DAG.getSrcValue(I.getArgOperand(0)),
7767                           DAG.getSrcValue(I.getArgOperand(1))));
7768 }
7769 
7770 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7771                                                     const Instruction &I,
7772                                                     SDValue Op) {
7773   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7774   if (!Range)
7775     return Op;
7776 
7777   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7778   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7779     return Op;
7780 
7781   APInt Lo = CR.getUnsignedMin();
7782   if (!Lo.isMinValue())
7783     return Op;
7784 
7785   APInt Hi = CR.getUnsignedMax();
7786   unsigned Bits = Hi.getActiveBits();
7787 
7788   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7789 
7790   SDLoc SL = getCurSDLoc();
7791 
7792   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7793                              DAG.getValueType(SmallVT));
7794   unsigned NumVals = Op.getNode()->getNumValues();
7795   if (NumVals == 1)
7796     return ZExt;
7797 
7798   SmallVector<SDValue, 4> Ops;
7799 
7800   Ops.push_back(ZExt);
7801   for (unsigned I = 1; I != NumVals; ++I)
7802     Ops.push_back(Op.getValue(I));
7803 
7804   return DAG.getMergeValues(Ops, SL);
7805 }
7806 
7807 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
7808 /// the call being lowered.
7809 ///
7810 /// This is a helper for lowering intrinsics that follow a target calling
7811 /// convention or require stack pointer adjustment. Only a subset of the
7812 /// intrinsic's operands need to participate in the calling convention.
7813 void SelectionDAGBuilder::populateCallLoweringInfo(
7814     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7815     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7816     bool IsPatchPoint) {
7817   TargetLowering::ArgListTy Args;
7818   Args.reserve(NumArgs);
7819 
7820   // Populate the argument list.
7821   // Attributes for args start at offset 1, after the return attribute.
7822   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7823        ArgI != ArgE; ++ArgI) {
7824     const Value *V = CS->getOperand(ArgI);
7825 
7826     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7827 
7828     TargetLowering::ArgListEntry Entry;
7829     Entry.Node = getValue(V);
7830     Entry.Ty = V->getType();
7831     Entry.setAttributes(&CS, ArgI);
7832     Args.push_back(Entry);
7833   }
7834 
7835   CLI.setDebugLoc(getCurSDLoc())
7836       .setChain(getRoot())
7837       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7838       .setDiscardResult(CS->use_empty())
7839       .setIsPatchPoint(IsPatchPoint);
7840 }
7841 
7842 /// Add a stack map intrinsic call's live variable operands to a stackmap
7843 /// or patchpoint target node's operand list.
7844 ///
7845 /// Constants are converted to TargetConstants purely as an optimization to
7846 /// avoid constant materialization and register allocation.
7847 ///
7848 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7849 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
7850 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7851 /// address materialization and register allocation, but may also be required
7852 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7853 /// alloca in the entry block, then the runtime may assume that the alloca's
7854 /// StackMap location can be read immediately after compilation and that the
7855 /// location is valid at any point during execution (this is similar to the
7856 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7857 /// only available in a register, then the runtime would need to trap when
7858 /// execution reaches the StackMap in order to read the alloca's location.
7859 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7860                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
7861                                 SelectionDAGBuilder &Builder) {
7862   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7863     SDValue OpVal = Builder.getValue(CS.getArgument(i));
7864     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7865       Ops.push_back(
7866         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7867       Ops.push_back(
7868         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7869     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7870       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7871       Ops.push_back(Builder.DAG.getTargetFrameIndex(
7872           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
7873     } else
7874       Ops.push_back(OpVal);
7875   }
7876 }
7877 
7878 /// Lower llvm.experimental.stackmap directly to its target opcode.
7879 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7880   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7881   //                                  [live variables...])
7882 
7883   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7884 
7885   SDValue Chain, InFlag, Callee, NullPtr;
7886   SmallVector<SDValue, 32> Ops;
7887 
7888   SDLoc DL = getCurSDLoc();
7889   Callee = getValue(CI.getCalledValue());
7890   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7891 
7892   // The stackmap intrinsic only records the live variables (the arguemnts
7893   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7894   // intrinsic, this won't be lowered to a function call. This means we don't
7895   // have to worry about calling conventions and target specific lowering code.
7896   // Instead we perform the call lowering right here.
7897   //
7898   // chain, flag = CALLSEQ_START(chain, 0, 0)
7899   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7900   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7901   //
7902   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
7903   InFlag = Chain.getValue(1);
7904 
7905   // Add the <id> and <numBytes> constants.
7906   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7907   Ops.push_back(DAG.getTargetConstant(
7908                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7909   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7910   Ops.push_back(DAG.getTargetConstant(
7911                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7912                   MVT::i32));
7913 
7914   // Push live variables for the stack map.
7915   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7916 
7917   // We are not pushing any register mask info here on the operands list,
7918   // because the stackmap doesn't clobber anything.
7919 
7920   // Push the chain and the glue flag.
7921   Ops.push_back(Chain);
7922   Ops.push_back(InFlag);
7923 
7924   // Create the STACKMAP node.
7925   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7926   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7927   Chain = SDValue(SM, 0);
7928   InFlag = Chain.getValue(1);
7929 
7930   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7931 
7932   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7933 
7934   // Set the root to the target-lowered call chain.
7935   DAG.setRoot(Chain);
7936 
7937   // Inform the Frame Information that we have a stackmap in this function.
7938   FuncInfo.MF->getFrameInfo().setHasStackMap();
7939 }
7940 
7941 /// Lower llvm.experimental.patchpoint directly to its target opcode.
7942 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7943                                           const BasicBlock *EHPadBB) {
7944   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7945   //                                                 i32 <numBytes>,
7946   //                                                 i8* <target>,
7947   //                                                 i32 <numArgs>,
7948   //                                                 [Args...],
7949   //                                                 [live variables...])
7950 
7951   CallingConv::ID CC = CS.getCallingConv();
7952   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7953   bool HasDef = !CS->getType()->isVoidTy();
7954   SDLoc dl = getCurSDLoc();
7955   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7956 
7957   // Handle immediate and symbolic callees.
7958   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7959     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7960                                    /*isTarget=*/true);
7961   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7962     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7963                                          SDLoc(SymbolicCallee),
7964                                          SymbolicCallee->getValueType(0));
7965 
7966   // Get the real number of arguments participating in the call <numArgs>
7967   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7968   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7969 
7970   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7971   // Intrinsics include all meta-operands up to but not including CC.
7972   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7973   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7974          "Not enough arguments provided to the patchpoint intrinsic");
7975 
7976   // For AnyRegCC the arguments are lowered later on manually.
7977   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7978   Type *ReturnTy =
7979     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7980 
7981   TargetLowering::CallLoweringInfo CLI(DAG);
7982   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7983                            true);
7984   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7985 
7986   SDNode *CallEnd = Result.second.getNode();
7987   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7988     CallEnd = CallEnd->getOperand(0).getNode();
7989 
7990   /// Get a call instruction from the call sequence chain.
7991   /// Tail calls are not allowed.
7992   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7993          "Expected a callseq node.");
7994   SDNode *Call = CallEnd->getOperand(0).getNode();
7995   bool HasGlue = Call->getGluedNode();
7996 
7997   // Replace the target specific call node with the patchable intrinsic.
7998   SmallVector<SDValue, 8> Ops;
7999 
8000   // Add the <id> and <numBytes> constants.
8001   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8002   Ops.push_back(DAG.getTargetConstant(
8003                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8004   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8005   Ops.push_back(DAG.getTargetConstant(
8006                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8007                   MVT::i32));
8008 
8009   // Add the callee.
8010   Ops.push_back(Callee);
8011 
8012   // Adjust <numArgs> to account for any arguments that have been passed on the
8013   // stack instead.
8014   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8015   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8016   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8017   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8018 
8019   // Add the calling convention
8020   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8021 
8022   // Add the arguments we omitted previously. The register allocator should
8023   // place these in any free register.
8024   if (IsAnyRegCC)
8025     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8026       Ops.push_back(getValue(CS.getArgument(i)));
8027 
8028   // Push the arguments from the call instruction up to the register mask.
8029   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8030   Ops.append(Call->op_begin() + 2, e);
8031 
8032   // Push live variables for the stack map.
8033   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8034 
8035   // Push the register mask info.
8036   if (HasGlue)
8037     Ops.push_back(*(Call->op_end()-2));
8038   else
8039     Ops.push_back(*(Call->op_end()-1));
8040 
8041   // Push the chain (this is originally the first operand of the call, but
8042   // becomes now the last or second to last operand).
8043   Ops.push_back(*(Call->op_begin()));
8044 
8045   // Push the glue flag (last operand).
8046   if (HasGlue)
8047     Ops.push_back(*(Call->op_end()-1));
8048 
8049   SDVTList NodeTys;
8050   if (IsAnyRegCC && HasDef) {
8051     // Create the return types based on the intrinsic definition
8052     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8053     SmallVector<EVT, 3> ValueVTs;
8054     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8055     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8056 
8057     // There is always a chain and a glue type at the end
8058     ValueVTs.push_back(MVT::Other);
8059     ValueVTs.push_back(MVT::Glue);
8060     NodeTys = DAG.getVTList(ValueVTs);
8061   } else
8062     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8063 
8064   // Replace the target specific call node with a PATCHPOINT node.
8065   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8066                                          dl, NodeTys, Ops);
8067 
8068   // Update the NodeMap.
8069   if (HasDef) {
8070     if (IsAnyRegCC)
8071       setValue(CS.getInstruction(), SDValue(MN, 0));
8072     else
8073       setValue(CS.getInstruction(), Result.first);
8074   }
8075 
8076   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8077   // call sequence. Furthermore the location of the chain and glue can change
8078   // when the AnyReg calling convention is used and the intrinsic returns a
8079   // value.
8080   if (IsAnyRegCC && HasDef) {
8081     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8082     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8083     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8084   } else
8085     DAG.ReplaceAllUsesWith(Call, MN);
8086   DAG.DeleteNode(Call);
8087 
8088   // Inform the Frame Information that we have a patchpoint in this function.
8089   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8090 }
8091 
8092 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8093                                             unsigned Intrinsic) {
8094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8095   SDValue Op1 = getValue(I.getArgOperand(0));
8096   SDValue Op2;
8097   if (I.getNumArgOperands() > 1)
8098     Op2 = getValue(I.getArgOperand(1));
8099   SDLoc dl = getCurSDLoc();
8100   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8101   SDValue Res;
8102   FastMathFlags FMF;
8103   if (isa<FPMathOperator>(I))
8104     FMF = I.getFastMathFlags();
8105   SDNodeFlags SDFlags;
8106   SDFlags.setNoNaNs(FMF.noNaNs());
8107 
8108   switch (Intrinsic) {
8109   case Intrinsic::experimental_vector_reduce_fadd:
8110     if (FMF.isFast())
8111       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8112     else
8113       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8114     break;
8115   case Intrinsic::experimental_vector_reduce_fmul:
8116     if (FMF.isFast())
8117       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8118     else
8119       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8120     break;
8121   case Intrinsic::experimental_vector_reduce_add:
8122     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8123     break;
8124   case Intrinsic::experimental_vector_reduce_mul:
8125     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8126     break;
8127   case Intrinsic::experimental_vector_reduce_and:
8128     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8129     break;
8130   case Intrinsic::experimental_vector_reduce_or:
8131     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8132     break;
8133   case Intrinsic::experimental_vector_reduce_xor:
8134     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8135     break;
8136   case Intrinsic::experimental_vector_reduce_smax:
8137     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8138     break;
8139   case Intrinsic::experimental_vector_reduce_smin:
8140     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8141     break;
8142   case Intrinsic::experimental_vector_reduce_umax:
8143     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8144     break;
8145   case Intrinsic::experimental_vector_reduce_umin:
8146     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8147     break;
8148   case Intrinsic::experimental_vector_reduce_fmax:
8149     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
8150     break;
8151   case Intrinsic::experimental_vector_reduce_fmin:
8152     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
8153     break;
8154   default:
8155     llvm_unreachable("Unhandled vector reduce intrinsic");
8156   }
8157   setValue(&I, Res);
8158 }
8159 
8160 /// Returns an AttributeList representing the attributes applied to the return
8161 /// value of the given call.
8162 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8163   SmallVector<Attribute::AttrKind, 2> Attrs;
8164   if (CLI.RetSExt)
8165     Attrs.push_back(Attribute::SExt);
8166   if (CLI.RetZExt)
8167     Attrs.push_back(Attribute::ZExt);
8168   if (CLI.IsInReg)
8169     Attrs.push_back(Attribute::InReg);
8170 
8171   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8172                             Attrs);
8173 }
8174 
8175 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8176 /// implementation, which just calls LowerCall.
8177 /// FIXME: When all targets are
8178 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8179 std::pair<SDValue, SDValue>
8180 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8181   // Handle the incoming return values from the call.
8182   CLI.Ins.clear();
8183   Type *OrigRetTy = CLI.RetTy;
8184   SmallVector<EVT, 4> RetTys;
8185   SmallVector<uint64_t, 4> Offsets;
8186   auto &DL = CLI.DAG.getDataLayout();
8187   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8188 
8189   if (CLI.IsPostTypeLegalization) {
8190     // If we are lowering a libcall after legalization, split the return type.
8191     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8192     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8193     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8194       EVT RetVT = OldRetTys[i];
8195       uint64_t Offset = OldOffsets[i];
8196       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8197       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8198       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8199       RetTys.append(NumRegs, RegisterVT);
8200       for (unsigned j = 0; j != NumRegs; ++j)
8201         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8202     }
8203   }
8204 
8205   SmallVector<ISD::OutputArg, 4> Outs;
8206   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8207 
8208   bool CanLowerReturn =
8209       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8210                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8211 
8212   SDValue DemoteStackSlot;
8213   int DemoteStackIdx = -100;
8214   if (!CanLowerReturn) {
8215     // FIXME: equivalent assert?
8216     // assert(!CS.hasInAllocaArgument() &&
8217     //        "sret demotion is incompatible with inalloca");
8218     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8219     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8220     MachineFunction &MF = CLI.DAG.getMachineFunction();
8221     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8222     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
8223 
8224     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8225     ArgListEntry Entry;
8226     Entry.Node = DemoteStackSlot;
8227     Entry.Ty = StackSlotPtrType;
8228     Entry.IsSExt = false;
8229     Entry.IsZExt = false;
8230     Entry.IsInReg = false;
8231     Entry.IsSRet = true;
8232     Entry.IsNest = false;
8233     Entry.IsByVal = false;
8234     Entry.IsReturned = false;
8235     Entry.IsSwiftSelf = false;
8236     Entry.IsSwiftError = false;
8237     Entry.Alignment = Align;
8238     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8239     CLI.NumFixedArgs += 1;
8240     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8241 
8242     // sret demotion isn't compatible with tail-calls, since the sret argument
8243     // points into the callers stack frame.
8244     CLI.IsTailCall = false;
8245   } else {
8246     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8247       EVT VT = RetTys[I];
8248       MVT RegisterVT =
8249           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8250       unsigned NumRegs =
8251           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8252       for (unsigned i = 0; i != NumRegs; ++i) {
8253         ISD::InputArg MyFlags;
8254         MyFlags.VT = RegisterVT;
8255         MyFlags.ArgVT = VT;
8256         MyFlags.Used = CLI.IsReturnValueUsed;
8257         if (CLI.RetSExt)
8258           MyFlags.Flags.setSExt();
8259         if (CLI.RetZExt)
8260           MyFlags.Flags.setZExt();
8261         if (CLI.IsInReg)
8262           MyFlags.Flags.setInReg();
8263         CLI.Ins.push_back(MyFlags);
8264       }
8265     }
8266   }
8267 
8268   // We push in swifterror return as the last element of CLI.Ins.
8269   ArgListTy &Args = CLI.getArgs();
8270   if (supportSwiftError()) {
8271     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8272       if (Args[i].IsSwiftError) {
8273         ISD::InputArg MyFlags;
8274         MyFlags.VT = getPointerTy(DL);
8275         MyFlags.ArgVT = EVT(getPointerTy(DL));
8276         MyFlags.Flags.setSwiftError();
8277         CLI.Ins.push_back(MyFlags);
8278       }
8279     }
8280   }
8281 
8282   // Handle all of the outgoing arguments.
8283   CLI.Outs.clear();
8284   CLI.OutVals.clear();
8285   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8286     SmallVector<EVT, 4> ValueVTs;
8287     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8288     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8289     Type *FinalType = Args[i].Ty;
8290     if (Args[i].IsByVal)
8291       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8292     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8293         FinalType, CLI.CallConv, CLI.IsVarArg);
8294     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8295          ++Value) {
8296       EVT VT = ValueVTs[Value];
8297       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8298       SDValue Op = SDValue(Args[i].Node.getNode(),
8299                            Args[i].Node.getResNo() + Value);
8300       ISD::ArgFlagsTy Flags;
8301 
8302       // Certain targets (such as MIPS), may have a different ABI alignment
8303       // for a type depending on the context. Give the target a chance to
8304       // specify the alignment it wants.
8305       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8306 
8307       if (Args[i].IsZExt)
8308         Flags.setZExt();
8309       if (Args[i].IsSExt)
8310         Flags.setSExt();
8311       if (Args[i].IsInReg) {
8312         // If we are using vectorcall calling convention, a structure that is
8313         // passed InReg - is surely an HVA
8314         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8315             isa<StructType>(FinalType)) {
8316           // The first value of a structure is marked
8317           if (0 == Value)
8318             Flags.setHvaStart();
8319           Flags.setHva();
8320         }
8321         // Set InReg Flag
8322         Flags.setInReg();
8323       }
8324       if (Args[i].IsSRet)
8325         Flags.setSRet();
8326       if (Args[i].IsSwiftSelf)
8327         Flags.setSwiftSelf();
8328       if (Args[i].IsSwiftError)
8329         Flags.setSwiftError();
8330       if (Args[i].IsByVal)
8331         Flags.setByVal();
8332       if (Args[i].IsInAlloca) {
8333         Flags.setInAlloca();
8334         // Set the byval flag for CCAssignFn callbacks that don't know about
8335         // inalloca.  This way we can know how many bytes we should've allocated
8336         // and how many bytes a callee cleanup function will pop.  If we port
8337         // inalloca to more targets, we'll have to add custom inalloca handling
8338         // in the various CC lowering callbacks.
8339         Flags.setByVal();
8340       }
8341       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8342         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8343         Type *ElementTy = Ty->getElementType();
8344         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8345         // For ByVal, alignment should come from FE.  BE will guess if this
8346         // info is not there but there are cases it cannot get right.
8347         unsigned FrameAlign;
8348         if (Args[i].Alignment)
8349           FrameAlign = Args[i].Alignment;
8350         else
8351           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8352         Flags.setByValAlign(FrameAlign);
8353       }
8354       if (Args[i].IsNest)
8355         Flags.setNest();
8356       if (NeedsRegBlock)
8357         Flags.setInConsecutiveRegs();
8358       Flags.setOrigAlign(OriginalAlignment);
8359 
8360       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8361       unsigned NumParts =
8362           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8363       SmallVector<SDValue, 4> Parts(NumParts);
8364       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8365 
8366       if (Args[i].IsSExt)
8367         ExtendKind = ISD::SIGN_EXTEND;
8368       else if (Args[i].IsZExt)
8369         ExtendKind = ISD::ZERO_EXTEND;
8370 
8371       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8372       // for now.
8373       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8374           CanLowerReturn) {
8375         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8376                "unexpected use of 'returned'");
8377         // Before passing 'returned' to the target lowering code, ensure that
8378         // either the register MVT and the actual EVT are the same size or that
8379         // the return value and argument are extended in the same way; in these
8380         // cases it's safe to pass the argument register value unchanged as the
8381         // return register value (although it's at the target's option whether
8382         // to do so)
8383         // TODO: allow code generation to take advantage of partially preserved
8384         // registers rather than clobbering the entire register when the
8385         // parameter extension method is not compatible with the return
8386         // extension method
8387         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8388             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8389              CLI.RetZExt == Args[i].IsZExt))
8390           Flags.setReturned();
8391       }
8392 
8393       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8394                      CLI.CS.getInstruction(), ExtendKind, true);
8395 
8396       for (unsigned j = 0; j != NumParts; ++j) {
8397         // if it isn't first piece, alignment must be 1
8398         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8399                                i < CLI.NumFixedArgs,
8400                                i, j*Parts[j].getValueType().getStoreSize());
8401         if (NumParts > 1 && j == 0)
8402           MyFlags.Flags.setSplit();
8403         else if (j != 0) {
8404           MyFlags.Flags.setOrigAlign(1);
8405           if (j == NumParts - 1)
8406             MyFlags.Flags.setSplitEnd();
8407         }
8408 
8409         CLI.Outs.push_back(MyFlags);
8410         CLI.OutVals.push_back(Parts[j]);
8411       }
8412 
8413       if (NeedsRegBlock && Value == NumValues - 1)
8414         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8415     }
8416   }
8417 
8418   SmallVector<SDValue, 4> InVals;
8419   CLI.Chain = LowerCall(CLI, InVals);
8420 
8421   // Update CLI.InVals to use outside of this function.
8422   CLI.InVals = InVals;
8423 
8424   // Verify that the target's LowerCall behaved as expected.
8425   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8426          "LowerCall didn't return a valid chain!");
8427   assert((!CLI.IsTailCall || InVals.empty()) &&
8428          "LowerCall emitted a return value for a tail call!");
8429   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8430          "LowerCall didn't emit the correct number of values!");
8431 
8432   // For a tail call, the return value is merely live-out and there aren't
8433   // any nodes in the DAG representing it. Return a special value to
8434   // indicate that a tail call has been emitted and no more Instructions
8435   // should be processed in the current block.
8436   if (CLI.IsTailCall) {
8437     CLI.DAG.setRoot(CLI.Chain);
8438     return std::make_pair(SDValue(), SDValue());
8439   }
8440 
8441 #ifndef NDEBUG
8442   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8443     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8444     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8445            "LowerCall emitted a value with the wrong type!");
8446   }
8447 #endif
8448 
8449   SmallVector<SDValue, 4> ReturnValues;
8450   if (!CanLowerReturn) {
8451     // The instruction result is the result of loading from the
8452     // hidden sret parameter.
8453     SmallVector<EVT, 1> PVTs;
8454     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8455 
8456     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8457     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8458     EVT PtrVT = PVTs[0];
8459 
8460     unsigned NumValues = RetTys.size();
8461     ReturnValues.resize(NumValues);
8462     SmallVector<SDValue, 4> Chains(NumValues);
8463 
8464     // An aggregate return value cannot wrap around the address space, so
8465     // offsets to its parts don't wrap either.
8466     SDNodeFlags Flags;
8467     Flags.setNoUnsignedWrap(true);
8468 
8469     for (unsigned i = 0; i < NumValues; ++i) {
8470       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8471                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8472                                                         PtrVT), Flags);
8473       SDValue L = CLI.DAG.getLoad(
8474           RetTys[i], CLI.DL, CLI.Chain, Add,
8475           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8476                                             DemoteStackIdx, Offsets[i]),
8477           /* Alignment = */ 1);
8478       ReturnValues[i] = L;
8479       Chains[i] = L.getValue(1);
8480     }
8481 
8482     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8483   } else {
8484     // Collect the legal value parts into potentially illegal values
8485     // that correspond to the original function's return values.
8486     Optional<ISD::NodeType> AssertOp;
8487     if (CLI.RetSExt)
8488       AssertOp = ISD::AssertSext;
8489     else if (CLI.RetZExt)
8490       AssertOp = ISD::AssertZext;
8491     unsigned CurReg = 0;
8492     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8493       EVT VT = RetTys[I];
8494       MVT RegisterVT =
8495           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8496       unsigned NumRegs =
8497           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8498 
8499       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8500                                               NumRegs, RegisterVT, VT, nullptr,
8501                                               AssertOp, true));
8502       CurReg += NumRegs;
8503     }
8504 
8505     // For a function returning void, there is no return value. We can't create
8506     // such a node, so we just return a null return value in that case. In
8507     // that case, nothing will actually look at the value.
8508     if (ReturnValues.empty())
8509       return std::make_pair(SDValue(), CLI.Chain);
8510   }
8511 
8512   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8513                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8514   return std::make_pair(Res, CLI.Chain);
8515 }
8516 
8517 void TargetLowering::LowerOperationWrapper(SDNode *N,
8518                                            SmallVectorImpl<SDValue> &Results,
8519                                            SelectionDAG &DAG) const {
8520   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8521     Results.push_back(Res);
8522 }
8523 
8524 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8525   llvm_unreachable("LowerOperation not implemented for this target!");
8526 }
8527 
8528 void
8529 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8530   SDValue Op = getNonRegisterValue(V);
8531   assert((Op.getOpcode() != ISD::CopyFromReg ||
8532           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8533          "Copy from a reg to the same reg!");
8534   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8535 
8536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8537   // If this is an InlineAsm we have to match the registers required, not the
8538   // notional registers required by the type.
8539 
8540   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
8541                    V->getType(), isABIRegCopy(V));
8542   SDValue Chain = DAG.getEntryNode();
8543 
8544   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8545                               FuncInfo.PreferredExtendType.end())
8546                                  ? ISD::ANY_EXTEND
8547                                  : FuncInfo.PreferredExtendType[V];
8548   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8549   PendingExports.push_back(Chain);
8550 }
8551 
8552 #include "llvm/CodeGen/SelectionDAGISel.h"
8553 
8554 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8555 /// entry block, return true.  This includes arguments used by switches, since
8556 /// the switch may expand into multiple basic blocks.
8557 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8558   // With FastISel active, we may be splitting blocks, so force creation
8559   // of virtual registers for all non-dead arguments.
8560   if (FastISel)
8561     return A->use_empty();
8562 
8563   const BasicBlock &Entry = A->getParent()->front();
8564   for (const User *U : A->users())
8565     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8566       return false;  // Use not in entry block.
8567 
8568   return true;
8569 }
8570 
8571 using ArgCopyElisionMapTy =
8572     DenseMap<const Argument *,
8573              std::pair<const AllocaInst *, const StoreInst *>>;
8574 
8575 /// Scan the entry block of the function in FuncInfo for arguments that look
8576 /// like copies into a local alloca. Record any copied arguments in
8577 /// ArgCopyElisionCandidates.
8578 static void
8579 findArgumentCopyElisionCandidates(const DataLayout &DL,
8580                                   FunctionLoweringInfo *FuncInfo,
8581                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8582   // Record the state of every static alloca used in the entry block. Argument
8583   // allocas are all used in the entry block, so we need approximately as many
8584   // entries as we have arguments.
8585   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8586   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8587   unsigned NumArgs = FuncInfo->Fn->arg_size();
8588   StaticAllocas.reserve(NumArgs * 2);
8589 
8590   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8591     if (!V)
8592       return nullptr;
8593     V = V->stripPointerCasts();
8594     const auto *AI = dyn_cast<AllocaInst>(V);
8595     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8596       return nullptr;
8597     auto Iter = StaticAllocas.insert({AI, Unknown});
8598     return &Iter.first->second;
8599   };
8600 
8601   // Look for stores of arguments to static allocas. Look through bitcasts and
8602   // GEPs to handle type coercions, as long as the alloca is fully initialized
8603   // by the store. Any non-store use of an alloca escapes it and any subsequent
8604   // unanalyzed store might write it.
8605   // FIXME: Handle structs initialized with multiple stores.
8606   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8607     // Look for stores, and handle non-store uses conservatively.
8608     const auto *SI = dyn_cast<StoreInst>(&I);
8609     if (!SI) {
8610       // We will look through cast uses, so ignore them completely.
8611       if (I.isCast())
8612         continue;
8613       // Ignore debug info intrinsics, they don't escape or store to allocas.
8614       if (isa<DbgInfoIntrinsic>(I))
8615         continue;
8616       // This is an unknown instruction. Assume it escapes or writes to all
8617       // static alloca operands.
8618       for (const Use &U : I.operands()) {
8619         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8620           *Info = StaticAllocaInfo::Clobbered;
8621       }
8622       continue;
8623     }
8624 
8625     // If the stored value is a static alloca, mark it as escaped.
8626     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8627       *Info = StaticAllocaInfo::Clobbered;
8628 
8629     // Check if the destination is a static alloca.
8630     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8631     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8632     if (!Info)
8633       continue;
8634     const AllocaInst *AI = cast<AllocaInst>(Dst);
8635 
8636     // Skip allocas that have been initialized or clobbered.
8637     if (*Info != StaticAllocaInfo::Unknown)
8638       continue;
8639 
8640     // Check if the stored value is an argument, and that this store fully
8641     // initializes the alloca. Don't elide copies from the same argument twice.
8642     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8643     const auto *Arg = dyn_cast<Argument>(Val);
8644     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8645         Arg->getType()->isEmptyTy() ||
8646         DL.getTypeStoreSize(Arg->getType()) !=
8647             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8648         ArgCopyElisionCandidates.count(Arg)) {
8649       *Info = StaticAllocaInfo::Clobbered;
8650       continue;
8651     }
8652 
8653     DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
8654 
8655     // Mark this alloca and store for argument copy elision.
8656     *Info = StaticAllocaInfo::Elidable;
8657     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8658 
8659     // Stop scanning if we've seen all arguments. This will happen early in -O0
8660     // builds, which is useful, because -O0 builds have large entry blocks and
8661     // many allocas.
8662     if (ArgCopyElisionCandidates.size() == NumArgs)
8663       break;
8664   }
8665 }
8666 
8667 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8668 /// ArgVal is a load from a suitable fixed stack object.
8669 static void tryToElideArgumentCopy(
8670     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8671     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8672     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8673     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8674     SDValue ArgVal, bool &ArgHasUses) {
8675   // Check if this is a load from a fixed stack object.
8676   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8677   if (!LNode)
8678     return;
8679   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8680   if (!FINode)
8681     return;
8682 
8683   // Check that the fixed stack object is the right size and alignment.
8684   // Look at the alignment that the user wrote on the alloca instead of looking
8685   // at the stack object.
8686   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8687   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8688   const AllocaInst *AI = ArgCopyIter->second.first;
8689   int FixedIndex = FINode->getIndex();
8690   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8691   int OldIndex = AllocaIndex;
8692   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8693   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8694     DEBUG(dbgs() << "  argument copy elision failed due to bad fixed stack "
8695                     "object size\n");
8696     return;
8697   }
8698   unsigned RequiredAlignment = AI->getAlignment();
8699   if (!RequiredAlignment) {
8700     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8701         AI->getAllocatedType());
8702   }
8703   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8704     DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8705                     "greater than stack argument alignment ("
8706                  << RequiredAlignment << " vs "
8707                  << MFI.getObjectAlignment(FixedIndex) << ")\n");
8708     return;
8709   }
8710 
8711   // Perform the elision. Delete the old stack object and replace its only use
8712   // in the variable info map. Mark the stack object as mutable.
8713   DEBUG({
8714     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8715            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8716            << '\n';
8717   });
8718   MFI.RemoveStackObject(OldIndex);
8719   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8720   AllocaIndex = FixedIndex;
8721   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8722   Chains.push_back(ArgVal.getValue(1));
8723 
8724   // Avoid emitting code for the store implementing the copy.
8725   const StoreInst *SI = ArgCopyIter->second.second;
8726   ElidedArgCopyInstrs.insert(SI);
8727 
8728   // Check for uses of the argument again so that we can avoid exporting ArgVal
8729   // if it is't used by anything other than the store.
8730   for (const Value *U : Arg.users()) {
8731     if (U != SI) {
8732       ArgHasUses = true;
8733       break;
8734     }
8735   }
8736 }
8737 
8738 void SelectionDAGISel::LowerArguments(const Function &F) {
8739   SelectionDAG &DAG = SDB->DAG;
8740   SDLoc dl = SDB->getCurSDLoc();
8741   const DataLayout &DL = DAG.getDataLayout();
8742   SmallVector<ISD::InputArg, 16> Ins;
8743 
8744   if (!FuncInfo->CanLowerReturn) {
8745     // Put in an sret pointer parameter before all the other parameters.
8746     SmallVector<EVT, 1> ValueVTs;
8747     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8748                     F.getReturnType()->getPointerTo(
8749                         DAG.getDataLayout().getAllocaAddrSpace()),
8750                     ValueVTs);
8751 
8752     // NOTE: Assuming that a pointer will never break down to more than one VT
8753     // or one register.
8754     ISD::ArgFlagsTy Flags;
8755     Flags.setSRet();
8756     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8757     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8758                          ISD::InputArg::NoArgIndex, 0);
8759     Ins.push_back(RetArg);
8760   }
8761 
8762   // Look for stores of arguments to static allocas. Mark such arguments with a
8763   // flag to ask the target to give us the memory location of that argument if
8764   // available.
8765   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8766   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8767 
8768   // Set up the incoming argument description vector.
8769   for (const Argument &Arg : F.args()) {
8770     unsigned ArgNo = Arg.getArgNo();
8771     SmallVector<EVT, 4> ValueVTs;
8772     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8773     bool isArgValueUsed = !Arg.use_empty();
8774     unsigned PartBase = 0;
8775     Type *FinalType = Arg.getType();
8776     if (Arg.hasAttribute(Attribute::ByVal))
8777       FinalType = cast<PointerType>(FinalType)->getElementType();
8778     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8779         FinalType, F.getCallingConv(), F.isVarArg());
8780     for (unsigned Value = 0, NumValues = ValueVTs.size();
8781          Value != NumValues; ++Value) {
8782       EVT VT = ValueVTs[Value];
8783       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8784       ISD::ArgFlagsTy Flags;
8785 
8786       // Certain targets (such as MIPS), may have a different ABI alignment
8787       // for a type depending on the context. Give the target a chance to
8788       // specify the alignment it wants.
8789       unsigned OriginalAlignment =
8790           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8791 
8792       if (Arg.hasAttribute(Attribute::ZExt))
8793         Flags.setZExt();
8794       if (Arg.hasAttribute(Attribute::SExt))
8795         Flags.setSExt();
8796       if (Arg.hasAttribute(Attribute::InReg)) {
8797         // If we are using vectorcall calling convention, a structure that is
8798         // passed InReg - is surely an HVA
8799         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8800             isa<StructType>(Arg.getType())) {
8801           // The first value of a structure is marked
8802           if (0 == Value)
8803             Flags.setHvaStart();
8804           Flags.setHva();
8805         }
8806         // Set InReg Flag
8807         Flags.setInReg();
8808       }
8809       if (Arg.hasAttribute(Attribute::StructRet))
8810         Flags.setSRet();
8811       if (Arg.hasAttribute(Attribute::SwiftSelf))
8812         Flags.setSwiftSelf();
8813       if (Arg.hasAttribute(Attribute::SwiftError))
8814         Flags.setSwiftError();
8815       if (Arg.hasAttribute(Attribute::ByVal))
8816         Flags.setByVal();
8817       if (Arg.hasAttribute(Attribute::InAlloca)) {
8818         Flags.setInAlloca();
8819         // Set the byval flag for CCAssignFn callbacks that don't know about
8820         // inalloca.  This way we can know how many bytes we should've allocated
8821         // and how many bytes a callee cleanup function will pop.  If we port
8822         // inalloca to more targets, we'll have to add custom inalloca handling
8823         // in the various CC lowering callbacks.
8824         Flags.setByVal();
8825       }
8826       if (F.getCallingConv() == CallingConv::X86_INTR) {
8827         // IA Interrupt passes frame (1st parameter) by value in the stack.
8828         if (ArgNo == 0)
8829           Flags.setByVal();
8830       }
8831       if (Flags.isByVal() || Flags.isInAlloca()) {
8832         PointerType *Ty = cast<PointerType>(Arg.getType());
8833         Type *ElementTy = Ty->getElementType();
8834         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8835         // For ByVal, alignment should be passed from FE.  BE will guess if
8836         // this info is not there but there are cases it cannot get right.
8837         unsigned FrameAlign;
8838         if (Arg.getParamAlignment())
8839           FrameAlign = Arg.getParamAlignment();
8840         else
8841           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
8842         Flags.setByValAlign(FrameAlign);
8843       }
8844       if (Arg.hasAttribute(Attribute::Nest))
8845         Flags.setNest();
8846       if (NeedsRegBlock)
8847         Flags.setInConsecutiveRegs();
8848       Flags.setOrigAlign(OriginalAlignment);
8849       if (ArgCopyElisionCandidates.count(&Arg))
8850         Flags.setCopyElisionCandidate();
8851 
8852       MVT RegisterVT =
8853           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8854       unsigned NumRegs =
8855           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8856       for (unsigned i = 0; i != NumRegs; ++i) {
8857         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
8858                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
8859         if (NumRegs > 1 && i == 0)
8860           MyFlags.Flags.setSplit();
8861         // if it isn't first piece, alignment must be 1
8862         else if (i > 0) {
8863           MyFlags.Flags.setOrigAlign(1);
8864           if (i == NumRegs - 1)
8865             MyFlags.Flags.setSplitEnd();
8866         }
8867         Ins.push_back(MyFlags);
8868       }
8869       if (NeedsRegBlock && Value == NumValues - 1)
8870         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
8871       PartBase += VT.getStoreSize();
8872     }
8873   }
8874 
8875   // Call the target to set up the argument values.
8876   SmallVector<SDValue, 8> InVals;
8877   SDValue NewRoot = TLI->LowerFormalArguments(
8878       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
8879 
8880   // Verify that the target's LowerFormalArguments behaved as expected.
8881   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
8882          "LowerFormalArguments didn't return a valid chain!");
8883   assert(InVals.size() == Ins.size() &&
8884          "LowerFormalArguments didn't emit the correct number of values!");
8885   DEBUG({
8886       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
8887         assert(InVals[i].getNode() &&
8888                "LowerFormalArguments emitted a null value!");
8889         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
8890                "LowerFormalArguments emitted a value with the wrong type!");
8891       }
8892     });
8893 
8894   // Update the DAG with the new chain value resulting from argument lowering.
8895   DAG.setRoot(NewRoot);
8896 
8897   // Set up the argument values.
8898   unsigned i = 0;
8899   if (!FuncInfo->CanLowerReturn) {
8900     // Create a virtual register for the sret pointer, and put in a copy
8901     // from the sret argument into it.
8902     SmallVector<EVT, 1> ValueVTs;
8903     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8904                     F.getReturnType()->getPointerTo(
8905                         DAG.getDataLayout().getAllocaAddrSpace()),
8906                     ValueVTs);
8907     MVT VT = ValueVTs[0].getSimpleVT();
8908     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
8909     Optional<ISD::NodeType> AssertOp = None;
8910     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
8911                                         RegVT, VT, nullptr, AssertOp);
8912 
8913     MachineFunction& MF = SDB->DAG.getMachineFunction();
8914     MachineRegisterInfo& RegInfo = MF.getRegInfo();
8915     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
8916     FuncInfo->DemoteRegister = SRetReg;
8917     NewRoot =
8918         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
8919     DAG.setRoot(NewRoot);
8920 
8921     // i indexes lowered arguments.  Bump it past the hidden sret argument.
8922     ++i;
8923   }
8924 
8925   SmallVector<SDValue, 4> Chains;
8926   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
8927   for (const Argument &Arg : F.args()) {
8928     SmallVector<SDValue, 4> ArgValues;
8929     SmallVector<EVT, 4> ValueVTs;
8930     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8931     unsigned NumValues = ValueVTs.size();
8932     if (NumValues == 0)
8933       continue;
8934 
8935     bool ArgHasUses = !Arg.use_empty();
8936 
8937     // Elide the copying store if the target loaded this argument from a
8938     // suitable fixed stack object.
8939     if (Ins[i].Flags.isCopyElisionCandidate()) {
8940       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
8941                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
8942                              InVals[i], ArgHasUses);
8943     }
8944 
8945     // If this argument is unused then remember its value. It is used to generate
8946     // debugging information.
8947     bool isSwiftErrorArg =
8948         TLI->supportSwiftError() &&
8949         Arg.hasAttribute(Attribute::SwiftError);
8950     if (!ArgHasUses && !isSwiftErrorArg) {
8951       SDB->setUnusedArgValue(&Arg, InVals[i]);
8952 
8953       // Also remember any frame index for use in FastISel.
8954       if (FrameIndexSDNode *FI =
8955           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
8956         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8957     }
8958 
8959     for (unsigned Val = 0; Val != NumValues; ++Val) {
8960       EVT VT = ValueVTs[Val];
8961       MVT PartVT =
8962           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8963       unsigned NumParts =
8964           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8965 
8966       // Even an apparant 'unused' swifterror argument needs to be returned. So
8967       // we do generate a copy for it that can be used on return from the
8968       // function.
8969       if (ArgHasUses || isSwiftErrorArg) {
8970         Optional<ISD::NodeType> AssertOp;
8971         if (Arg.hasAttribute(Attribute::SExt))
8972           AssertOp = ISD::AssertSext;
8973         else if (Arg.hasAttribute(Attribute::ZExt))
8974           AssertOp = ISD::AssertZext;
8975 
8976         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
8977                                              PartVT, VT, nullptr, AssertOp,
8978                                              true));
8979       }
8980 
8981       i += NumParts;
8982     }
8983 
8984     // We don't need to do anything else for unused arguments.
8985     if (ArgValues.empty())
8986       continue;
8987 
8988     // Note down frame index.
8989     if (FrameIndexSDNode *FI =
8990         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
8991       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8992 
8993     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
8994                                      SDB->getCurSDLoc());
8995 
8996     SDB->setValue(&Arg, Res);
8997     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
8998       // We want to associate the argument with the frame index, among
8999       // involved operands, that correspond to the lowest address. The
9000       // getCopyFromParts function, called earlier, is swapping the order of
9001       // the operands to BUILD_PAIR depending on endianness. The result of
9002       // that swapping is that the least significant bits of the argument will
9003       // be in the first operand of the BUILD_PAIR node, and the most
9004       // significant bits will be in the second operand.
9005       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9006       if (LoadSDNode *LNode =
9007           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9008         if (FrameIndexSDNode *FI =
9009             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9010           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9011     }
9012 
9013     // Update the SwiftErrorVRegDefMap.
9014     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9015       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9016       if (TargetRegisterInfo::isVirtualRegister(Reg))
9017         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9018                                            FuncInfo->SwiftErrorArg, Reg);
9019     }
9020 
9021     // If this argument is live outside of the entry block, insert a copy from
9022     // wherever we got it to the vreg that other BB's will reference it as.
9023     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9024       // If we can, though, try to skip creating an unnecessary vreg.
9025       // FIXME: This isn't very clean... it would be nice to make this more
9026       // general.  It's also subtly incompatible with the hacks FastISel
9027       // uses with vregs.
9028       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9029       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9030         FuncInfo->ValueMap[&Arg] = Reg;
9031         continue;
9032       }
9033     }
9034     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9035       FuncInfo->InitializeRegForValue(&Arg);
9036       SDB->CopyToExportRegsIfNeeded(&Arg);
9037     }
9038   }
9039 
9040   if (!Chains.empty()) {
9041     Chains.push_back(NewRoot);
9042     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9043   }
9044 
9045   DAG.setRoot(NewRoot);
9046 
9047   assert(i == InVals.size() && "Argument register count mismatch!");
9048 
9049   // If any argument copy elisions occurred and we have debug info, update the
9050   // stale frame indices used in the dbg.declare variable info table.
9051   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9052   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9053     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9054       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9055       if (I != ArgCopyElisionFrameIndexMap.end())
9056         VI.Slot = I->second;
9057     }
9058   }
9059 
9060   // Finally, if the target has anything special to do, allow it to do so.
9061   EmitFunctionEntryCode();
9062 }
9063 
9064 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9065 /// ensure constants are generated when needed.  Remember the virtual registers
9066 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9067 /// directly add them, because expansion might result in multiple MBB's for one
9068 /// BB.  As such, the start of the BB might correspond to a different MBB than
9069 /// the end.
9070 void
9071 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9072   const TerminatorInst *TI = LLVMBB->getTerminator();
9073 
9074   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9075 
9076   // Check PHI nodes in successors that expect a value to be available from this
9077   // block.
9078   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9079     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9080     if (!isa<PHINode>(SuccBB->begin())) continue;
9081     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9082 
9083     // If this terminator has multiple identical successors (common for
9084     // switches), only handle each succ once.
9085     if (!SuccsHandled.insert(SuccMBB).second)
9086       continue;
9087 
9088     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9089 
9090     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9091     // nodes and Machine PHI nodes, but the incoming operands have not been
9092     // emitted yet.
9093     for (const PHINode &PN : SuccBB->phis()) {
9094       // Ignore dead phi's.
9095       if (PN.use_empty())
9096         continue;
9097 
9098       // Skip empty types
9099       if (PN.getType()->isEmptyTy())
9100         continue;
9101 
9102       unsigned Reg;
9103       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9104 
9105       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9106         unsigned &RegOut = ConstantsOut[C];
9107         if (RegOut == 0) {
9108           RegOut = FuncInfo.CreateRegs(C->getType());
9109           CopyValueToVirtualRegister(C, RegOut);
9110         }
9111         Reg = RegOut;
9112       } else {
9113         DenseMap<const Value *, unsigned>::iterator I =
9114           FuncInfo.ValueMap.find(PHIOp);
9115         if (I != FuncInfo.ValueMap.end())
9116           Reg = I->second;
9117         else {
9118           assert(isa<AllocaInst>(PHIOp) &&
9119                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9120                  "Didn't codegen value into a register!??");
9121           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9122           CopyValueToVirtualRegister(PHIOp, Reg);
9123         }
9124       }
9125 
9126       // Remember that this register needs to added to the machine PHI node as
9127       // the input for this MBB.
9128       SmallVector<EVT, 4> ValueVTs;
9129       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9130       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9131       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9132         EVT VT = ValueVTs[vti];
9133         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9134         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9135           FuncInfo.PHINodesToUpdate.push_back(
9136               std::make_pair(&*MBBI++, Reg + i));
9137         Reg += NumRegisters;
9138       }
9139     }
9140   }
9141 
9142   ConstantsOut.clear();
9143 }
9144 
9145 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9146 /// is 0.
9147 MachineBasicBlock *
9148 SelectionDAGBuilder::StackProtectorDescriptor::
9149 AddSuccessorMBB(const BasicBlock *BB,
9150                 MachineBasicBlock *ParentMBB,
9151                 bool IsLikely,
9152                 MachineBasicBlock *SuccMBB) {
9153   // If SuccBB has not been created yet, create it.
9154   if (!SuccMBB) {
9155     MachineFunction *MF = ParentMBB->getParent();
9156     MachineFunction::iterator BBI(ParentMBB);
9157     SuccMBB = MF->CreateMachineBasicBlock(BB);
9158     MF->insert(++BBI, SuccMBB);
9159   }
9160   // Add it as a successor of ParentMBB.
9161   ParentMBB->addSuccessor(
9162       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9163   return SuccMBB;
9164 }
9165 
9166 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9167   MachineFunction::iterator I(MBB);
9168   if (++I == FuncInfo.MF->end())
9169     return nullptr;
9170   return &*I;
9171 }
9172 
9173 /// During lowering new call nodes can be created (such as memset, etc.).
9174 /// Those will become new roots of the current DAG, but complications arise
9175 /// when they are tail calls. In such cases, the call lowering will update
9176 /// the root, but the builder still needs to know that a tail call has been
9177 /// lowered in order to avoid generating an additional return.
9178 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9179   // If the node is null, we do have a tail call.
9180   if (MaybeTC.getNode() != nullptr)
9181     DAG.setRoot(MaybeTC);
9182   else
9183     HasTailCall = true;
9184 }
9185 
9186 uint64_t
9187 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9188                                        unsigned First, unsigned Last) const {
9189   assert(Last >= First);
9190   const APInt &LowCase = Clusters[First].Low->getValue();
9191   const APInt &HighCase = Clusters[Last].High->getValue();
9192   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9193 
9194   // FIXME: A range of consecutive cases has 100% density, but only requires one
9195   // comparison to lower. We should discriminate against such consecutive ranges
9196   // in jump tables.
9197 
9198   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9199 }
9200 
9201 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9202     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9203     unsigned Last) const {
9204   assert(Last >= First);
9205   assert(TotalCases[Last] >= TotalCases[First]);
9206   uint64_t NumCases =
9207       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9208   return NumCases;
9209 }
9210 
9211 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9212                                          unsigned First, unsigned Last,
9213                                          const SwitchInst *SI,
9214                                          MachineBasicBlock *DefaultMBB,
9215                                          CaseCluster &JTCluster) {
9216   assert(First <= Last);
9217 
9218   auto Prob = BranchProbability::getZero();
9219   unsigned NumCmps = 0;
9220   std::vector<MachineBasicBlock*> Table;
9221   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9222 
9223   // Initialize probabilities in JTProbs.
9224   for (unsigned I = First; I <= Last; ++I)
9225     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9226 
9227   for (unsigned I = First; I <= Last; ++I) {
9228     assert(Clusters[I].Kind == CC_Range);
9229     Prob += Clusters[I].Prob;
9230     const APInt &Low = Clusters[I].Low->getValue();
9231     const APInt &High = Clusters[I].High->getValue();
9232     NumCmps += (Low == High) ? 1 : 2;
9233     if (I != First) {
9234       // Fill the gap between this and the previous cluster.
9235       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9236       assert(PreviousHigh.slt(Low));
9237       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9238       for (uint64_t J = 0; J < Gap; J++)
9239         Table.push_back(DefaultMBB);
9240     }
9241     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9242     for (uint64_t J = 0; J < ClusterSize; ++J)
9243       Table.push_back(Clusters[I].MBB);
9244     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9245   }
9246 
9247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9248   unsigned NumDests = JTProbs.size();
9249   if (TLI.isSuitableForBitTests(
9250           NumDests, NumCmps, Clusters[First].Low->getValue(),
9251           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9252     // Clusters[First..Last] should be lowered as bit tests instead.
9253     return false;
9254   }
9255 
9256   // Create the MBB that will load from and jump through the table.
9257   // Note: We create it here, but it's not inserted into the function yet.
9258   MachineFunction *CurMF = FuncInfo.MF;
9259   MachineBasicBlock *JumpTableMBB =
9260       CurMF->CreateMachineBasicBlock(SI->getParent());
9261 
9262   // Add successors. Note: use table order for determinism.
9263   SmallPtrSet<MachineBasicBlock *, 8> Done;
9264   for (MachineBasicBlock *Succ : Table) {
9265     if (Done.count(Succ))
9266       continue;
9267     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9268     Done.insert(Succ);
9269   }
9270   JumpTableMBB->normalizeSuccProbs();
9271 
9272   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9273                      ->createJumpTableIndex(Table);
9274 
9275   // Set up the jump table info.
9276   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9277   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9278                       Clusters[Last].High->getValue(), SI->getCondition(),
9279                       nullptr, false);
9280   JTCases.emplace_back(std::move(JTH), std::move(JT));
9281 
9282   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9283                                      JTCases.size() - 1, Prob);
9284   return true;
9285 }
9286 
9287 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9288                                          const SwitchInst *SI,
9289                                          MachineBasicBlock *DefaultMBB) {
9290 #ifndef NDEBUG
9291   // Clusters must be non-empty, sorted, and only contain Range clusters.
9292   assert(!Clusters.empty());
9293   for (CaseCluster &C : Clusters)
9294     assert(C.Kind == CC_Range);
9295   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9296     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9297 #endif
9298 
9299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9300   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9301     return;
9302 
9303   const int64_t N = Clusters.size();
9304   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9305   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9306 
9307   if (N < 2 || N < MinJumpTableEntries)
9308     return;
9309 
9310   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9311   SmallVector<unsigned, 8> TotalCases(N);
9312   for (unsigned i = 0; i < N; ++i) {
9313     const APInt &Hi = Clusters[i].High->getValue();
9314     const APInt &Lo = Clusters[i].Low->getValue();
9315     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9316     if (i != 0)
9317       TotalCases[i] += TotalCases[i - 1];
9318   }
9319 
9320   // Cheap case: the whole range may be suitable for jump table.
9321   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9322   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9323   assert(NumCases < UINT64_MAX / 100);
9324   assert(Range >= NumCases);
9325   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9326     CaseCluster JTCluster;
9327     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9328       Clusters[0] = JTCluster;
9329       Clusters.resize(1);
9330       return;
9331     }
9332   }
9333 
9334   // The algorithm below is not suitable for -O0.
9335   if (TM.getOptLevel() == CodeGenOpt::None)
9336     return;
9337 
9338   // Split Clusters into minimum number of dense partitions. The algorithm uses
9339   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9340   // for the Case Statement'" (1994), but builds the MinPartitions array in
9341   // reverse order to make it easier to reconstruct the partitions in ascending
9342   // order. In the choice between two optimal partitionings, it picks the one
9343   // which yields more jump tables.
9344 
9345   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9346   SmallVector<unsigned, 8> MinPartitions(N);
9347   // LastElement[i] is the last element of the partition starting at i.
9348   SmallVector<unsigned, 8> LastElement(N);
9349   // PartitionsScore[i] is used to break ties when choosing between two
9350   // partitionings resulting in the same number of partitions.
9351   SmallVector<unsigned, 8> PartitionsScore(N);
9352   // For PartitionsScore, a small number of comparisons is considered as good as
9353   // a jump table and a single comparison is considered better than a jump
9354   // table.
9355   enum PartitionScores : unsigned {
9356     NoTable = 0,
9357     Table = 1,
9358     FewCases = 1,
9359     SingleCase = 2
9360   };
9361 
9362   // Base case: There is only one way to partition Clusters[N-1].
9363   MinPartitions[N - 1] = 1;
9364   LastElement[N - 1] = N - 1;
9365   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9366 
9367   // Note: loop indexes are signed to avoid underflow.
9368   for (int64_t i = N - 2; i >= 0; i--) {
9369     // Find optimal partitioning of Clusters[i..N-1].
9370     // Baseline: Put Clusters[i] into a partition on its own.
9371     MinPartitions[i] = MinPartitions[i + 1] + 1;
9372     LastElement[i] = i;
9373     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9374 
9375     // Search for a solution that results in fewer partitions.
9376     for (int64_t j = N - 1; j > i; j--) {
9377       // Try building a partition from Clusters[i..j].
9378       uint64_t Range = getJumpTableRange(Clusters, i, j);
9379       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9380       assert(NumCases < UINT64_MAX / 100);
9381       assert(Range >= NumCases);
9382       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9383         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9384         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9385         int64_t NumEntries = j - i + 1;
9386 
9387         if (NumEntries == 1)
9388           Score += PartitionScores::SingleCase;
9389         else if (NumEntries <= SmallNumberOfEntries)
9390           Score += PartitionScores::FewCases;
9391         else if (NumEntries >= MinJumpTableEntries)
9392           Score += PartitionScores::Table;
9393 
9394         // If this leads to fewer partitions, or to the same number of
9395         // partitions with better score, it is a better partitioning.
9396         if (NumPartitions < MinPartitions[i] ||
9397             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9398           MinPartitions[i] = NumPartitions;
9399           LastElement[i] = j;
9400           PartitionsScore[i] = Score;
9401         }
9402       }
9403     }
9404   }
9405 
9406   // Iterate over the partitions, replacing some with jump tables in-place.
9407   unsigned DstIndex = 0;
9408   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9409     Last = LastElement[First];
9410     assert(Last >= First);
9411     assert(DstIndex <= First);
9412     unsigned NumClusters = Last - First + 1;
9413 
9414     CaseCluster JTCluster;
9415     if (NumClusters >= MinJumpTableEntries &&
9416         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9417       Clusters[DstIndex++] = JTCluster;
9418     } else {
9419       for (unsigned I = First; I <= Last; ++I)
9420         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9421     }
9422   }
9423   Clusters.resize(DstIndex);
9424 }
9425 
9426 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9427                                         unsigned First, unsigned Last,
9428                                         const SwitchInst *SI,
9429                                         CaseCluster &BTCluster) {
9430   assert(First <= Last);
9431   if (First == Last)
9432     return false;
9433 
9434   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9435   unsigned NumCmps = 0;
9436   for (int64_t I = First; I <= Last; ++I) {
9437     assert(Clusters[I].Kind == CC_Range);
9438     Dests.set(Clusters[I].MBB->getNumber());
9439     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9440   }
9441   unsigned NumDests = Dests.count();
9442 
9443   APInt Low = Clusters[First].Low->getValue();
9444   APInt High = Clusters[Last].High->getValue();
9445   assert(Low.slt(High));
9446 
9447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9448   const DataLayout &DL = DAG.getDataLayout();
9449   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9450     return false;
9451 
9452   APInt LowBound;
9453   APInt CmpRange;
9454 
9455   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9456   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9457          "Case range must fit in bit mask!");
9458 
9459   // Check if the clusters cover a contiguous range such that no value in the
9460   // range will jump to the default statement.
9461   bool ContiguousRange = true;
9462   for (int64_t I = First + 1; I <= Last; ++I) {
9463     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9464       ContiguousRange = false;
9465       break;
9466     }
9467   }
9468 
9469   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9470     // Optimize the case where all the case values fit in a word without having
9471     // to subtract minValue. In this case, we can optimize away the subtraction.
9472     LowBound = APInt::getNullValue(Low.getBitWidth());
9473     CmpRange = High;
9474     ContiguousRange = false;
9475   } else {
9476     LowBound = Low;
9477     CmpRange = High - Low;
9478   }
9479 
9480   CaseBitsVector CBV;
9481   auto TotalProb = BranchProbability::getZero();
9482   for (unsigned i = First; i <= Last; ++i) {
9483     // Find the CaseBits for this destination.
9484     unsigned j;
9485     for (j = 0; j < CBV.size(); ++j)
9486       if (CBV[j].BB == Clusters[i].MBB)
9487         break;
9488     if (j == CBV.size())
9489       CBV.push_back(
9490           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9491     CaseBits *CB = &CBV[j];
9492 
9493     // Update Mask, Bits and ExtraProb.
9494     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9495     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9496     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9497     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9498     CB->Bits += Hi - Lo + 1;
9499     CB->ExtraProb += Clusters[i].Prob;
9500     TotalProb += Clusters[i].Prob;
9501   }
9502 
9503   BitTestInfo BTI;
9504   llvm::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9505     // Sort by probability first, number of bits second, bit mask third.
9506     if (a.ExtraProb != b.ExtraProb)
9507       return a.ExtraProb > b.ExtraProb;
9508     if (a.Bits != b.Bits)
9509       return a.Bits > b.Bits;
9510     return a.Mask < b.Mask;
9511   });
9512 
9513   for (auto &CB : CBV) {
9514     MachineBasicBlock *BitTestBB =
9515         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9516     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9517   }
9518   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9519                             SI->getCondition(), -1U, MVT::Other, false,
9520                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9521                             TotalProb);
9522 
9523   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9524                                     BitTestCases.size() - 1, TotalProb);
9525   return true;
9526 }
9527 
9528 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9529                                               const SwitchInst *SI) {
9530 // Partition Clusters into as few subsets as possible, where each subset has a
9531 // range that fits in a machine word and has <= 3 unique destinations.
9532 
9533 #ifndef NDEBUG
9534   // Clusters must be sorted and contain Range or JumpTable clusters.
9535   assert(!Clusters.empty());
9536   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9537   for (const CaseCluster &C : Clusters)
9538     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9539   for (unsigned i = 1; i < Clusters.size(); ++i)
9540     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9541 #endif
9542 
9543   // The algorithm below is not suitable for -O0.
9544   if (TM.getOptLevel() == CodeGenOpt::None)
9545     return;
9546 
9547   // If target does not have legal shift left, do not emit bit tests at all.
9548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9549   const DataLayout &DL = DAG.getDataLayout();
9550 
9551   EVT PTy = TLI.getPointerTy(DL);
9552   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9553     return;
9554 
9555   int BitWidth = PTy.getSizeInBits();
9556   const int64_t N = Clusters.size();
9557 
9558   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9559   SmallVector<unsigned, 8> MinPartitions(N);
9560   // LastElement[i] is the last element of the partition starting at i.
9561   SmallVector<unsigned, 8> LastElement(N);
9562 
9563   // FIXME: This might not be the best algorithm for finding bit test clusters.
9564 
9565   // Base case: There is only one way to partition Clusters[N-1].
9566   MinPartitions[N - 1] = 1;
9567   LastElement[N - 1] = N - 1;
9568 
9569   // Note: loop indexes are signed to avoid underflow.
9570   for (int64_t i = N - 2; i >= 0; --i) {
9571     // Find optimal partitioning of Clusters[i..N-1].
9572     // Baseline: Put Clusters[i] into a partition on its own.
9573     MinPartitions[i] = MinPartitions[i + 1] + 1;
9574     LastElement[i] = i;
9575 
9576     // Search for a solution that results in fewer partitions.
9577     // Note: the search is limited by BitWidth, reducing time complexity.
9578     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9579       // Try building a partition from Clusters[i..j].
9580 
9581       // Check the range.
9582       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9583                                Clusters[j].High->getValue(), DL))
9584         continue;
9585 
9586       // Check nbr of destinations and cluster types.
9587       // FIXME: This works, but doesn't seem very efficient.
9588       bool RangesOnly = true;
9589       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9590       for (int64_t k = i; k <= j; k++) {
9591         if (Clusters[k].Kind != CC_Range) {
9592           RangesOnly = false;
9593           break;
9594         }
9595         Dests.set(Clusters[k].MBB->getNumber());
9596       }
9597       if (!RangesOnly || Dests.count() > 3)
9598         break;
9599 
9600       // Check if it's a better partition.
9601       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9602       if (NumPartitions < MinPartitions[i]) {
9603         // Found a better partition.
9604         MinPartitions[i] = NumPartitions;
9605         LastElement[i] = j;
9606       }
9607     }
9608   }
9609 
9610   // Iterate over the partitions, replacing with bit-test clusters in-place.
9611   unsigned DstIndex = 0;
9612   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9613     Last = LastElement[First];
9614     assert(First <= Last);
9615     assert(DstIndex <= First);
9616 
9617     CaseCluster BitTestCluster;
9618     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9619       Clusters[DstIndex++] = BitTestCluster;
9620     } else {
9621       size_t NumClusters = Last - First + 1;
9622       std::memmove(&Clusters[DstIndex], &Clusters[First],
9623                    sizeof(Clusters[0]) * NumClusters);
9624       DstIndex += NumClusters;
9625     }
9626   }
9627   Clusters.resize(DstIndex);
9628 }
9629 
9630 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9631                                         MachineBasicBlock *SwitchMBB,
9632                                         MachineBasicBlock *DefaultMBB) {
9633   MachineFunction *CurMF = FuncInfo.MF;
9634   MachineBasicBlock *NextMBB = nullptr;
9635   MachineFunction::iterator BBI(W.MBB);
9636   if (++BBI != FuncInfo.MF->end())
9637     NextMBB = &*BBI;
9638 
9639   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9640 
9641   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9642 
9643   if (Size == 2 && W.MBB == SwitchMBB) {
9644     // If any two of the cases has the same destination, and if one value
9645     // is the same as the other, but has one bit unset that the other has set,
9646     // use bit manipulation to do two compares at once.  For example:
9647     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9648     // TODO: This could be extended to merge any 2 cases in switches with 3
9649     // cases.
9650     // TODO: Handle cases where W.CaseBB != SwitchBB.
9651     CaseCluster &Small = *W.FirstCluster;
9652     CaseCluster &Big = *W.LastCluster;
9653 
9654     if (Small.Low == Small.High && Big.Low == Big.High &&
9655         Small.MBB == Big.MBB) {
9656       const APInt &SmallValue = Small.Low->getValue();
9657       const APInt &BigValue = Big.Low->getValue();
9658 
9659       // Check that there is only one bit different.
9660       APInt CommonBit = BigValue ^ SmallValue;
9661       if (CommonBit.isPowerOf2()) {
9662         SDValue CondLHS = getValue(Cond);
9663         EVT VT = CondLHS.getValueType();
9664         SDLoc DL = getCurSDLoc();
9665 
9666         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9667                                  DAG.getConstant(CommonBit, DL, VT));
9668         SDValue Cond = DAG.getSetCC(
9669             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9670             ISD::SETEQ);
9671 
9672         // Update successor info.
9673         // Both Small and Big will jump to Small.BB, so we sum up the
9674         // probabilities.
9675         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9676         if (BPI)
9677           addSuccessorWithProb(
9678               SwitchMBB, DefaultMBB,
9679               // The default destination is the first successor in IR.
9680               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9681         else
9682           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9683 
9684         // Insert the true branch.
9685         SDValue BrCond =
9686             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9687                         DAG.getBasicBlock(Small.MBB));
9688         // Insert the false branch.
9689         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9690                              DAG.getBasicBlock(DefaultMBB));
9691 
9692         DAG.setRoot(BrCond);
9693         return;
9694       }
9695     }
9696   }
9697 
9698   if (TM.getOptLevel() != CodeGenOpt::None) {
9699     // Here, we order cases by probability so the most likely case will be
9700     // checked first. However, two clusters can have the same probability in
9701     // which case their relative ordering is non-deterministic. So we use Low
9702     // as a tie-breaker as clusters are guaranteed to never overlap.
9703     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9704                [](const CaseCluster &a, const CaseCluster &b) {
9705       return a.Prob != b.Prob ?
9706              a.Prob > b.Prob :
9707              a.Low->getValue().slt(b.Low->getValue());
9708     });
9709 
9710     // Rearrange the case blocks so that the last one falls through if possible
9711     // without changing the order of probabilities.
9712     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9713       --I;
9714       if (I->Prob > W.LastCluster->Prob)
9715         break;
9716       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9717         std::swap(*I, *W.LastCluster);
9718         break;
9719       }
9720     }
9721   }
9722 
9723   // Compute total probability.
9724   BranchProbability DefaultProb = W.DefaultProb;
9725   BranchProbability UnhandledProbs = DefaultProb;
9726   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9727     UnhandledProbs += I->Prob;
9728 
9729   MachineBasicBlock *CurMBB = W.MBB;
9730   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9731     MachineBasicBlock *Fallthrough;
9732     if (I == W.LastCluster) {
9733       // For the last cluster, fall through to the default destination.
9734       Fallthrough = DefaultMBB;
9735     } else {
9736       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9737       CurMF->insert(BBI, Fallthrough);
9738       // Put Cond in a virtual register to make it available from the new blocks.
9739       ExportFromCurrentBlock(Cond);
9740     }
9741     UnhandledProbs -= I->Prob;
9742 
9743     switch (I->Kind) {
9744       case CC_JumpTable: {
9745         // FIXME: Optimize away range check based on pivot comparisons.
9746         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9747         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9748 
9749         // The jump block hasn't been inserted yet; insert it here.
9750         MachineBasicBlock *JumpMBB = JT->MBB;
9751         CurMF->insert(BBI, JumpMBB);
9752 
9753         auto JumpProb = I->Prob;
9754         auto FallthroughProb = UnhandledProbs;
9755 
9756         // If the default statement is a target of the jump table, we evenly
9757         // distribute the default probability to successors of CurMBB. Also
9758         // update the probability on the edge from JumpMBB to Fallthrough.
9759         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9760                                               SE = JumpMBB->succ_end();
9761              SI != SE; ++SI) {
9762           if (*SI == DefaultMBB) {
9763             JumpProb += DefaultProb / 2;
9764             FallthroughProb -= DefaultProb / 2;
9765             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9766             JumpMBB->normalizeSuccProbs();
9767             break;
9768           }
9769         }
9770 
9771         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9772         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9773         CurMBB->normalizeSuccProbs();
9774 
9775         // The jump table header will be inserted in our current block, do the
9776         // range check, and fall through to our fallthrough block.
9777         JTH->HeaderBB = CurMBB;
9778         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9779 
9780         // If we're in the right place, emit the jump table header right now.
9781         if (CurMBB == SwitchMBB) {
9782           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9783           JTH->Emitted = true;
9784         }
9785         break;
9786       }
9787       case CC_BitTests: {
9788         // FIXME: Optimize away range check based on pivot comparisons.
9789         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9790 
9791         // The bit test blocks haven't been inserted yet; insert them here.
9792         for (BitTestCase &BTC : BTB->Cases)
9793           CurMF->insert(BBI, BTC.ThisBB);
9794 
9795         // Fill in fields of the BitTestBlock.
9796         BTB->Parent = CurMBB;
9797         BTB->Default = Fallthrough;
9798 
9799         BTB->DefaultProb = UnhandledProbs;
9800         // If the cases in bit test don't form a contiguous range, we evenly
9801         // distribute the probability on the edge to Fallthrough to two
9802         // successors of CurMBB.
9803         if (!BTB->ContiguousRange) {
9804           BTB->Prob += DefaultProb / 2;
9805           BTB->DefaultProb -= DefaultProb / 2;
9806         }
9807 
9808         // If we're in the right place, emit the bit test header right now.
9809         if (CurMBB == SwitchMBB) {
9810           visitBitTestHeader(*BTB, SwitchMBB);
9811           BTB->Emitted = true;
9812         }
9813         break;
9814       }
9815       case CC_Range: {
9816         const Value *RHS, *LHS, *MHS;
9817         ISD::CondCode CC;
9818         if (I->Low == I->High) {
9819           // Check Cond == I->Low.
9820           CC = ISD::SETEQ;
9821           LHS = Cond;
9822           RHS=I->Low;
9823           MHS = nullptr;
9824         } else {
9825           // Check I->Low <= Cond <= I->High.
9826           CC = ISD::SETLE;
9827           LHS = I->Low;
9828           MHS = Cond;
9829           RHS = I->High;
9830         }
9831 
9832         // The false probability is the sum of all unhandled cases.
9833         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
9834                      getCurSDLoc(), I->Prob, UnhandledProbs);
9835 
9836         if (CurMBB == SwitchMBB)
9837           visitSwitchCase(CB, SwitchMBB);
9838         else
9839           SwitchCases.push_back(CB);
9840 
9841         break;
9842       }
9843     }
9844     CurMBB = Fallthrough;
9845   }
9846 }
9847 
9848 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
9849                                               CaseClusterIt First,
9850                                               CaseClusterIt Last) {
9851   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
9852     if (X.Prob != CC.Prob)
9853       return X.Prob > CC.Prob;
9854 
9855     // Ties are broken by comparing the case value.
9856     return X.Low->getValue().slt(CC.Low->getValue());
9857   });
9858 }
9859 
9860 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
9861                                         const SwitchWorkListItem &W,
9862                                         Value *Cond,
9863                                         MachineBasicBlock *SwitchMBB) {
9864   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
9865          "Clusters not sorted?");
9866 
9867   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
9868 
9869   // Balance the tree based on branch probabilities to create a near-optimal (in
9870   // terms of search time given key frequency) binary search tree. See e.g. Kurt
9871   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
9872   CaseClusterIt LastLeft = W.FirstCluster;
9873   CaseClusterIt FirstRight = W.LastCluster;
9874   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
9875   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
9876 
9877   // Move LastLeft and FirstRight towards each other from opposite directions to
9878   // find a partitioning of the clusters which balances the probability on both
9879   // sides. If LeftProb and RightProb are equal, alternate which side is
9880   // taken to ensure 0-probability nodes are distributed evenly.
9881   unsigned I = 0;
9882   while (LastLeft + 1 < FirstRight) {
9883     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
9884       LeftProb += (++LastLeft)->Prob;
9885     else
9886       RightProb += (--FirstRight)->Prob;
9887     I++;
9888   }
9889 
9890   while (true) {
9891     // Our binary search tree differs from a typical BST in that ours can have up
9892     // to three values in each leaf. The pivot selection above doesn't take that
9893     // into account, which means the tree might require more nodes and be less
9894     // efficient. We compensate for this here.
9895 
9896     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
9897     unsigned NumRight = W.LastCluster - FirstRight + 1;
9898 
9899     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
9900       // If one side has less than 3 clusters, and the other has more than 3,
9901       // consider taking a cluster from the other side.
9902 
9903       if (NumLeft < NumRight) {
9904         // Consider moving the first cluster on the right to the left side.
9905         CaseCluster &CC = *FirstRight;
9906         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9907         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9908         if (LeftSideRank <= RightSideRank) {
9909           // Moving the cluster to the left does not demote it.
9910           ++LastLeft;
9911           ++FirstRight;
9912           continue;
9913         }
9914       } else {
9915         assert(NumRight < NumLeft);
9916         // Consider moving the last element on the left to the right side.
9917         CaseCluster &CC = *LastLeft;
9918         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9919         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9920         if (RightSideRank <= LeftSideRank) {
9921           // Moving the cluster to the right does not demot it.
9922           --LastLeft;
9923           --FirstRight;
9924           continue;
9925         }
9926       }
9927     }
9928     break;
9929   }
9930 
9931   assert(LastLeft + 1 == FirstRight);
9932   assert(LastLeft >= W.FirstCluster);
9933   assert(FirstRight <= W.LastCluster);
9934 
9935   // Use the first element on the right as pivot since we will make less-than
9936   // comparisons against it.
9937   CaseClusterIt PivotCluster = FirstRight;
9938   assert(PivotCluster > W.FirstCluster);
9939   assert(PivotCluster <= W.LastCluster);
9940 
9941   CaseClusterIt FirstLeft = W.FirstCluster;
9942   CaseClusterIt LastRight = W.LastCluster;
9943 
9944   const ConstantInt *Pivot = PivotCluster->Low;
9945 
9946   // New blocks will be inserted immediately after the current one.
9947   MachineFunction::iterator BBI(W.MBB);
9948   ++BBI;
9949 
9950   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
9951   // we can branch to its destination directly if it's squeezed exactly in
9952   // between the known lower bound and Pivot - 1.
9953   MachineBasicBlock *LeftMBB;
9954   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
9955       FirstLeft->Low == W.GE &&
9956       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
9957     LeftMBB = FirstLeft->MBB;
9958   } else {
9959     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9960     FuncInfo.MF->insert(BBI, LeftMBB);
9961     WorkList.push_back(
9962         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
9963     // Put Cond in a virtual register to make it available from the new blocks.
9964     ExportFromCurrentBlock(Cond);
9965   }
9966 
9967   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
9968   // single cluster, RHS.Low == Pivot, and we can branch to its destination
9969   // directly if RHS.High equals the current upper bound.
9970   MachineBasicBlock *RightMBB;
9971   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
9972       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
9973     RightMBB = FirstRight->MBB;
9974   } else {
9975     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9976     FuncInfo.MF->insert(BBI, RightMBB);
9977     WorkList.push_back(
9978         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
9979     // Put Cond in a virtual register to make it available from the new blocks.
9980     ExportFromCurrentBlock(Cond);
9981   }
9982 
9983   // Create the CaseBlock record that will be used to lower the branch.
9984   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
9985                getCurSDLoc(), LeftProb, RightProb);
9986 
9987   if (W.MBB == SwitchMBB)
9988     visitSwitchCase(CB, SwitchMBB);
9989   else
9990     SwitchCases.push_back(CB);
9991 }
9992 
9993 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
9994 // from the swith statement.
9995 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
9996                                             BranchProbability PeeledCaseProb) {
9997   if (PeeledCaseProb == BranchProbability::getOne())
9998     return BranchProbability::getZero();
9999   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10000 
10001   uint32_t Numerator = CaseProb.getNumerator();
10002   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10003   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10004 }
10005 
10006 // Try to peel the top probability case if it exceeds the threshold.
10007 // Return current MachineBasicBlock for the switch statement if the peeling
10008 // does not occur.
10009 // If the peeling is performed, return the newly created MachineBasicBlock
10010 // for the peeled switch statement. Also update Clusters to remove the peeled
10011 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10012 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10013     const SwitchInst &SI, CaseClusterVector &Clusters,
10014     BranchProbability &PeeledCaseProb) {
10015   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10016   // Don't perform if there is only one cluster or optimizing for size.
10017   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10018       TM.getOptLevel() == CodeGenOpt::None ||
10019       SwitchMBB->getParent()->getFunction().optForMinSize())
10020     return SwitchMBB;
10021 
10022   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10023   unsigned PeeledCaseIndex = 0;
10024   bool SwitchPeeled = false;
10025   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10026     CaseCluster &CC = Clusters[Index];
10027     if (CC.Prob < TopCaseProb)
10028       continue;
10029     TopCaseProb = CC.Prob;
10030     PeeledCaseIndex = Index;
10031     SwitchPeeled = true;
10032   }
10033   if (!SwitchPeeled)
10034     return SwitchMBB;
10035 
10036   DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " << TopCaseProb
10037                << "\n");
10038 
10039   // Record the MBB for the peeled switch statement.
10040   MachineFunction::iterator BBI(SwitchMBB);
10041   ++BBI;
10042   MachineBasicBlock *PeeledSwitchMBB =
10043       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10044   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10045 
10046   ExportFromCurrentBlock(SI.getCondition());
10047   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10048   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10049                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10050   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10051 
10052   Clusters.erase(PeeledCaseIt);
10053   for (CaseCluster &CC : Clusters) {
10054     DEBUG(dbgs() << "Scale the probablity for one cluster, before scaling: "
10055                  << CC.Prob << "\n");
10056     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10057     DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10058   }
10059   PeeledCaseProb = TopCaseProb;
10060   return PeeledSwitchMBB;
10061 }
10062 
10063 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10064   // Extract cases from the switch.
10065   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10066   CaseClusterVector Clusters;
10067   Clusters.reserve(SI.getNumCases());
10068   for (auto I : SI.cases()) {
10069     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10070     const ConstantInt *CaseVal = I.getCaseValue();
10071     BranchProbability Prob =
10072         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10073             : BranchProbability(1, SI.getNumCases() + 1);
10074     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10075   }
10076 
10077   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10078 
10079   // Cluster adjacent cases with the same destination. We do this at all
10080   // optimization levels because it's cheap to do and will make codegen faster
10081   // if there are many clusters.
10082   sortAndRangeify(Clusters);
10083 
10084   if (TM.getOptLevel() != CodeGenOpt::None) {
10085     // Replace an unreachable default with the most popular destination.
10086     // FIXME: Exploit unreachable default more aggressively.
10087     bool UnreachableDefault =
10088         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10089     if (UnreachableDefault && !Clusters.empty()) {
10090       DenseMap<const BasicBlock *, unsigned> Popularity;
10091       unsigned MaxPop = 0;
10092       const BasicBlock *MaxBB = nullptr;
10093       for (auto I : SI.cases()) {
10094         const BasicBlock *BB = I.getCaseSuccessor();
10095         if (++Popularity[BB] > MaxPop) {
10096           MaxPop = Popularity[BB];
10097           MaxBB = BB;
10098         }
10099       }
10100       // Set new default.
10101       assert(MaxPop > 0 && MaxBB);
10102       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10103 
10104       // Remove cases that were pointing to the destination that is now the
10105       // default.
10106       CaseClusterVector New;
10107       New.reserve(Clusters.size());
10108       for (CaseCluster &CC : Clusters) {
10109         if (CC.MBB != DefaultMBB)
10110           New.push_back(CC);
10111       }
10112       Clusters = std::move(New);
10113     }
10114   }
10115 
10116   // The branch probablity of the peeled case.
10117   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10118   MachineBasicBlock *PeeledSwitchMBB =
10119       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10120 
10121   // If there is only the default destination, jump there directly.
10122   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10123   if (Clusters.empty()) {
10124     assert(PeeledSwitchMBB == SwitchMBB);
10125     SwitchMBB->addSuccessor(DefaultMBB);
10126     if (DefaultMBB != NextBlock(SwitchMBB)) {
10127       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10128                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10129     }
10130     return;
10131   }
10132 
10133   findJumpTables(Clusters, &SI, DefaultMBB);
10134   findBitTestClusters(Clusters, &SI);
10135 
10136   DEBUG({
10137     dbgs() << "Case clusters: ";
10138     for (const CaseCluster &C : Clusters) {
10139       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
10140       if (C.Kind == CC_BitTests) dbgs() << "BT:";
10141 
10142       C.Low->getValue().print(dbgs(), true);
10143       if (C.Low != C.High) {
10144         dbgs() << '-';
10145         C.High->getValue().print(dbgs(), true);
10146       }
10147       dbgs() << ' ';
10148     }
10149     dbgs() << '\n';
10150   });
10151 
10152   assert(!Clusters.empty());
10153   SwitchWorkList WorkList;
10154   CaseClusterIt First = Clusters.begin();
10155   CaseClusterIt Last = Clusters.end() - 1;
10156   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10157   // Scale the branchprobability for DefaultMBB if the peel occurs and
10158   // DefaultMBB is not replaced.
10159   if (PeeledCaseProb != BranchProbability::getZero() &&
10160       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10161     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10162   WorkList.push_back(
10163       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10164 
10165   while (!WorkList.empty()) {
10166     SwitchWorkListItem W = WorkList.back();
10167     WorkList.pop_back();
10168     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10169 
10170     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10171         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10172       // For optimized builds, lower large range as a balanced binary tree.
10173       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10174       continue;
10175     }
10176 
10177     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10178   }
10179 }
10180