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