xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 5182113f07baf2403801df8684391b096e356775)
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/MachineValueType.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/TargetFrameLowering.h"
60 #include "llvm/CodeGen/TargetInstrInfo.h"
61 #include "llvm/CodeGen/TargetLowering.h"
62 #include "llvm/CodeGen/TargetOpcodes.h"
63 #include "llvm/CodeGen/TargetRegisterInfo.h"
64 #include "llvm/CodeGen/TargetSubtargetInfo.h"
65 #include "llvm/CodeGen/ValueTypes.h"
66 #include "llvm/CodeGen/WinEHFuncInfo.h"
67 #include "llvm/IR/Argument.h"
68 #include "llvm/IR/Attributes.h"
69 #include "llvm/IR/BasicBlock.h"
70 #include "llvm/IR/CFG.h"
71 #include "llvm/IR/CallSite.h"
72 #include "llvm/IR/CallingConv.h"
73 #include "llvm/IR/Constant.h"
74 #include "llvm/IR/ConstantRange.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DataLayout.h"
77 #include "llvm/IR/DebugInfoMetadata.h"
78 #include "llvm/IR/DebugLoc.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/GetElementPtrTypeIterator.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/InstrTypes.h"
84 #include "llvm/IR/Instruction.h"
85 #include "llvm/IR/Instructions.h"
86 #include "llvm/IR/IntrinsicInst.h"
87 #include "llvm/IR/Intrinsics.h"
88 #include "llvm/IR/LLVMContext.h"
89 #include "llvm/IR/Metadata.h"
90 #include "llvm/IR/Module.h"
91 #include "llvm/IR/Operator.h"
92 #include "llvm/IR/Statepoint.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/User.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/MC/MCContext.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/Support/AtomicOrdering.h"
99 #include "llvm/Support/BranchProbability.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CodeGen.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstring>
116 #include <iterator>
117 #include <limits>
118 #include <numeric>
119 #include <tuple>
120 #include <utility>
121 #include <vector>
122 
123 using namespace llvm;
124 
125 #define DEBUG_TYPE "isel"
126 
127 /// LimitFloatPrecision - Generate low-precision inline sequences for
128 /// some float libcalls (6, 8 or 12 bits).
129 static unsigned LimitFloatPrecision;
130 
131 static cl::opt<unsigned, true>
132     LimitFPPrecision("limit-float-precision",
133                      cl::desc("Generate low-precision inline sequences "
134                               "for some float libcalls"),
135                      cl::location(LimitFloatPrecision), cl::Hidden,
136                      cl::init(0));
137 
138 static cl::opt<unsigned> SwitchPeelThreshold(
139     "switch-peel-threshold", cl::Hidden, cl::init(66),
140     cl::desc("Set the case probability threshold for peeling the case from a "
141              "switch statement. A value greater than 100 will void this "
142              "optimization"));
143 
144 // Limit the width of DAG chains. This is important in general to prevent
145 // DAG-based analysis from blowing up. For example, alias analysis and
146 // load clustering may not complete in reasonable time. It is difficult to
147 // recognize and avoid this situation within each individual analysis, and
148 // future analyses are likely to have the same behavior. Limiting DAG width is
149 // the safe approach and will be especially important with global DAGs.
150 //
151 // MaxParallelChains default is arbitrarily high to avoid affecting
152 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
153 // sequence over this should have been converted to llvm.memcpy by the
154 // frontend. It is easy to induce this behavior with .ll code such as:
155 // %buffer = alloca [4096 x i8]
156 // %data = load [4096 x i8]* %argPtr
157 // store [4096 x i8] %data, [4096 x i8]* %buffer
158 static const unsigned MaxParallelChains = 64;
159 
160 // True if the Value passed requires ABI mangling as it is a parameter to a
161 // function or a return value from a function which is not an intrinsic.
162 static bool isABIRegCopy(const Value *V) {
163   const bool IsRetInst = V && isa<ReturnInst>(V);
164   const bool IsCallInst = V && isa<CallInst>(V);
165   const bool IsInLineAsm =
166       IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm();
167   const bool IsIndirectFunctionCall =
168       IsCallInst && !IsInLineAsm &&
169       !static_cast<const CallInst *>(V)->getCalledFunction();
170   // It is possible that the call instruction is an inline asm statement or an
171   // indirect function call in which case the return value of
172   // getCalledFunction() would be nullptr.
173   const bool IsInstrinsicCall =
174       IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall &&
175       static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() !=
176           Intrinsic::not_intrinsic;
177 
178   return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall));
179 }
180 
181 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
182                                       const SDValue *Parts, unsigned NumParts,
183                                       MVT PartVT, EVT ValueVT, const Value *V,
184                                       bool IsABIRegCopy);
185 
186 /// getCopyFromParts - Create a value that contains the specified legal parts
187 /// combined into the value they represent.  If the parts combine to a type
188 /// larger than ValueVT then AssertOp can be used to specify whether the extra
189 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
190 /// (ISD::AssertSext).
191 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
192                                 const SDValue *Parts, unsigned NumParts,
193                                 MVT PartVT, EVT ValueVT, const Value *V,
194                                 Optional<ISD::NodeType> AssertOp = None,
195                                 bool IsABIRegCopy = false) {
196   if (ValueVT.isVector())
197     return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
198                                   PartVT, ValueVT, V, IsABIRegCopy);
199 
200   assert(NumParts > 0 && "No parts to assemble!");
201   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
202   SDValue Val = Parts[0];
203 
204   if (NumParts > 1) {
205     // Assemble the value from multiple parts.
206     if (ValueVT.isInteger()) {
207       unsigned PartBits = PartVT.getSizeInBits();
208       unsigned ValueBits = ValueVT.getSizeInBits();
209 
210       // Assemble the power of 2 part.
211       unsigned RoundParts = NumParts & (NumParts - 1) ?
212         1 << Log2_32(NumParts) : NumParts;
213       unsigned RoundBits = PartBits * RoundParts;
214       EVT RoundVT = RoundBits == ValueBits ?
215         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
216       SDValue Lo, Hi;
217 
218       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
219 
220       if (RoundParts > 2) {
221         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
222                               PartVT, HalfVT, V);
223         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
224                               RoundParts / 2, PartVT, HalfVT, V);
225       } else {
226         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
227         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
228       }
229 
230       if (DAG.getDataLayout().isBigEndian())
231         std::swap(Lo, Hi);
232 
233       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
234 
235       if (RoundParts < NumParts) {
236         // Assemble the trailing non-power-of-2 part.
237         unsigned OddParts = NumParts - RoundParts;
238         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
239         Hi = getCopyFromParts(DAG, DL,
240                               Parts + RoundParts, OddParts, PartVT, OddVT, V);
241 
242         // Combine the round and odd parts.
243         Lo = Val;
244         if (DAG.getDataLayout().isBigEndian())
245           std::swap(Lo, Hi);
246         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
247         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
248         Hi =
249             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
250                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
251                                         TLI.getPointerTy(DAG.getDataLayout())));
252         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
253         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
254       }
255     } else if (PartVT.isFloatingPoint()) {
256       // FP split into multiple FP parts (for ppcf128)
257       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
258              "Unexpected split");
259       SDValue Lo, Hi;
260       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
261       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
262       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
263         std::swap(Lo, Hi);
264       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
265     } else {
266       // FP split into integer parts (soft fp)
267       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
268              !PartVT.isVector() && "Unexpected split");
269       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
270       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
271     }
272   }
273 
274   // There is now one part, held in Val.  Correct it to match ValueVT.
275   // PartEVT is the type of the register class that holds the value.
276   // ValueVT is the type of the inline asm operation.
277   EVT PartEVT = Val.getValueType();
278 
279   if (PartEVT == ValueVT)
280     return Val;
281 
282   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
283       ValueVT.bitsLT(PartEVT)) {
284     // For an FP value in an integer part, we need to truncate to the right
285     // width first.
286     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
287     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
288   }
289 
290   // Handle types that have the same size.
291   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
292     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
293 
294   // Handle types with different sizes.
295   if (PartEVT.isInteger() && ValueVT.isInteger()) {
296     if (ValueVT.bitsLT(PartEVT)) {
297       // For a truncate, see if we have any information to
298       // indicate whether the truncated bits will always be
299       // zero or sign-extension.
300       if (AssertOp.hasValue())
301         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
302                           DAG.getValueType(ValueVT));
303       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
304     }
305     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
306   }
307 
308   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
309     // FP_ROUND's are always exact here.
310     if (ValueVT.bitsLT(Val.getValueType()))
311       return DAG.getNode(
312           ISD::FP_ROUND, DL, ValueVT, Val,
313           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
314 
315     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
316   }
317 
318   llvm_unreachable("Unknown mismatch!");
319 }
320 
321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
322                                               const Twine &ErrMsg) {
323   const Instruction *I = dyn_cast_or_null<Instruction>(V);
324   if (!V)
325     return Ctx.emitError(ErrMsg);
326 
327   const char *AsmError = ", possible invalid constraint for vector type";
328   if (const CallInst *CI = dyn_cast<CallInst>(I))
329     if (isa<InlineAsm>(CI->getCalledValue()))
330       return Ctx.emitError(I, ErrMsg + AsmError);
331 
332   return Ctx.emitError(I, ErrMsg);
333 }
334 
335 /// getCopyFromPartsVector - Create a value that contains the specified legal
336 /// parts combined into the value they represent.  If the parts combine to a
337 /// type larger than ValueVT then AssertOp can be used to specify whether the
338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
339 /// ValueVT (ISD::AssertSext).
340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
341                                       const SDValue *Parts, unsigned NumParts,
342                                       MVT PartVT, EVT ValueVT, const Value *V,
343                                       bool IsABIRegCopy) {
344   assert(ValueVT.isVector() && "Not a vector value");
345   assert(NumParts > 0 && "No parts to assemble!");
346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
347   SDValue Val = Parts[0];
348 
349   // Handle a multi-element vector.
350   if (NumParts > 1) {
351     EVT IntermediateVT;
352     MVT RegisterVT;
353     unsigned NumIntermediates;
354     unsigned NumRegs;
355 
356     if (IsABIRegCopy) {
357       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
358           *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
359           RegisterVT);
360     } else {
361       NumRegs =
362           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
363                                      NumIntermediates, RegisterVT);
364     }
365 
366     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
367     NumParts = NumRegs; // Silence a compiler warning.
368     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
369     assert(RegisterVT.getSizeInBits() ==
370            Parts[0].getSimpleValueType().getSizeInBits() &&
371            "Part type sizes don't match!");
372 
373     // Assemble the parts into intermediate operands.
374     SmallVector<SDValue, 8> Ops(NumIntermediates);
375     if (NumIntermediates == NumParts) {
376       // If the register was not expanded, truncate or copy the value,
377       // as appropriate.
378       for (unsigned i = 0; i != NumParts; ++i)
379         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
380                                   PartVT, IntermediateVT, V);
381     } else if (NumParts > 0) {
382       // If the intermediate type was expanded, build the intermediate
383       // operands from the parts.
384       assert(NumParts % NumIntermediates == 0 &&
385              "Must expand into a divisible number of parts!");
386       unsigned Factor = NumParts / NumIntermediates;
387       for (unsigned i = 0; i != NumIntermediates; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
389                                   PartVT, IntermediateVT, V);
390     }
391 
392     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
393     // intermediate operands.
394     EVT BuiltVectorTy =
395         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
396                          (IntermediateVT.isVector()
397                               ? IntermediateVT.getVectorNumElements() * NumParts
398                               : NumIntermediates));
399     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
400                                                 : ISD::BUILD_VECTOR,
401                       DL, BuiltVectorTy, Ops);
402   }
403 
404   // There is now one part, held in Val.  Correct it to match ValueVT.
405   EVT PartEVT = Val.getValueType();
406 
407   if (PartEVT == ValueVT)
408     return Val;
409 
410   if (PartEVT.isVector()) {
411     // If the element type of the source/dest vectors are the same, but the
412     // parts vector has more elements than the value vector, then we have a
413     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
414     // elements we want.
415     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
416       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
417              "Cannot narrow, it would be a lossy transformation");
418       return DAG.getNode(
419           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
420           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
421     }
422 
423     // Vector/Vector bitcast.
424     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
425       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
426 
427     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
428       "Cannot handle this kind of promotion");
429     // Promoted vector extract
430     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
431 
432   }
433 
434   // Trivial bitcast if the types are the same size and the destination
435   // vector type is legal.
436   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
437       TLI.isTypeLegal(ValueVT))
438     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
439 
440   if (ValueVT.getVectorNumElements() != 1) {
441      // Certain ABIs require that vectors are passed as integers. For vectors
442      // are the same size, this is an obvious bitcast.
443      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
444        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
445      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
446        // Bitcast Val back the original type and extract the corresponding
447        // vector we want.
448        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
449        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
450                                            ValueVT.getVectorElementType(), Elts);
451        Val = DAG.getBitcast(WiderVecType, Val);
452        return DAG.getNode(
453            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
454            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
455      }
456 
457      diagnosePossiblyInvalidConstraint(
458          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
459      return DAG.getUNDEF(ValueVT);
460   }
461 
462   // Handle cases such as i8 -> <1 x i1>
463   EVT ValueSVT = ValueVT.getVectorElementType();
464   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
465     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
466                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
467 
468   return DAG.getBuildVector(ValueVT, DL, Val);
469 }
470 
471 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
472                                  SDValue Val, SDValue *Parts, unsigned NumParts,
473                                  MVT PartVT, const Value *V, bool IsABIRegCopy);
474 
475 /// getCopyToParts - Create a series of nodes that contain the specified value
476 /// split into legal parts.  If the parts contain more bits than Val, then, for
477 /// integers, ExtendKind can be used to specify how to generate the extra bits.
478 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
479                            SDValue *Parts, unsigned NumParts, MVT PartVT,
480                            const Value *V,
481                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND,
482                            bool IsABIRegCopy = false) {
483   EVT ValueVT = Val.getValueType();
484 
485   // Handle the vector case separately.
486   if (ValueVT.isVector())
487     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
488                                 IsABIRegCopy);
489 
490   unsigned PartBits = PartVT.getSizeInBits();
491   unsigned OrigNumParts = NumParts;
492   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
493          "Copying to an illegal type!");
494 
495   if (NumParts == 0)
496     return;
497 
498   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
499   EVT PartEVT = PartVT;
500   if (PartEVT == ValueVT) {
501     assert(NumParts == 1 && "No-op copy with multiple parts!");
502     Parts[0] = Val;
503     return;
504   }
505 
506   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
507     // If the parts cover more bits than the value has, promote the value.
508     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
509       assert(NumParts == 1 && "Do not know what to promote to!");
510       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
511     } else {
512       if (ValueVT.isFloatingPoint()) {
513         // FP values need to be bitcast, then extended if they are being put
514         // into a larger container.
515         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
516         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
517       }
518       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
519              ValueVT.isInteger() &&
520              "Unknown mismatch!");
521       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
522       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
523       if (PartVT == MVT::x86mmx)
524         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525     }
526   } else if (PartBits == ValueVT.getSizeInBits()) {
527     // Different types of the same size.
528     assert(NumParts == 1 && PartEVT != ValueVT);
529     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
530   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
531     // If the parts cover less bits than value has, truncate the value.
532     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
533            ValueVT.isInteger() &&
534            "Unknown mismatch!");
535     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
536     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
537     if (PartVT == MVT::x86mmx)
538       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   }
540 
541   // The value may have changed - recompute ValueVT.
542   ValueVT = Val.getValueType();
543   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
544          "Failed to tile the value with PartVT!");
545 
546   if (NumParts == 1) {
547     if (PartEVT != ValueVT) {
548       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
549                                         "scalar-to-vector conversion failed");
550       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
551     }
552 
553     Parts[0] = Val;
554     return;
555   }
556 
557   // Expand the value into multiple parts.
558   if (NumParts & (NumParts - 1)) {
559     // The number of parts is not a power of 2.  Split off and copy the tail.
560     assert(PartVT.isInteger() && ValueVT.isInteger() &&
561            "Do not know what to expand to!");
562     unsigned RoundParts = 1 << Log2_32(NumParts);
563     unsigned RoundBits = RoundParts * PartBits;
564     unsigned OddParts = NumParts - RoundParts;
565     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
566                                  DAG.getIntPtrConstant(RoundBits, DL));
567     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
568 
569     if (DAG.getDataLayout().isBigEndian())
570       // The odd parts were reversed by getCopyToParts - unreverse them.
571       std::reverse(Parts + RoundParts, Parts + NumParts);
572 
573     NumParts = RoundParts;
574     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
575     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
576   }
577 
578   // The number of parts is a power of 2.  Repeatedly bisect the value using
579   // EXTRACT_ELEMENT.
580   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
581                          EVT::getIntegerVT(*DAG.getContext(),
582                                            ValueVT.getSizeInBits()),
583                          Val);
584 
585   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
586     for (unsigned i = 0; i < NumParts; i += StepSize) {
587       unsigned ThisBits = StepSize * PartBits / 2;
588       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
589       SDValue &Part0 = Parts[i];
590       SDValue &Part1 = Parts[i+StepSize/2];
591 
592       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
593                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
594       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
595                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
596 
597       if (ThisBits == PartBits && ThisVT != PartVT) {
598         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
599         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
600       }
601     }
602   }
603 
604   if (DAG.getDataLayout().isBigEndian())
605     std::reverse(Parts, Parts + OrigNumParts);
606 }
607 
608 
609 /// getCopyToPartsVector - Create a series of nodes that contain the specified
610 /// value split into legal parts.
611 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
612                                  SDValue Val, SDValue *Parts, unsigned NumParts,
613                                  MVT PartVT, const Value *V,
614                                  bool IsABIRegCopy) {
615   EVT ValueVT = Val.getValueType();
616   assert(ValueVT.isVector() && "Not a vector");
617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
618 
619   if (NumParts == 1) {
620     EVT PartEVT = PartVT;
621     if (PartEVT == ValueVT) {
622       // Nothing to do.
623     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
624       // Bitconvert vector->vector case.
625       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
626     } else if (PartVT.isVector() &&
627                PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
628                PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
629       EVT ElementVT = PartVT.getVectorElementType();
630       // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
631       // undef elements.
632       SmallVector<SDValue, 16> Ops;
633       for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
634         Ops.push_back(DAG.getNode(
635             ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
636             DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
637 
638       for (unsigned i = ValueVT.getVectorNumElements(),
639            e = PartVT.getVectorNumElements(); i != e; ++i)
640         Ops.push_back(DAG.getUNDEF(ElementVT));
641 
642       Val = DAG.getBuildVector(PartVT, DL, Ops);
643 
644       // FIXME: Use CONCAT for 2x -> 4x.
645 
646       //SDValue UndefElts = DAG.getUNDEF(VectorTy);
647       //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
648     } else if (PartVT.isVector() &&
649                PartEVT.getVectorElementType().bitsGE(
650                  ValueVT.getVectorElementType()) &&
651                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
652 
653       // Promoted vector extract
654       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
655     } else {
656       if (ValueVT.getVectorNumElements() == 1) {
657         Val = DAG.getNode(
658             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
659             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
660       } else {
661         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
662                "lossy conversion of vector to scalar type");
663         EVT IntermediateType =
664             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
665         Val = DAG.getBitcast(IntermediateType, Val);
666         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
667       }
668     }
669 
670     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
671     Parts[0] = Val;
672     return;
673   }
674 
675   // Handle a multi-element vector.
676   EVT IntermediateVT;
677   MVT RegisterVT;
678   unsigned NumIntermediates;
679   unsigned NumRegs;
680   if (IsABIRegCopy) {
681     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
682         *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates,
683         RegisterVT);
684   } else {
685     NumRegs =
686         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
687                                    NumIntermediates, RegisterVT);
688   }
689   unsigned NumElements = ValueVT.getVectorNumElements();
690 
691   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
692   NumParts = NumRegs; // Silence a compiler warning.
693   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
694 
695   // Convert the vector to the appropiate type if necessary.
696   unsigned DestVectorNoElts =
697       NumIntermediates *
698       (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1);
699   EVT BuiltVectorTy = EVT::getVectorVT(
700       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
701   if (Val.getValueType() != BuiltVectorTy)
702     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
703 
704   // Split the vector into intermediate operands.
705   SmallVector<SDValue, 8> Ops(NumIntermediates);
706   for (unsigned i = 0; i != NumIntermediates; ++i) {
707     if (IntermediateVT.isVector())
708       Ops[i] =
709           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
710                       DAG.getConstant(i * (NumElements / NumIntermediates), DL,
711                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
712     else
713       Ops[i] = DAG.getNode(
714           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
715           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
716   }
717 
718   // Split the intermediate operands into legal parts.
719   if (NumParts == NumIntermediates) {
720     // If the register was not expanded, promote or copy the value,
721     // as appropriate.
722     for (unsigned i = 0; i != NumParts; ++i)
723       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
724   } else if (NumParts > 0) {
725     // If the intermediate type was expanded, split each the value into
726     // legal parts.
727     assert(NumIntermediates != 0 && "division by zero");
728     assert(NumParts % NumIntermediates == 0 &&
729            "Must expand into a divisible number of parts!");
730     unsigned Factor = NumParts / NumIntermediates;
731     for (unsigned i = 0; i != NumIntermediates; ++i)
732       getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
733   }
734 }
735 
736 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
737                            EVT valuevt, bool IsABIMangledValue)
738     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
739       RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {}
740 
741 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
742                            const DataLayout &DL, unsigned Reg, Type *Ty,
743                            bool IsABIMangledValue) {
744   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
745 
746   IsABIMangled = IsABIMangledValue;
747 
748   for (EVT ValueVT : ValueVTs) {
749     unsigned NumRegs = IsABIMangledValue
750                            ? TLI.getNumRegistersForCallingConv(Context, ValueVT)
751                            : TLI.getNumRegisters(Context, ValueVT);
752     MVT RegisterVT = IsABIMangledValue
753                          ? TLI.getRegisterTypeForCallingConv(Context, ValueVT)
754                          : TLI.getRegisterType(Context, ValueVT);
755     for (unsigned i = 0; i != NumRegs; ++i)
756       Regs.push_back(Reg + i);
757     RegVTs.push_back(RegisterVT);
758     RegCount.push_back(NumRegs);
759     Reg += NumRegs;
760   }
761 }
762 
763 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
764                                       FunctionLoweringInfo &FuncInfo,
765                                       const SDLoc &dl, SDValue &Chain,
766                                       SDValue *Flag, const Value *V) const {
767   // A Value with type {} or [0 x %t] needs no registers.
768   if (ValueVTs.empty())
769     return SDValue();
770 
771   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
772 
773   // Assemble the legal parts into the final values.
774   SmallVector<SDValue, 4> Values(ValueVTs.size());
775   SmallVector<SDValue, 8> Parts;
776   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
777     // Copy the legal parts from the registers.
778     EVT ValueVT = ValueVTs[Value];
779     unsigned NumRegs = RegCount[Value];
780     MVT RegisterVT = IsABIMangled
781                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
782                          : RegVTs[Value];
783 
784     Parts.resize(NumRegs);
785     for (unsigned i = 0; i != NumRegs; ++i) {
786       SDValue P;
787       if (!Flag) {
788         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
789       } else {
790         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
791         *Flag = P.getValue(2);
792       }
793 
794       Chain = P.getValue(1);
795       Parts[i] = P;
796 
797       // If the source register was virtual and if we know something about it,
798       // add an assert node.
799       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
800           !RegisterVT.isInteger() || RegisterVT.isVector())
801         continue;
802 
803       const FunctionLoweringInfo::LiveOutInfo *LOI =
804         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
805       if (!LOI)
806         continue;
807 
808       unsigned RegSize = RegisterVT.getSizeInBits();
809       unsigned NumSignBits = LOI->NumSignBits;
810       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
811 
812       if (NumZeroBits == RegSize) {
813         // The current value is a zero.
814         // Explicitly express that as it would be easier for
815         // optimizations to kick in.
816         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
817         continue;
818       }
819 
820       // FIXME: We capture more information than the dag can represent.  For
821       // now, just use the tightest assertzext/assertsext possible.
822       bool isSExt = true;
823       EVT FromVT(MVT::Other);
824       if (NumSignBits == RegSize) {
825         isSExt = true;   // ASSERT SEXT 1
826         FromVT = MVT::i1;
827       } else if (NumZeroBits >= RegSize - 1) {
828         isSExt = false;  // ASSERT ZEXT 1
829         FromVT = MVT::i1;
830       } else if (NumSignBits > RegSize - 8) {
831         isSExt = true;   // ASSERT SEXT 8
832         FromVT = MVT::i8;
833       } else if (NumZeroBits >= RegSize - 8) {
834         isSExt = false;  // ASSERT ZEXT 8
835         FromVT = MVT::i8;
836       } else if (NumSignBits > RegSize - 16) {
837         isSExt = true;   // ASSERT SEXT 16
838         FromVT = MVT::i16;
839       } else if (NumZeroBits >= RegSize - 16) {
840         isSExt = false;  // ASSERT ZEXT 16
841         FromVT = MVT::i16;
842       } else if (NumSignBits > RegSize - 32) {
843         isSExt = true;   // ASSERT SEXT 32
844         FromVT = MVT::i32;
845       } else if (NumZeroBits >= RegSize - 32) {
846         isSExt = false;  // ASSERT ZEXT 32
847         FromVT = MVT::i32;
848       } else {
849         continue;
850       }
851       // Add an assertion node.
852       assert(FromVT != MVT::Other);
853       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
854                              RegisterVT, P, DAG.getValueType(FromVT));
855     }
856 
857     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
858                                      NumRegs, RegisterVT, ValueVT, V);
859     Part += NumRegs;
860     Parts.clear();
861   }
862 
863   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
864 }
865 
866 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
867                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
868                                  const Value *V,
869                                  ISD::NodeType PreferredExtendType) const {
870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
871   ISD::NodeType ExtendKind = PreferredExtendType;
872 
873   // Get the list of the values's legal parts.
874   unsigned NumRegs = Regs.size();
875   SmallVector<SDValue, 8> Parts(NumRegs);
876   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
877     unsigned NumParts = RegCount[Value];
878 
879     MVT RegisterVT = IsABIMangled
880                          ? TLI.getRegisterTypeForCallingConv(RegVTs[Value])
881                          : RegVTs[Value];
882 
883     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
884       ExtendKind = ISD::ZERO_EXTEND;
885 
886     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
887                    &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
888     Part += NumParts;
889   }
890 
891   // Copy the parts into the registers.
892   SmallVector<SDValue, 8> Chains(NumRegs);
893   for (unsigned i = 0; i != NumRegs; ++i) {
894     SDValue Part;
895     if (!Flag) {
896       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
897     } else {
898       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
899       *Flag = Part.getValue(1);
900     }
901 
902     Chains[i] = Part.getValue(0);
903   }
904 
905   if (NumRegs == 1 || Flag)
906     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
907     // flagged to it. That is the CopyToReg nodes and the user are considered
908     // a single scheduling unit. If we create a TokenFactor and return it as
909     // chain, then the TokenFactor is both a predecessor (operand) of the
910     // user as well as a successor (the TF operands are flagged to the user).
911     // c1, f1 = CopyToReg
912     // c2, f2 = CopyToReg
913     // c3     = TokenFactor c1, c2
914     // ...
915     //        = op c3, ..., f2
916     Chain = Chains[NumRegs-1];
917   else
918     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
919 }
920 
921 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
922                                         unsigned MatchingIdx, const SDLoc &dl,
923                                         SelectionDAG &DAG,
924                                         std::vector<SDValue> &Ops) const {
925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
926 
927   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
928   if (HasMatching)
929     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
930   else if (!Regs.empty() &&
931            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
932     // Put the register class of the virtual registers in the flag word.  That
933     // way, later passes can recompute register class constraints for inline
934     // assembly as well as normal instructions.
935     // Don't do this for tied operands that can use the regclass information
936     // from the def.
937     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
938     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
939     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
940   }
941 
942   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
943   Ops.push_back(Res);
944 
945   if (Code == InlineAsm::Kind_Clobber) {
946     // Clobbers should always have a 1:1 mapping with registers, and may
947     // reference registers that have illegal (e.g. vector) types. Hence, we
948     // shouldn't try to apply any sort of splitting logic to them.
949     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
950            "No 1:1 mapping from clobbers to regs?");
951     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
952     (void)SP;
953     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
954       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
955       assert(
956           (Regs[I] != SP ||
957            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
958           "If we clobbered the stack pointer, MFI should know about it.");
959     }
960     return;
961   }
962 
963   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
964     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
965     MVT RegisterVT = RegVTs[Value];
966     for (unsigned i = 0; i != NumRegs; ++i) {
967       assert(Reg < Regs.size() && "Mismatch in # registers expected");
968       unsigned TheReg = Regs[Reg++];
969       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
970     }
971   }
972 }
973 
974 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
975                                const TargetLibraryInfo *li) {
976   AA = aa;
977   GFI = gfi;
978   LibInfo = li;
979   DL = &DAG.getDataLayout();
980   Context = DAG.getContext();
981   LPadToCallSiteMap.clear();
982 }
983 
984 void SelectionDAGBuilder::clear() {
985   NodeMap.clear();
986   UnusedArgNodeMap.clear();
987   PendingLoads.clear();
988   PendingExports.clear();
989   CurInst = nullptr;
990   HasTailCall = false;
991   SDNodeOrder = LowestSDNodeOrder;
992   StatepointLowering.clear();
993 }
994 
995 void SelectionDAGBuilder::clearDanglingDebugInfo() {
996   DanglingDebugInfoMap.clear();
997 }
998 
999 SDValue SelectionDAGBuilder::getRoot() {
1000   if (PendingLoads.empty())
1001     return DAG.getRoot();
1002 
1003   if (PendingLoads.size() == 1) {
1004     SDValue Root = PendingLoads[0];
1005     DAG.setRoot(Root);
1006     PendingLoads.clear();
1007     return Root;
1008   }
1009 
1010   // Otherwise, we have to make a token factor node.
1011   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1012                              PendingLoads);
1013   PendingLoads.clear();
1014   DAG.setRoot(Root);
1015   return Root;
1016 }
1017 
1018 SDValue SelectionDAGBuilder::getControlRoot() {
1019   SDValue Root = DAG.getRoot();
1020 
1021   if (PendingExports.empty())
1022     return Root;
1023 
1024   // Turn all of the CopyToReg chains into one factored node.
1025   if (Root.getOpcode() != ISD::EntryToken) {
1026     unsigned i = 0, e = PendingExports.size();
1027     for (; i != e; ++i) {
1028       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1029       if (PendingExports[i].getNode()->getOperand(0) == Root)
1030         break;  // Don't add the root if we already indirectly depend on it.
1031     }
1032 
1033     if (i == e)
1034       PendingExports.push_back(Root);
1035   }
1036 
1037   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1038                      PendingExports);
1039   PendingExports.clear();
1040   DAG.setRoot(Root);
1041   return Root;
1042 }
1043 
1044 void SelectionDAGBuilder::visit(const Instruction &I) {
1045   // Set up outgoing PHI node register values before emitting the terminator.
1046   if (isa<TerminatorInst>(&I)) {
1047     HandlePHINodesInSuccessorBlocks(I.getParent());
1048   }
1049 
1050   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1051   if (!isa<DbgInfoIntrinsic>(I))
1052     ++SDNodeOrder;
1053 
1054   CurInst = &I;
1055 
1056   visit(I.getOpcode(), I);
1057 
1058   if (!isa<TerminatorInst>(&I) && !HasTailCall &&
1059       !isStatepoint(&I)) // statepoints handle their exports internally
1060     CopyToExportRegsIfNeeded(&I);
1061 
1062   CurInst = nullptr;
1063 }
1064 
1065 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1066   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1067 }
1068 
1069 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1070   // Note: this doesn't use InstVisitor, because it has to work with
1071   // ConstantExpr's in addition to instructions.
1072   switch (Opcode) {
1073   default: llvm_unreachable("Unknown instruction type encountered!");
1074     // Build the switch statement using the Instruction.def file.
1075 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1076     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1077 #include "llvm/IR/Instruction.def"
1078   }
1079 }
1080 
1081 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1082                                                 const DIExpression *Expr) {
1083   SmallVector<const Value *, 4> ToRemove;
1084   for (auto &DMI : DanglingDebugInfoMap) {
1085     DanglingDebugInfo &DDI = DMI.second;
1086     if (DDI.getDI()) {
1087       const DbgValueInst *DI = DDI.getDI();
1088       DIVariable *DanglingVariable = DI->getVariable();
1089       DIExpression *DanglingExpr = DI->getExpression();
1090       if (DanglingVariable == Variable &&
1091           Expr->fragmentsOverlap(DanglingExpr)) {
1092         DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1093         ToRemove.push_back(DMI.first);
1094       }
1095     }
1096   }
1097 
1098   for (auto V : ToRemove)
1099     DanglingDebugInfoMap[V] = DanglingDebugInfo();
1100 }
1101 
1102 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1103 // generate the debug data structures now that we've seen its definition.
1104 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1105                                                    SDValue Val) {
1106   DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
1107   if (!DDI.getDI())
1108     return;
1109   const DbgValueInst *DI = DDI.getDI();
1110   DebugLoc dl = DDI.getdl();
1111   unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1112   unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1113   DILocalVariable *Variable = DI->getVariable();
1114   DIExpression *Expr = DI->getExpression();
1115   assert(Variable->isValidLocationForIntrinsic(dl) &&
1116          "Expected inlined-at fields to agree");
1117   SDDbgValue *SDV;
1118   if (Val.getNode()) {
1119     if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1120       DEBUG(dbgs() << "Resolve dangling debug info [order=" << DbgSDNodeOrder
1121             << "] for:\n  " << *DI << "\n");
1122       DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1123       // Increase the SDNodeOrder for the DbgValue here to make sure it is
1124       // inserted after the definition of Val when emitting the instructions
1125       // after ISel. An alternative could be to teach
1126       // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1127       DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder)
1128               dbgs() << "changing SDNodeOrder from " << DbgSDNodeOrder
1129                      << " to " << ValSDNodeOrder << "\n");
1130       SDV = getDbgValue(Val, Variable, Expr, dl,
1131                         std::max(DbgSDNodeOrder, ValSDNodeOrder));
1132       DAG.AddDbgValue(SDV, Val.getNode(), false);
1133     } else
1134       DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1135             << "in EmitFuncArgumentDbgValue\n");
1136   } else
1137     DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1138   DanglingDebugInfoMap[V] = DanglingDebugInfo();
1139 }
1140 
1141 /// getCopyFromRegs - If there was virtual register allocated for the value V
1142 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1143 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1144   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1145   SDValue Result;
1146 
1147   if (It != FuncInfo.ValueMap.end()) {
1148     unsigned InReg = It->second;
1149 
1150     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1151                      DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V));
1152     SDValue Chain = DAG.getEntryNode();
1153     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1154                                  V);
1155     resolveDanglingDebugInfo(V, Result);
1156   }
1157 
1158   return Result;
1159 }
1160 
1161 /// getValue - Return an SDValue for the given Value.
1162 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1163   // If we already have an SDValue for this value, use it. It's important
1164   // to do this first, so that we don't create a CopyFromReg if we already
1165   // have a regular SDValue.
1166   SDValue &N = NodeMap[V];
1167   if (N.getNode()) return N;
1168 
1169   // If there's a virtual register allocated and initialized for this
1170   // value, use it.
1171   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1172     return copyFromReg;
1173 
1174   // Otherwise create a new SDValue and remember it.
1175   SDValue Val = getValueImpl(V);
1176   NodeMap[V] = Val;
1177   resolveDanglingDebugInfo(V, Val);
1178   return Val;
1179 }
1180 
1181 // Return true if SDValue exists for the given Value
1182 bool SelectionDAGBuilder::findValue(const Value *V) const {
1183   return (NodeMap.find(V) != NodeMap.end()) ||
1184     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1185 }
1186 
1187 /// getNonRegisterValue - Return an SDValue for the given Value, but
1188 /// don't look in FuncInfo.ValueMap for a virtual register.
1189 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1190   // If we already have an SDValue for this value, use it.
1191   SDValue &N = NodeMap[V];
1192   if (N.getNode()) {
1193     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1194       // Remove the debug location from the node as the node is about to be used
1195       // in a location which may differ from the original debug location.  This
1196       // is relevant to Constant and ConstantFP nodes because they can appear
1197       // as constant expressions inside PHI nodes.
1198       N->setDebugLoc(DebugLoc());
1199     }
1200     return N;
1201   }
1202 
1203   // Otherwise create a new SDValue and remember it.
1204   SDValue Val = getValueImpl(V);
1205   NodeMap[V] = Val;
1206   resolveDanglingDebugInfo(V, Val);
1207   return Val;
1208 }
1209 
1210 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1211 /// Create an SDValue for the given value.
1212 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1214 
1215   if (const Constant *C = dyn_cast<Constant>(V)) {
1216     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1217 
1218     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1219       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1220 
1221     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1222       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1223 
1224     if (isa<ConstantPointerNull>(C)) {
1225       unsigned AS = V->getType()->getPointerAddressSpace();
1226       return DAG.getConstant(0, getCurSDLoc(),
1227                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1228     }
1229 
1230     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1231       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1232 
1233     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1234       return DAG.getUNDEF(VT);
1235 
1236     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1237       visit(CE->getOpcode(), *CE);
1238       SDValue N1 = NodeMap[V];
1239       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1240       return N1;
1241     }
1242 
1243     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1244       SmallVector<SDValue, 4> Constants;
1245       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1246            OI != OE; ++OI) {
1247         SDNode *Val = getValue(*OI).getNode();
1248         // If the operand is an empty aggregate, there are no values.
1249         if (!Val) continue;
1250         // Add each leaf value from the operand to the Constants list
1251         // to form a flattened list of all the values.
1252         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1253           Constants.push_back(SDValue(Val, i));
1254       }
1255 
1256       return DAG.getMergeValues(Constants, getCurSDLoc());
1257     }
1258 
1259     if (const ConstantDataSequential *CDS =
1260           dyn_cast<ConstantDataSequential>(C)) {
1261       SmallVector<SDValue, 4> Ops;
1262       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1263         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1264         // Add each leaf value from the operand to the Constants list
1265         // to form a flattened list of all the values.
1266         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1267           Ops.push_back(SDValue(Val, i));
1268       }
1269 
1270       if (isa<ArrayType>(CDS->getType()))
1271         return DAG.getMergeValues(Ops, getCurSDLoc());
1272       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1273     }
1274 
1275     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1276       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1277              "Unknown struct or array constant!");
1278 
1279       SmallVector<EVT, 4> ValueVTs;
1280       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1281       unsigned NumElts = ValueVTs.size();
1282       if (NumElts == 0)
1283         return SDValue(); // empty struct
1284       SmallVector<SDValue, 4> Constants(NumElts);
1285       for (unsigned i = 0; i != NumElts; ++i) {
1286         EVT EltVT = ValueVTs[i];
1287         if (isa<UndefValue>(C))
1288           Constants[i] = DAG.getUNDEF(EltVT);
1289         else if (EltVT.isFloatingPoint())
1290           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1291         else
1292           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1293       }
1294 
1295       return DAG.getMergeValues(Constants, getCurSDLoc());
1296     }
1297 
1298     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1299       return DAG.getBlockAddress(BA, VT);
1300 
1301     VectorType *VecTy = cast<VectorType>(V->getType());
1302     unsigned NumElements = VecTy->getNumElements();
1303 
1304     // Now that we know the number and type of the elements, get that number of
1305     // elements into the Ops array based on what kind of constant it is.
1306     SmallVector<SDValue, 16> Ops;
1307     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1308       for (unsigned i = 0; i != NumElements; ++i)
1309         Ops.push_back(getValue(CV->getOperand(i)));
1310     } else {
1311       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1312       EVT EltVT =
1313           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1314 
1315       SDValue Op;
1316       if (EltVT.isFloatingPoint())
1317         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1318       else
1319         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1320       Ops.assign(NumElements, Op);
1321     }
1322 
1323     // Create a BUILD_VECTOR node.
1324     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1325   }
1326 
1327   // If this is a static alloca, generate it as the frameindex instead of
1328   // computation.
1329   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1330     DenseMap<const AllocaInst*, int>::iterator SI =
1331       FuncInfo.StaticAllocaMap.find(AI);
1332     if (SI != FuncInfo.StaticAllocaMap.end())
1333       return DAG.getFrameIndex(SI->second,
1334                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1335   }
1336 
1337   // If this is an instruction which fast-isel has deferred, select it now.
1338   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1339     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1340 
1341     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1342                      Inst->getType(), isABIRegCopy(V));
1343     SDValue Chain = DAG.getEntryNode();
1344     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1345   }
1346 
1347   llvm_unreachable("Can't get register for value!");
1348 }
1349 
1350 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1351   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1352   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1353   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1354   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1355   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1356   if (IsMSVCCXX || IsCoreCLR)
1357     CatchPadMBB->setIsEHFuncletEntry();
1358 
1359   DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot()));
1360 }
1361 
1362 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1363   // Update machine-CFG edge.
1364   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1365   FuncInfo.MBB->addSuccessor(TargetMBB);
1366 
1367   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1368   bool IsSEH = isAsynchronousEHPersonality(Pers);
1369   if (IsSEH) {
1370     // If this is not a fall-through branch or optimizations are switched off,
1371     // emit the branch.
1372     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1373         TM.getOptLevel() == CodeGenOpt::None)
1374       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1375                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1376     return;
1377   }
1378 
1379   // Figure out the funclet membership for the catchret's successor.
1380   // This will be used by the FuncletLayout pass to determine how to order the
1381   // BB's.
1382   // A 'catchret' returns to the outer scope's color.
1383   Value *ParentPad = I.getCatchSwitchParentPad();
1384   const BasicBlock *SuccessorColor;
1385   if (isa<ConstantTokenNone>(ParentPad))
1386     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1387   else
1388     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1389   assert(SuccessorColor && "No parent funclet for catchret!");
1390   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1391   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1392 
1393   // Create the terminator node.
1394   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1395                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1396                             DAG.getBasicBlock(SuccessorColorMBB));
1397   DAG.setRoot(Ret);
1398 }
1399 
1400 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1401   // Don't emit any special code for the cleanuppad instruction. It just marks
1402   // the start of a funclet.
1403   FuncInfo.MBB->setIsEHFuncletEntry();
1404   FuncInfo.MBB->setIsCleanupFuncletEntry();
1405 }
1406 
1407 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1408 /// many places it could ultimately go. In the IR, we have a single unwind
1409 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1410 /// This function skips over imaginary basic blocks that hold catchswitch
1411 /// instructions, and finds all the "real" machine
1412 /// basic block destinations. As those destinations may not be successors of
1413 /// EHPadBB, here we also calculate the edge probability to those destinations.
1414 /// The passed-in Prob is the edge probability to EHPadBB.
1415 static void findUnwindDestinations(
1416     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1417     BranchProbability Prob,
1418     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1419         &UnwindDests) {
1420   EHPersonality Personality =
1421     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1422   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1423   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1424 
1425   while (EHPadBB) {
1426     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1427     BasicBlock *NewEHPadBB = nullptr;
1428     if (isa<LandingPadInst>(Pad)) {
1429       // Stop on landingpads. They are not funclets.
1430       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1431       break;
1432     } else if (isa<CleanupPadInst>(Pad)) {
1433       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1434       // personalities.
1435       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1436       UnwindDests.back().first->setIsEHFuncletEntry();
1437       break;
1438     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1439       // Add the catchpad handlers to the possible destinations.
1440       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1441         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1442         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1443         if (IsMSVCCXX || IsCoreCLR)
1444           UnwindDests.back().first->setIsEHFuncletEntry();
1445       }
1446       NewEHPadBB = CatchSwitch->getUnwindDest();
1447     } else {
1448       continue;
1449     }
1450 
1451     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1452     if (BPI && NewEHPadBB)
1453       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1454     EHPadBB = NewEHPadBB;
1455   }
1456 }
1457 
1458 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1459   // Update successor info.
1460   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1461   auto UnwindDest = I.getUnwindDest();
1462   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1463   BranchProbability UnwindDestProb =
1464       (BPI && UnwindDest)
1465           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1466           : BranchProbability::getZero();
1467   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1468   for (auto &UnwindDest : UnwindDests) {
1469     UnwindDest.first->setIsEHPad();
1470     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1471   }
1472   FuncInfo.MBB->normalizeSuccProbs();
1473 
1474   // Create the terminator node.
1475   SDValue Ret =
1476       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1477   DAG.setRoot(Ret);
1478 }
1479 
1480 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1481   report_fatal_error("visitCatchSwitch not yet implemented!");
1482 }
1483 
1484 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1485   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1486   auto &DL = DAG.getDataLayout();
1487   SDValue Chain = getControlRoot();
1488   SmallVector<ISD::OutputArg, 8> Outs;
1489   SmallVector<SDValue, 8> OutVals;
1490 
1491   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1492   // lower
1493   //
1494   //   %val = call <ty> @llvm.experimental.deoptimize()
1495   //   ret <ty> %val
1496   //
1497   // differently.
1498   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1499     LowerDeoptimizingReturn();
1500     return;
1501   }
1502 
1503   if (!FuncInfo.CanLowerReturn) {
1504     unsigned DemoteReg = FuncInfo.DemoteRegister;
1505     const Function *F = I.getParent()->getParent();
1506 
1507     // Emit a store of the return value through the virtual register.
1508     // Leave Outs empty so that LowerReturn won't try to load return
1509     // registers the usual way.
1510     SmallVector<EVT, 1> PtrValueVTs;
1511     ComputeValueVTs(TLI, DL,
1512                     F->getReturnType()->getPointerTo(
1513                         DAG.getDataLayout().getAllocaAddrSpace()),
1514                     PtrValueVTs);
1515 
1516     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1517                                         DemoteReg, PtrValueVTs[0]);
1518     SDValue RetOp = getValue(I.getOperand(0));
1519 
1520     SmallVector<EVT, 4> ValueVTs;
1521     SmallVector<uint64_t, 4> Offsets;
1522     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1523     unsigned NumValues = ValueVTs.size();
1524 
1525     SmallVector<SDValue, 4> Chains(NumValues);
1526     for (unsigned i = 0; i != NumValues; ++i) {
1527       // An aggregate return value cannot wrap around the address space, so
1528       // offsets to its parts don't wrap either.
1529       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1530       Chains[i] = DAG.getStore(
1531           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1532           // FIXME: better loc info would be nice.
1533           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1534     }
1535 
1536     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1537                         MVT::Other, Chains);
1538   } else if (I.getNumOperands() != 0) {
1539     SmallVector<EVT, 4> ValueVTs;
1540     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1541     unsigned NumValues = ValueVTs.size();
1542     if (NumValues) {
1543       SDValue RetOp = getValue(I.getOperand(0));
1544 
1545       const Function *F = I.getParent()->getParent();
1546 
1547       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1548       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1549                                           Attribute::SExt))
1550         ExtendKind = ISD::SIGN_EXTEND;
1551       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1552                                                Attribute::ZExt))
1553         ExtendKind = ISD::ZERO_EXTEND;
1554 
1555       LLVMContext &Context = F->getContext();
1556       bool RetInReg = F->getAttributes().hasAttribute(
1557           AttributeList::ReturnIndex, Attribute::InReg);
1558 
1559       for (unsigned j = 0; j != NumValues; ++j) {
1560         EVT VT = ValueVTs[j];
1561 
1562         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1563           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1564 
1565         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT);
1566         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT);
1567         SmallVector<SDValue, 4> Parts(NumParts);
1568         getCopyToParts(DAG, getCurSDLoc(),
1569                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1570                        &Parts[0], NumParts, PartVT, &I, ExtendKind, true);
1571 
1572         // 'inreg' on function refers to return value
1573         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1574         if (RetInReg)
1575           Flags.setInReg();
1576 
1577         // Propagate extension type if any
1578         if (ExtendKind == ISD::SIGN_EXTEND)
1579           Flags.setSExt();
1580         else if (ExtendKind == ISD::ZERO_EXTEND)
1581           Flags.setZExt();
1582 
1583         for (unsigned i = 0; i < NumParts; ++i) {
1584           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1585                                         VT, /*isfixed=*/true, 0, 0));
1586           OutVals.push_back(Parts[i]);
1587         }
1588       }
1589     }
1590   }
1591 
1592   // Push in swifterror virtual register as the last element of Outs. This makes
1593   // sure swifterror virtual register will be returned in the swifterror
1594   // physical register.
1595   const Function *F = I.getParent()->getParent();
1596   if (TLI.supportSwiftError() &&
1597       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1598     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1599     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1600     Flags.setSwiftError();
1601     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1602                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1603                                   true /*isfixed*/, 1 /*origidx*/,
1604                                   0 /*partOffs*/));
1605     // Create SDNode for the swifterror virtual register.
1606     OutVals.push_back(
1607         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1608                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1609                         EVT(TLI.getPointerTy(DL))));
1610   }
1611 
1612   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1613   CallingConv::ID CallConv =
1614     DAG.getMachineFunction().getFunction().getCallingConv();
1615   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1616       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1617 
1618   // Verify that the target's LowerReturn behaved as expected.
1619   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1620          "LowerReturn didn't return a valid chain!");
1621 
1622   // Update the DAG with the new chain value resulting from return lowering.
1623   DAG.setRoot(Chain);
1624 }
1625 
1626 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1627 /// created for it, emit nodes to copy the value into the virtual
1628 /// registers.
1629 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1630   // Skip empty types
1631   if (V->getType()->isEmptyTy())
1632     return;
1633 
1634   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1635   if (VMI != FuncInfo.ValueMap.end()) {
1636     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1637     CopyValueToVirtualRegister(V, VMI->second);
1638   }
1639 }
1640 
1641 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1642 /// the current basic block, add it to ValueMap now so that we'll get a
1643 /// CopyTo/FromReg.
1644 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1645   // No need to export constants.
1646   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1647 
1648   // Already exported?
1649   if (FuncInfo.isExportedInst(V)) return;
1650 
1651   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1652   CopyValueToVirtualRegister(V, Reg);
1653 }
1654 
1655 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1656                                                      const BasicBlock *FromBB) {
1657   // The operands of the setcc have to be in this block.  We don't know
1658   // how to export them from some other block.
1659   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1660     // Can export from current BB.
1661     if (VI->getParent() == FromBB)
1662       return true;
1663 
1664     // Is already exported, noop.
1665     return FuncInfo.isExportedInst(V);
1666   }
1667 
1668   // If this is an argument, we can export it if the BB is the entry block or
1669   // if it is already exported.
1670   if (isa<Argument>(V)) {
1671     if (FromBB == &FromBB->getParent()->getEntryBlock())
1672       return true;
1673 
1674     // Otherwise, can only export this if it is already exported.
1675     return FuncInfo.isExportedInst(V);
1676   }
1677 
1678   // Otherwise, constants can always be exported.
1679   return true;
1680 }
1681 
1682 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1683 BranchProbability
1684 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1685                                         const MachineBasicBlock *Dst) const {
1686   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1687   const BasicBlock *SrcBB = Src->getBasicBlock();
1688   const BasicBlock *DstBB = Dst->getBasicBlock();
1689   if (!BPI) {
1690     // If BPI is not available, set the default probability as 1 / N, where N is
1691     // the number of successors.
1692     auto SuccSize = std::max<uint32_t>(
1693         std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1);
1694     return BranchProbability(1, SuccSize);
1695   }
1696   return BPI->getEdgeProbability(SrcBB, DstBB);
1697 }
1698 
1699 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1700                                                MachineBasicBlock *Dst,
1701                                                BranchProbability Prob) {
1702   if (!FuncInfo.BPI)
1703     Src->addSuccessorWithoutProb(Dst);
1704   else {
1705     if (Prob.isUnknown())
1706       Prob = getEdgeProbability(Src, Dst);
1707     Src->addSuccessor(Dst, Prob);
1708   }
1709 }
1710 
1711 static bool InBlock(const Value *V, const BasicBlock *BB) {
1712   if (const Instruction *I = dyn_cast<Instruction>(V))
1713     return I->getParent() == BB;
1714   return true;
1715 }
1716 
1717 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1718 /// This function emits a branch and is used at the leaves of an OR or an
1719 /// AND operator tree.
1720 void
1721 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1722                                                   MachineBasicBlock *TBB,
1723                                                   MachineBasicBlock *FBB,
1724                                                   MachineBasicBlock *CurBB,
1725                                                   MachineBasicBlock *SwitchBB,
1726                                                   BranchProbability TProb,
1727                                                   BranchProbability FProb,
1728                                                   bool InvertCond) {
1729   const BasicBlock *BB = CurBB->getBasicBlock();
1730 
1731   // If the leaf of the tree is a comparison, merge the condition into
1732   // the caseblock.
1733   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1734     // The operands of the cmp have to be in this block.  We don't know
1735     // how to export them from some other block.  If this is the first block
1736     // of the sequence, no exporting is needed.
1737     if (CurBB == SwitchBB ||
1738         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1739          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1740       ISD::CondCode Condition;
1741       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1742         ICmpInst::Predicate Pred =
1743             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1744         Condition = getICmpCondCode(Pred);
1745       } else {
1746         const FCmpInst *FC = cast<FCmpInst>(Cond);
1747         FCmpInst::Predicate Pred =
1748             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1749         Condition = getFCmpCondCode(Pred);
1750         if (TM.Options.NoNaNsFPMath)
1751           Condition = getFCmpCodeWithoutNaN(Condition);
1752       }
1753 
1754       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1755                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1756       SwitchCases.push_back(CB);
1757       return;
1758     }
1759   }
1760 
1761   // Create a CaseBlock record representing this branch.
1762   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1763   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1764                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1765   SwitchCases.push_back(CB);
1766 }
1767 
1768 /// FindMergedConditions - If Cond is an expression like
1769 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1770                                                MachineBasicBlock *TBB,
1771                                                MachineBasicBlock *FBB,
1772                                                MachineBasicBlock *CurBB,
1773                                                MachineBasicBlock *SwitchBB,
1774                                                Instruction::BinaryOps Opc,
1775                                                BranchProbability TProb,
1776                                                BranchProbability FProb,
1777                                                bool InvertCond) {
1778   // Skip over not part of the tree and remember to invert op and operands at
1779   // next level.
1780   if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) {
1781     const Value *CondOp = BinaryOperator::getNotArgument(Cond);
1782     if (InBlock(CondOp, CurBB->getBasicBlock())) {
1783       FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1784                            !InvertCond);
1785       return;
1786     }
1787   }
1788 
1789   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1790   // Compute the effective opcode for Cond, taking into account whether it needs
1791   // to be inverted, e.g.
1792   //   and (not (or A, B)), C
1793   // gets lowered as
1794   //   and (and (not A, not B), C)
1795   unsigned BOpc = 0;
1796   if (BOp) {
1797     BOpc = BOp->getOpcode();
1798     if (InvertCond) {
1799       if (BOpc == Instruction::And)
1800         BOpc = Instruction::Or;
1801       else if (BOpc == Instruction::Or)
1802         BOpc = Instruction::And;
1803     }
1804   }
1805 
1806   // If this node is not part of the or/and tree, emit it as a branch.
1807   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1808       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1809       BOp->getParent() != CurBB->getBasicBlock() ||
1810       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1811       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1812     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1813                                  TProb, FProb, InvertCond);
1814     return;
1815   }
1816 
1817   //  Create TmpBB after CurBB.
1818   MachineFunction::iterator BBI(CurBB);
1819   MachineFunction &MF = DAG.getMachineFunction();
1820   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1821   CurBB->getParent()->insert(++BBI, TmpBB);
1822 
1823   if (Opc == Instruction::Or) {
1824     // Codegen X | Y as:
1825     // BB1:
1826     //   jmp_if_X TBB
1827     //   jmp TmpBB
1828     // TmpBB:
1829     //   jmp_if_Y TBB
1830     //   jmp FBB
1831     //
1832 
1833     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1834     // The requirement is that
1835     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1836     //     = TrueProb for original BB.
1837     // Assuming the original probabilities are A and B, one choice is to set
1838     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1839     // A/(1+B) and 2B/(1+B). This choice assumes that
1840     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1841     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1842     // TmpBB, but the math is more complicated.
1843 
1844     auto NewTrueProb = TProb / 2;
1845     auto NewFalseProb = TProb / 2 + FProb;
1846     // Emit the LHS condition.
1847     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1848                          NewTrueProb, NewFalseProb, InvertCond);
1849 
1850     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1851     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1852     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1853     // Emit the RHS condition into TmpBB.
1854     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1855                          Probs[0], Probs[1], InvertCond);
1856   } else {
1857     assert(Opc == Instruction::And && "Unknown merge op!");
1858     // Codegen X & Y as:
1859     // BB1:
1860     //   jmp_if_X TmpBB
1861     //   jmp FBB
1862     // TmpBB:
1863     //   jmp_if_Y TBB
1864     //   jmp FBB
1865     //
1866     //  This requires creation of TmpBB after CurBB.
1867 
1868     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1869     // The requirement is that
1870     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1871     //     = FalseProb for original BB.
1872     // Assuming the original probabilities are A and B, one choice is to set
1873     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1874     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1875     // TrueProb for BB1 * FalseProb for TmpBB.
1876 
1877     auto NewTrueProb = TProb + FProb / 2;
1878     auto NewFalseProb = FProb / 2;
1879     // Emit the LHS condition.
1880     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1881                          NewTrueProb, NewFalseProb, InvertCond);
1882 
1883     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1884     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1885     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1886     // Emit the RHS condition into TmpBB.
1887     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1888                          Probs[0], Probs[1], InvertCond);
1889   }
1890 }
1891 
1892 /// If the set of cases should be emitted as a series of branches, return true.
1893 /// If we should emit this as a bunch of and/or'd together conditions, return
1894 /// false.
1895 bool
1896 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1897   if (Cases.size() != 2) return true;
1898 
1899   // If this is two comparisons of the same values or'd or and'd together, they
1900   // will get folded into a single comparison, so don't emit two blocks.
1901   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1902        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1903       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1904        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1905     return false;
1906   }
1907 
1908   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1909   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1910   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1911       Cases[0].CC == Cases[1].CC &&
1912       isa<Constant>(Cases[0].CmpRHS) &&
1913       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1914     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1915       return false;
1916     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1917       return false;
1918   }
1919 
1920   return true;
1921 }
1922 
1923 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1924   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1925 
1926   // Update machine-CFG edges.
1927   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1928 
1929   if (I.isUnconditional()) {
1930     // Update machine-CFG edges.
1931     BrMBB->addSuccessor(Succ0MBB);
1932 
1933     // If this is not a fall-through branch or optimizations are switched off,
1934     // emit the branch.
1935     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1936       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1937                               MVT::Other, getControlRoot(),
1938                               DAG.getBasicBlock(Succ0MBB)));
1939 
1940     return;
1941   }
1942 
1943   // If this condition is one of the special cases we handle, do special stuff
1944   // now.
1945   const Value *CondVal = I.getCondition();
1946   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1947 
1948   // If this is a series of conditions that are or'd or and'd together, emit
1949   // this as a sequence of branches instead of setcc's with and/or operations.
1950   // As long as jumps are not expensive, this should improve performance.
1951   // For example, instead of something like:
1952   //     cmp A, B
1953   //     C = seteq
1954   //     cmp D, E
1955   //     F = setle
1956   //     or C, F
1957   //     jnz foo
1958   // Emit:
1959   //     cmp A, B
1960   //     je foo
1961   //     cmp D, E
1962   //     jle foo
1963   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1964     Instruction::BinaryOps Opcode = BOp->getOpcode();
1965     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1966         !I.getMetadata(LLVMContext::MD_unpredictable) &&
1967         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1968       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1969                            Opcode,
1970                            getEdgeProbability(BrMBB, Succ0MBB),
1971                            getEdgeProbability(BrMBB, Succ1MBB),
1972                            /*InvertCond=*/false);
1973       // If the compares in later blocks need to use values not currently
1974       // exported from this block, export them now.  This block should always
1975       // be the first entry.
1976       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1977 
1978       // Allow some cases to be rejected.
1979       if (ShouldEmitAsBranches(SwitchCases)) {
1980         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1981           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1982           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1983         }
1984 
1985         // Emit the branch for this block.
1986         visitSwitchCase(SwitchCases[0], BrMBB);
1987         SwitchCases.erase(SwitchCases.begin());
1988         return;
1989       }
1990 
1991       // Okay, we decided not to do this, remove any inserted MBB's and clear
1992       // SwitchCases.
1993       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1994         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1995 
1996       SwitchCases.clear();
1997     }
1998   }
1999 
2000   // Create a CaseBlock record representing this branch.
2001   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2002                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2003 
2004   // Use visitSwitchCase to actually insert the fast branch sequence for this
2005   // cond branch.
2006   visitSwitchCase(CB, BrMBB);
2007 }
2008 
2009 /// visitSwitchCase - Emits the necessary code to represent a single node in
2010 /// the binary search tree resulting from lowering a switch instruction.
2011 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2012                                           MachineBasicBlock *SwitchBB) {
2013   SDValue Cond;
2014   SDValue CondLHS = getValue(CB.CmpLHS);
2015   SDLoc dl = CB.DL;
2016 
2017   // Build the setcc now.
2018   if (!CB.CmpMHS) {
2019     // Fold "(X == true)" to X and "(X == false)" to !X to
2020     // handle common cases produced by branch lowering.
2021     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2022         CB.CC == ISD::SETEQ)
2023       Cond = CondLHS;
2024     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2025              CB.CC == ISD::SETEQ) {
2026       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2027       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2028     } else
2029       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2030   } else {
2031     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2032 
2033     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2034     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2035 
2036     SDValue CmpOp = getValue(CB.CmpMHS);
2037     EVT VT = CmpOp.getValueType();
2038 
2039     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2040       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2041                           ISD::SETLE);
2042     } else {
2043       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2044                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2045       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2046                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2047     }
2048   }
2049 
2050   // Update successor info
2051   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2052   // TrueBB and FalseBB are always different unless the incoming IR is
2053   // degenerate. This only happens when running llc on weird IR.
2054   if (CB.TrueBB != CB.FalseBB)
2055     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2056   SwitchBB->normalizeSuccProbs();
2057 
2058   // If the lhs block is the next block, invert the condition so that we can
2059   // fall through to the lhs instead of the rhs block.
2060   if (CB.TrueBB == NextBlock(SwitchBB)) {
2061     std::swap(CB.TrueBB, CB.FalseBB);
2062     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2063     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2064   }
2065 
2066   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2067                                MVT::Other, getControlRoot(), Cond,
2068                                DAG.getBasicBlock(CB.TrueBB));
2069 
2070   // Insert the false branch. Do this even if it's a fall through branch,
2071   // this makes it easier to do DAG optimizations which require inverting
2072   // the branch condition.
2073   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2074                        DAG.getBasicBlock(CB.FalseBB));
2075 
2076   DAG.setRoot(BrCond);
2077 }
2078 
2079 /// visitJumpTable - Emit JumpTable node in the current MBB
2080 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2081   // Emit the code for the jump table
2082   assert(JT.Reg != -1U && "Should lower JT Header first!");
2083   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2084   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2085                                      JT.Reg, PTy);
2086   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2087   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2088                                     MVT::Other, Index.getValue(1),
2089                                     Table, Index);
2090   DAG.setRoot(BrJumpTable);
2091 }
2092 
2093 /// visitJumpTableHeader - This function emits necessary code to produce index
2094 /// in the JumpTable from switch case.
2095 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2096                                                JumpTableHeader &JTH,
2097                                                MachineBasicBlock *SwitchBB) {
2098   SDLoc dl = getCurSDLoc();
2099 
2100   // Subtract the lowest switch case value from the value being switched on and
2101   // conditional branch to default mbb if the result is greater than the
2102   // difference between smallest and largest cases.
2103   SDValue SwitchOp = getValue(JTH.SValue);
2104   EVT VT = SwitchOp.getValueType();
2105   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2106                             DAG.getConstant(JTH.First, dl, VT));
2107 
2108   // The SDNode we just created, which holds the value being switched on minus
2109   // the smallest case value, needs to be copied to a virtual register so it
2110   // can be used as an index into the jump table in a subsequent basic block.
2111   // This value may be smaller or larger than the target's pointer type, and
2112   // therefore require extension or truncating.
2113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2114   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2115 
2116   unsigned JumpTableReg =
2117       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2118   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2119                                     JumpTableReg, SwitchOp);
2120   JT.Reg = JumpTableReg;
2121 
2122   // Emit the range check for the jump table, and branch to the default block
2123   // for the switch statement if the value being switched on exceeds the largest
2124   // case in the switch.
2125   SDValue CMP = DAG.getSetCC(
2126       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2127                                  Sub.getValueType()),
2128       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2129 
2130   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2131                                MVT::Other, CopyTo, CMP,
2132                                DAG.getBasicBlock(JT.Default));
2133 
2134   // Avoid emitting unnecessary branches to the next block.
2135   if (JT.MBB != NextBlock(SwitchBB))
2136     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2137                          DAG.getBasicBlock(JT.MBB));
2138 
2139   DAG.setRoot(BrCond);
2140 }
2141 
2142 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2143 /// variable if there exists one.
2144 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2145                                  SDValue &Chain) {
2146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2147   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2148   MachineFunction &MF = DAG.getMachineFunction();
2149   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2150   MachineSDNode *Node =
2151       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2152   if (Global) {
2153     MachinePointerInfo MPInfo(Global);
2154     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
2155     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2156                  MachineMemOperand::MODereferenceable;
2157     *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8,
2158                                        DAG.getEVTAlignment(PtrTy));
2159     Node->setMemRefs(MemRefs, MemRefs + 1);
2160   }
2161   return SDValue(Node, 0);
2162 }
2163 
2164 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2165 /// tail spliced into a stack protector check success bb.
2166 ///
2167 /// For a high level explanation of how this fits into the stack protector
2168 /// generation see the comment on the declaration of class
2169 /// StackProtectorDescriptor.
2170 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2171                                                   MachineBasicBlock *ParentBB) {
2172 
2173   // First create the loads to the guard/stack slot for the comparison.
2174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2175   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2176 
2177   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2178   int FI = MFI.getStackProtectorIndex();
2179 
2180   SDValue Guard;
2181   SDLoc dl = getCurSDLoc();
2182   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2183   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2184   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2185 
2186   // Generate code to load the content of the guard slot.
2187   SDValue GuardVal = DAG.getLoad(
2188       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2189       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2190       MachineMemOperand::MOVolatile);
2191 
2192   if (TLI.useStackGuardXorFP())
2193     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2194 
2195   // Retrieve guard check function, nullptr if instrumentation is inlined.
2196   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2197     // The target provides a guard check function to validate the guard value.
2198     // Generate a call to that function with the content of the guard slot as
2199     // argument.
2200     auto *Fn = cast<Function>(GuardCheck);
2201     FunctionType *FnTy = Fn->getFunctionType();
2202     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2203 
2204     TargetLowering::ArgListTy Args;
2205     TargetLowering::ArgListEntry Entry;
2206     Entry.Node = GuardVal;
2207     Entry.Ty = FnTy->getParamType(0);
2208     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2209       Entry.IsInReg = true;
2210     Args.push_back(Entry);
2211 
2212     TargetLowering::CallLoweringInfo CLI(DAG);
2213     CLI.setDebugLoc(getCurSDLoc())
2214       .setChain(DAG.getEntryNode())
2215       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2216                  getValue(GuardCheck), std::move(Args));
2217 
2218     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2219     DAG.setRoot(Result.second);
2220     return;
2221   }
2222 
2223   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2224   // Otherwise, emit a volatile load to retrieve the stack guard value.
2225   SDValue Chain = DAG.getEntryNode();
2226   if (TLI.useLoadStackGuardNode()) {
2227     Guard = getLoadStackGuard(DAG, dl, Chain);
2228   } else {
2229     const Value *IRGuard = TLI.getSDagStackGuard(M);
2230     SDValue GuardPtr = getValue(IRGuard);
2231 
2232     Guard =
2233         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2234                     Align, MachineMemOperand::MOVolatile);
2235   }
2236 
2237   // Perform the comparison via a subtract/getsetcc.
2238   EVT VT = Guard.getValueType();
2239   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2240 
2241   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2242                                                         *DAG.getContext(),
2243                                                         Sub.getValueType()),
2244                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2245 
2246   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2247   // branch to failure MBB.
2248   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2249                                MVT::Other, GuardVal.getOperand(0),
2250                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2251   // Otherwise branch to success MBB.
2252   SDValue Br = DAG.getNode(ISD::BR, dl,
2253                            MVT::Other, BrCond,
2254                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2255 
2256   DAG.setRoot(Br);
2257 }
2258 
2259 /// Codegen the failure basic block for a stack protector check.
2260 ///
2261 /// A failure stack protector machine basic block consists simply of a call to
2262 /// __stack_chk_fail().
2263 ///
2264 /// For a high level explanation of how this fits into the stack protector
2265 /// generation see the comment on the declaration of class
2266 /// StackProtectorDescriptor.
2267 void
2268 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2270   SDValue Chain =
2271       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2272                       None, false, getCurSDLoc(), false, false).second;
2273   DAG.setRoot(Chain);
2274 }
2275 
2276 /// visitBitTestHeader - This function emits necessary code to produce value
2277 /// suitable for "bit tests"
2278 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2279                                              MachineBasicBlock *SwitchBB) {
2280   SDLoc dl = getCurSDLoc();
2281 
2282   // Subtract the minimum value
2283   SDValue SwitchOp = getValue(B.SValue);
2284   EVT VT = SwitchOp.getValueType();
2285   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2286                             DAG.getConstant(B.First, dl, VT));
2287 
2288   // Check range
2289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2290   SDValue RangeCmp = DAG.getSetCC(
2291       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2292                                  Sub.getValueType()),
2293       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2294 
2295   // Determine the type of the test operands.
2296   bool UsePtrType = false;
2297   if (!TLI.isTypeLegal(VT))
2298     UsePtrType = true;
2299   else {
2300     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2301       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2302         // Switch table case range are encoded into series of masks.
2303         // Just use pointer type, it's guaranteed to fit.
2304         UsePtrType = true;
2305         break;
2306       }
2307   }
2308   if (UsePtrType) {
2309     VT = TLI.getPointerTy(DAG.getDataLayout());
2310     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2311   }
2312 
2313   B.RegVT = VT.getSimpleVT();
2314   B.Reg = FuncInfo.CreateReg(B.RegVT);
2315   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2316 
2317   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2318 
2319   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2320   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2321   SwitchBB->normalizeSuccProbs();
2322 
2323   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2324                                 MVT::Other, CopyTo, RangeCmp,
2325                                 DAG.getBasicBlock(B.Default));
2326 
2327   // Avoid emitting unnecessary branches to the next block.
2328   if (MBB != NextBlock(SwitchBB))
2329     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2330                           DAG.getBasicBlock(MBB));
2331 
2332   DAG.setRoot(BrRange);
2333 }
2334 
2335 /// visitBitTestCase - this function produces one "bit test"
2336 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2337                                            MachineBasicBlock* NextMBB,
2338                                            BranchProbability BranchProbToNext,
2339                                            unsigned Reg,
2340                                            BitTestCase &B,
2341                                            MachineBasicBlock *SwitchBB) {
2342   SDLoc dl = getCurSDLoc();
2343   MVT VT = BB.RegVT;
2344   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2345   SDValue Cmp;
2346   unsigned PopCount = countPopulation(B.Mask);
2347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2348   if (PopCount == 1) {
2349     // Testing for a single bit; just compare the shift count with what it
2350     // would need to be to shift a 1 bit in that position.
2351     Cmp = DAG.getSetCC(
2352         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2353         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2354         ISD::SETEQ);
2355   } else if (PopCount == BB.Range) {
2356     // There is only one zero bit in the range, test for it directly.
2357     Cmp = DAG.getSetCC(
2358         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2359         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2360         ISD::SETNE);
2361   } else {
2362     // Make desired shift
2363     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2364                                     DAG.getConstant(1, dl, VT), ShiftOp);
2365 
2366     // Emit bit tests and jumps
2367     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2368                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2369     Cmp = DAG.getSetCC(
2370         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2371         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2372   }
2373 
2374   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2375   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2376   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2377   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2378   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2379   // one as they are relative probabilities (and thus work more like weights),
2380   // and hence we need to normalize them to let the sum of them become one.
2381   SwitchBB->normalizeSuccProbs();
2382 
2383   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2384                               MVT::Other, getControlRoot(),
2385                               Cmp, DAG.getBasicBlock(B.TargetBB));
2386 
2387   // Avoid emitting unnecessary branches to the next block.
2388   if (NextMBB != NextBlock(SwitchBB))
2389     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2390                         DAG.getBasicBlock(NextMBB));
2391 
2392   DAG.setRoot(BrAnd);
2393 }
2394 
2395 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2396   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2397 
2398   // Retrieve successors. Look through artificial IR level blocks like
2399   // catchswitch for successors.
2400   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2401   const BasicBlock *EHPadBB = I.getSuccessor(1);
2402 
2403   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2404   // have to do anything here to lower funclet bundles.
2405   assert(!I.hasOperandBundlesOtherThan(
2406              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2407          "Cannot lower invokes with arbitrary operand bundles yet!");
2408 
2409   const Value *Callee(I.getCalledValue());
2410   const Function *Fn = dyn_cast<Function>(Callee);
2411   if (isa<InlineAsm>(Callee))
2412     visitInlineAsm(&I);
2413   else if (Fn && Fn->isIntrinsic()) {
2414     switch (Fn->getIntrinsicID()) {
2415     default:
2416       llvm_unreachable("Cannot invoke this intrinsic");
2417     case Intrinsic::donothing:
2418       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2419       break;
2420     case Intrinsic::experimental_patchpoint_void:
2421     case Intrinsic::experimental_patchpoint_i64:
2422       visitPatchpoint(&I, EHPadBB);
2423       break;
2424     case Intrinsic::experimental_gc_statepoint:
2425       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2426       break;
2427     }
2428   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2429     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2430     // Eventually we will support lowering the @llvm.experimental.deoptimize
2431     // intrinsic, and right now there are no plans to support other intrinsics
2432     // with deopt state.
2433     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2434   } else {
2435     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2436   }
2437 
2438   // If the value of the invoke is used outside of its defining block, make it
2439   // available as a virtual register.
2440   // We already took care of the exported value for the statepoint instruction
2441   // during call to the LowerStatepoint.
2442   if (!isStatepoint(I)) {
2443     CopyToExportRegsIfNeeded(&I);
2444   }
2445 
2446   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2447   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2448   BranchProbability EHPadBBProb =
2449       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2450           : BranchProbability::getZero();
2451   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2452 
2453   // Update successor info.
2454   addSuccessorWithProb(InvokeMBB, Return);
2455   for (auto &UnwindDest : UnwindDests) {
2456     UnwindDest.first->setIsEHPad();
2457     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2458   }
2459   InvokeMBB->normalizeSuccProbs();
2460 
2461   // Drop into normal successor.
2462   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2463                           MVT::Other, getControlRoot(),
2464                           DAG.getBasicBlock(Return)));
2465 }
2466 
2467 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2468   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2469 }
2470 
2471 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2472   assert(FuncInfo.MBB->isEHPad() &&
2473          "Call to landingpad not in landing pad!");
2474 
2475   MachineBasicBlock *MBB = FuncInfo.MBB;
2476   addLandingPadInfo(LP, *MBB);
2477 
2478   // If there aren't registers to copy the values into (e.g., during SjLj
2479   // exceptions), then don't bother to create these DAG nodes.
2480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2481   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2482   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2483       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2484     return;
2485 
2486   // If landingpad's return type is token type, we don't create DAG nodes
2487   // for its exception pointer and selector value. The extraction of exception
2488   // pointer or selector value from token type landingpads is not currently
2489   // supported.
2490   if (LP.getType()->isTokenTy())
2491     return;
2492 
2493   SmallVector<EVT, 2> ValueVTs;
2494   SDLoc dl = getCurSDLoc();
2495   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2496   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2497 
2498   // Get the two live-in registers as SDValues. The physregs have already been
2499   // copied into virtual registers.
2500   SDValue Ops[2];
2501   if (FuncInfo.ExceptionPointerVirtReg) {
2502     Ops[0] = DAG.getZExtOrTrunc(
2503         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2504                            FuncInfo.ExceptionPointerVirtReg,
2505                            TLI.getPointerTy(DAG.getDataLayout())),
2506         dl, ValueVTs[0]);
2507   } else {
2508     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2509   }
2510   Ops[1] = DAG.getZExtOrTrunc(
2511       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2512                          FuncInfo.ExceptionSelectorVirtReg,
2513                          TLI.getPointerTy(DAG.getDataLayout())),
2514       dl, ValueVTs[1]);
2515 
2516   // Merge into one.
2517   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2518                             DAG.getVTList(ValueVTs), Ops);
2519   setValue(&LP, Res);
2520 }
2521 
2522 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2523 #ifndef NDEBUG
2524   for (const CaseCluster &CC : Clusters)
2525     assert(CC.Low == CC.High && "Input clusters must be single-case");
2526 #endif
2527 
2528   std::sort(Clusters.begin(), Clusters.end(),
2529             [](const CaseCluster &a, const CaseCluster &b) {
2530     return a.Low->getValue().slt(b.Low->getValue());
2531   });
2532 
2533   // Merge adjacent clusters with the same destination.
2534   const unsigned N = Clusters.size();
2535   unsigned DstIndex = 0;
2536   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2537     CaseCluster &CC = Clusters[SrcIndex];
2538     const ConstantInt *CaseVal = CC.Low;
2539     MachineBasicBlock *Succ = CC.MBB;
2540 
2541     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2542         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2543       // If this case has the same successor and is a neighbour, merge it into
2544       // the previous cluster.
2545       Clusters[DstIndex - 1].High = CaseVal;
2546       Clusters[DstIndex - 1].Prob += CC.Prob;
2547     } else {
2548       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2549                    sizeof(Clusters[SrcIndex]));
2550     }
2551   }
2552   Clusters.resize(DstIndex);
2553 }
2554 
2555 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2556                                            MachineBasicBlock *Last) {
2557   // Update JTCases.
2558   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2559     if (JTCases[i].first.HeaderBB == First)
2560       JTCases[i].first.HeaderBB = Last;
2561 
2562   // Update BitTestCases.
2563   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2564     if (BitTestCases[i].Parent == First)
2565       BitTestCases[i].Parent = Last;
2566 }
2567 
2568 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2569   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2570 
2571   // Update machine-CFG edges with unique successors.
2572   SmallSet<BasicBlock*, 32> Done;
2573   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2574     BasicBlock *BB = I.getSuccessor(i);
2575     bool Inserted = Done.insert(BB).second;
2576     if (!Inserted)
2577         continue;
2578 
2579     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2580     addSuccessorWithProb(IndirectBrMBB, Succ);
2581   }
2582   IndirectBrMBB->normalizeSuccProbs();
2583 
2584   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2585                           MVT::Other, getControlRoot(),
2586                           getValue(I.getAddress())));
2587 }
2588 
2589 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2590   if (DAG.getTarget().Options.TrapUnreachable)
2591     DAG.setRoot(
2592         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2593 }
2594 
2595 void SelectionDAGBuilder::visitFSub(const User &I) {
2596   // -0.0 - X --> fneg
2597   Type *Ty = I.getType();
2598   if (isa<Constant>(I.getOperand(0)) &&
2599       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2600     SDValue Op2 = getValue(I.getOperand(1));
2601     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2602                              Op2.getValueType(), Op2));
2603     return;
2604   }
2605 
2606   visitBinary(I, ISD::FSUB);
2607 }
2608 
2609 /// Checks if the given instruction performs a vector reduction, in which case
2610 /// we have the freedom to alter the elements in the result as long as the
2611 /// reduction of them stays unchanged.
2612 static bool isVectorReductionOp(const User *I) {
2613   const Instruction *Inst = dyn_cast<Instruction>(I);
2614   if (!Inst || !Inst->getType()->isVectorTy())
2615     return false;
2616 
2617   auto OpCode = Inst->getOpcode();
2618   switch (OpCode) {
2619   case Instruction::Add:
2620   case Instruction::Mul:
2621   case Instruction::And:
2622   case Instruction::Or:
2623   case Instruction::Xor:
2624     break;
2625   case Instruction::FAdd:
2626   case Instruction::FMul:
2627     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2628       if (FPOp->getFastMathFlags().isFast())
2629         break;
2630     LLVM_FALLTHROUGH;
2631   default:
2632     return false;
2633   }
2634 
2635   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2636   unsigned ElemNumToReduce = ElemNum;
2637 
2638   // Do DFS search on the def-use chain from the given instruction. We only
2639   // allow four kinds of operations during the search until we reach the
2640   // instruction that extracts the first element from the vector:
2641   //
2642   //   1. The reduction operation of the same opcode as the given instruction.
2643   //
2644   //   2. PHI node.
2645   //
2646   //   3. ShuffleVector instruction together with a reduction operation that
2647   //      does a partial reduction.
2648   //
2649   //   4. ExtractElement that extracts the first element from the vector, and we
2650   //      stop searching the def-use chain here.
2651   //
2652   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2653   // from 1-3 to the stack to continue the DFS. The given instruction is not
2654   // a reduction operation if we meet any other instructions other than those
2655   // listed above.
2656 
2657   SmallVector<const User *, 16> UsersToVisit{Inst};
2658   SmallPtrSet<const User *, 16> Visited;
2659   bool ReduxExtracted = false;
2660 
2661   while (!UsersToVisit.empty()) {
2662     auto User = UsersToVisit.back();
2663     UsersToVisit.pop_back();
2664     if (!Visited.insert(User).second)
2665       continue;
2666 
2667     for (const auto &U : User->users()) {
2668       auto Inst = dyn_cast<Instruction>(U);
2669       if (!Inst)
2670         return false;
2671 
2672       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2673         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2674           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2675             return false;
2676         UsersToVisit.push_back(U);
2677       } else if (const ShuffleVectorInst *ShufInst =
2678                      dyn_cast<ShuffleVectorInst>(U)) {
2679         // Detect the following pattern: A ShuffleVector instruction together
2680         // with a reduction that do partial reduction on the first and second
2681         // ElemNumToReduce / 2 elements, and store the result in
2682         // ElemNumToReduce / 2 elements in another vector.
2683 
2684         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2685         if (ResultElements < ElemNum)
2686           return false;
2687 
2688         if (ElemNumToReduce == 1)
2689           return false;
2690         if (!isa<UndefValue>(U->getOperand(1)))
2691           return false;
2692         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2693           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2694             return false;
2695         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2696           if (ShufInst->getMaskValue(i) != -1)
2697             return false;
2698 
2699         // There is only one user of this ShuffleVector instruction, which
2700         // must be a reduction operation.
2701         if (!U->hasOneUse())
2702           return false;
2703 
2704         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2705         if (!U2 || U2->getOpcode() != OpCode)
2706           return false;
2707 
2708         // Check operands of the reduction operation.
2709         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2710             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2711           UsersToVisit.push_back(U2);
2712           ElemNumToReduce /= 2;
2713         } else
2714           return false;
2715       } else if (isa<ExtractElementInst>(U)) {
2716         // At this moment we should have reduced all elements in the vector.
2717         if (ElemNumToReduce != 1)
2718           return false;
2719 
2720         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2721         if (!Val || Val->getZExtValue() != 0)
2722           return false;
2723 
2724         ReduxExtracted = true;
2725       } else
2726         return false;
2727     }
2728   }
2729   return ReduxExtracted;
2730 }
2731 
2732 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2733   SDValue Op1 = getValue(I.getOperand(0));
2734   SDValue Op2 = getValue(I.getOperand(1));
2735 
2736   bool nuw = false;
2737   bool nsw = false;
2738   bool exact = false;
2739   bool vec_redux = false;
2740   FastMathFlags FMF;
2741 
2742   if (const OverflowingBinaryOperator *OFBinOp =
2743           dyn_cast<const OverflowingBinaryOperator>(&I)) {
2744     nuw = OFBinOp->hasNoUnsignedWrap();
2745     nsw = OFBinOp->hasNoSignedWrap();
2746   }
2747   if (const PossiblyExactOperator *ExactOp =
2748           dyn_cast<const PossiblyExactOperator>(&I))
2749     exact = ExactOp->isExact();
2750   if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2751     FMF = FPOp->getFastMathFlags();
2752 
2753   if (isVectorReductionOp(&I)) {
2754     vec_redux = true;
2755     DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2756   }
2757 
2758   SDNodeFlags Flags;
2759   Flags.setExact(exact);
2760   Flags.setNoSignedWrap(nsw);
2761   Flags.setNoUnsignedWrap(nuw);
2762   Flags.setVectorReduction(vec_redux);
2763   Flags.setAllowReciprocal(FMF.allowReciprocal());
2764   Flags.setAllowContract(FMF.allowContract());
2765   Flags.setNoInfs(FMF.noInfs());
2766   Flags.setNoNaNs(FMF.noNaNs());
2767   Flags.setNoSignedZeros(FMF.noSignedZeros());
2768   Flags.setUnsafeAlgebra(FMF.isFast());
2769 
2770   SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2771                                      Op1, Op2, Flags);
2772   setValue(&I, BinNodeValue);
2773 }
2774 
2775 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2776   SDValue Op1 = getValue(I.getOperand(0));
2777   SDValue Op2 = getValue(I.getOperand(1));
2778 
2779   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2780       Op2.getValueType(), DAG.getDataLayout());
2781 
2782   // Coerce the shift amount to the right type if we can.
2783   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2784     unsigned ShiftSize = ShiftTy.getSizeInBits();
2785     unsigned Op2Size = Op2.getValueSizeInBits();
2786     SDLoc DL = getCurSDLoc();
2787 
2788     // If the operand is smaller than the shift count type, promote it.
2789     if (ShiftSize > Op2Size)
2790       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2791 
2792     // If the operand is larger than the shift count type but the shift
2793     // count type has enough bits to represent any shift value, truncate
2794     // it now. This is a common case and it exposes the truncate to
2795     // optimization early.
2796     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2797       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2798     // Otherwise we'll need to temporarily settle for some other convenient
2799     // type.  Type legalization will make adjustments once the shiftee is split.
2800     else
2801       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2802   }
2803 
2804   bool nuw = false;
2805   bool nsw = false;
2806   bool exact = false;
2807 
2808   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2809 
2810     if (const OverflowingBinaryOperator *OFBinOp =
2811             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2812       nuw = OFBinOp->hasNoUnsignedWrap();
2813       nsw = OFBinOp->hasNoSignedWrap();
2814     }
2815     if (const PossiblyExactOperator *ExactOp =
2816             dyn_cast<const PossiblyExactOperator>(&I))
2817       exact = ExactOp->isExact();
2818   }
2819   SDNodeFlags Flags;
2820   Flags.setExact(exact);
2821   Flags.setNoSignedWrap(nsw);
2822   Flags.setNoUnsignedWrap(nuw);
2823   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2824                             Flags);
2825   setValue(&I, Res);
2826 }
2827 
2828 void SelectionDAGBuilder::visitSDiv(const User &I) {
2829   SDValue Op1 = getValue(I.getOperand(0));
2830   SDValue Op2 = getValue(I.getOperand(1));
2831 
2832   SDNodeFlags Flags;
2833   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2834                  cast<PossiblyExactOperator>(&I)->isExact());
2835   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2836                            Op2, Flags));
2837 }
2838 
2839 void SelectionDAGBuilder::visitICmp(const User &I) {
2840   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2841   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2842     predicate = IC->getPredicate();
2843   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2844     predicate = ICmpInst::Predicate(IC->getPredicate());
2845   SDValue Op1 = getValue(I.getOperand(0));
2846   SDValue Op2 = getValue(I.getOperand(1));
2847   ISD::CondCode Opcode = getICmpCondCode(predicate);
2848 
2849   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2850                                                         I.getType());
2851   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2852 }
2853 
2854 void SelectionDAGBuilder::visitFCmp(const User &I) {
2855   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2856   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2857     predicate = FC->getPredicate();
2858   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2859     predicate = FCmpInst::Predicate(FC->getPredicate());
2860   SDValue Op1 = getValue(I.getOperand(0));
2861   SDValue Op2 = getValue(I.getOperand(1));
2862   ISD::CondCode Condition = getFCmpCondCode(predicate);
2863 
2864   // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2865   // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2866   // further optimization, but currently FMF is only applicable to binary nodes.
2867   if (TM.Options.NoNaNsFPMath)
2868     Condition = getFCmpCodeWithoutNaN(Condition);
2869   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2870                                                         I.getType());
2871   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2872 }
2873 
2874 // Check if the condition of the select has one use or two users that are both
2875 // selects with the same condition.
2876 static bool hasOnlySelectUsers(const Value *Cond) {
2877   return llvm::all_of(Cond->users(), [](const Value *V) {
2878     return isa<SelectInst>(V);
2879   });
2880 }
2881 
2882 void SelectionDAGBuilder::visitSelect(const User &I) {
2883   SmallVector<EVT, 4> ValueVTs;
2884   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2885                   ValueVTs);
2886   unsigned NumValues = ValueVTs.size();
2887   if (NumValues == 0) return;
2888 
2889   SmallVector<SDValue, 4> Values(NumValues);
2890   SDValue Cond     = getValue(I.getOperand(0));
2891   SDValue LHSVal   = getValue(I.getOperand(1));
2892   SDValue RHSVal   = getValue(I.getOperand(2));
2893   auto BaseOps = {Cond};
2894   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2895     ISD::VSELECT : ISD::SELECT;
2896 
2897   // Min/max matching is only viable if all output VTs are the same.
2898   if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2899     EVT VT = ValueVTs[0];
2900     LLVMContext &Ctx = *DAG.getContext();
2901     auto &TLI = DAG.getTargetLoweringInfo();
2902 
2903     // We care about the legality of the operation after it has been type
2904     // legalized.
2905     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2906            VT != TLI.getTypeToTransformTo(Ctx, VT))
2907       VT = TLI.getTypeToTransformTo(Ctx, VT);
2908 
2909     // If the vselect is legal, assume we want to leave this as a vector setcc +
2910     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2911     // min/max is legal on the scalar type.
2912     bool UseScalarMinMax = VT.isVector() &&
2913       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2914 
2915     Value *LHS, *RHS;
2916     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2917     ISD::NodeType Opc = ISD::DELETED_NODE;
2918     switch (SPR.Flavor) {
2919     case SPF_UMAX:    Opc = ISD::UMAX; break;
2920     case SPF_UMIN:    Opc = ISD::UMIN; break;
2921     case SPF_SMAX:    Opc = ISD::SMAX; break;
2922     case SPF_SMIN:    Opc = ISD::SMIN; break;
2923     case SPF_FMINNUM:
2924       switch (SPR.NaNBehavior) {
2925       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2926       case SPNB_RETURNS_NAN:   Opc = ISD::FMINNAN; break;
2927       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2928       case SPNB_RETURNS_ANY: {
2929         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2930           Opc = ISD::FMINNUM;
2931         else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT))
2932           Opc = ISD::FMINNAN;
2933         else if (UseScalarMinMax)
2934           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2935             ISD::FMINNUM : ISD::FMINNAN;
2936         break;
2937       }
2938       }
2939       break;
2940     case SPF_FMAXNUM:
2941       switch (SPR.NaNBehavior) {
2942       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2943       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXNAN; break;
2944       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2945       case SPNB_RETURNS_ANY:
2946 
2947         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
2948           Opc = ISD::FMAXNUM;
2949         else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT))
2950           Opc = ISD::FMAXNAN;
2951         else if (UseScalarMinMax)
2952           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
2953             ISD::FMAXNUM : ISD::FMAXNAN;
2954         break;
2955       }
2956       break;
2957     default: break;
2958     }
2959 
2960     if (Opc != ISD::DELETED_NODE &&
2961         (TLI.isOperationLegalOrCustom(Opc, VT) ||
2962          (UseScalarMinMax &&
2963           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
2964         // If the underlying comparison instruction is used by any other
2965         // instruction, the consumed instructions won't be destroyed, so it is
2966         // not profitable to convert to a min/max.
2967         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
2968       OpCode = Opc;
2969       LHSVal = getValue(LHS);
2970       RHSVal = getValue(RHS);
2971       BaseOps = {};
2972     }
2973   }
2974 
2975   for (unsigned i = 0; i != NumValues; ++i) {
2976     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2977     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2978     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2979     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2980                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2981                             Ops);
2982   }
2983 
2984   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2985                            DAG.getVTList(ValueVTs), Values));
2986 }
2987 
2988 void SelectionDAGBuilder::visitTrunc(const User &I) {
2989   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2990   SDValue N = getValue(I.getOperand(0));
2991   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2992                                                         I.getType());
2993   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2994 }
2995 
2996 void SelectionDAGBuilder::visitZExt(const User &I) {
2997   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2998   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2999   SDValue N = getValue(I.getOperand(0));
3000   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3001                                                         I.getType());
3002   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3003 }
3004 
3005 void SelectionDAGBuilder::visitSExt(const User &I) {
3006   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3007   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3008   SDValue N = getValue(I.getOperand(0));
3009   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3010                                                         I.getType());
3011   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3012 }
3013 
3014 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3015   // FPTrunc is never a no-op cast, no need to check
3016   SDValue N = getValue(I.getOperand(0));
3017   SDLoc dl = getCurSDLoc();
3018   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3019   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3020   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3021                            DAG.getTargetConstant(
3022                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3023 }
3024 
3025 void SelectionDAGBuilder::visitFPExt(const User &I) {
3026   // FPExt is never a no-op cast, no need to check
3027   SDValue N = getValue(I.getOperand(0));
3028   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3029                                                         I.getType());
3030   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3031 }
3032 
3033 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3034   // FPToUI is never a no-op cast, no need to check
3035   SDValue N = getValue(I.getOperand(0));
3036   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3037                                                         I.getType());
3038   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3039 }
3040 
3041 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3042   // FPToSI is never a no-op cast, no need to check
3043   SDValue N = getValue(I.getOperand(0));
3044   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3045                                                         I.getType());
3046   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3047 }
3048 
3049 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3050   // UIToFP is never a no-op cast, no need to check
3051   SDValue N = getValue(I.getOperand(0));
3052   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3053                                                         I.getType());
3054   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3055 }
3056 
3057 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3058   // SIToFP is never a no-op cast, no need to check
3059   SDValue N = getValue(I.getOperand(0));
3060   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3061                                                         I.getType());
3062   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3063 }
3064 
3065 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3066   // What to do depends on the size of the integer and the size of the pointer.
3067   // We can either truncate, zero extend, or no-op, accordingly.
3068   SDValue N = getValue(I.getOperand(0));
3069   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3070                                                         I.getType());
3071   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3072 }
3073 
3074 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3075   // What to do depends on the size of the integer and the size of the pointer.
3076   // We can either truncate, zero extend, or no-op, accordingly.
3077   SDValue N = getValue(I.getOperand(0));
3078   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3079                                                         I.getType());
3080   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3081 }
3082 
3083 void SelectionDAGBuilder::visitBitCast(const User &I) {
3084   SDValue N = getValue(I.getOperand(0));
3085   SDLoc dl = getCurSDLoc();
3086   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3087                                                         I.getType());
3088 
3089   // BitCast assures us that source and destination are the same size so this is
3090   // either a BITCAST or a no-op.
3091   if (DestVT != N.getValueType())
3092     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3093                              DestVT, N)); // convert types.
3094   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3095   // might fold any kind of constant expression to an integer constant and that
3096   // is not what we are looking for. Only recognize a bitcast of a genuine
3097   // constant integer as an opaque constant.
3098   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3099     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3100                                  /*isOpaque*/true));
3101   else
3102     setValue(&I, N);            // noop cast.
3103 }
3104 
3105 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3106   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3107   const Value *SV = I.getOperand(0);
3108   SDValue N = getValue(SV);
3109   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3110 
3111   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3112   unsigned DestAS = I.getType()->getPointerAddressSpace();
3113 
3114   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3115     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3116 
3117   setValue(&I, N);
3118 }
3119 
3120 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3122   SDValue InVec = getValue(I.getOperand(0));
3123   SDValue InVal = getValue(I.getOperand(1));
3124   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3125                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3126   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3127                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3128                            InVec, InVal, InIdx));
3129 }
3130 
3131 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3132   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3133   SDValue InVec = getValue(I.getOperand(0));
3134   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3135                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3136   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3137                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3138                            InVec, InIdx));
3139 }
3140 
3141 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3142   SDValue Src1 = getValue(I.getOperand(0));
3143   SDValue Src2 = getValue(I.getOperand(1));
3144   SDLoc DL = getCurSDLoc();
3145 
3146   SmallVector<int, 8> Mask;
3147   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3148   unsigned MaskNumElts = Mask.size();
3149 
3150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3151   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3152   EVT SrcVT = Src1.getValueType();
3153   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3154 
3155   if (SrcNumElts == MaskNumElts) {
3156     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3157     return;
3158   }
3159 
3160   // Normalize the shuffle vector since mask and vector length don't match.
3161   if (SrcNumElts < MaskNumElts) {
3162     // Mask is longer than the source vectors. We can use concatenate vector to
3163     // make the mask and vectors lengths match.
3164 
3165     if (MaskNumElts % SrcNumElts == 0) {
3166       // Mask length is a multiple of the source vector length.
3167       // Check if the shuffle is some kind of concatenation of the input
3168       // vectors.
3169       unsigned NumConcat = MaskNumElts / SrcNumElts;
3170       bool IsConcat = true;
3171       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3172       for (unsigned i = 0; i != MaskNumElts; ++i) {
3173         int Idx = Mask[i];
3174         if (Idx < 0)
3175           continue;
3176         // Ensure the indices in each SrcVT sized piece are sequential and that
3177         // the same source is used for the whole piece.
3178         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3179             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3180              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3181           IsConcat = false;
3182           break;
3183         }
3184         // Remember which source this index came from.
3185         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3186       }
3187 
3188       // The shuffle is concatenating multiple vectors together. Just emit
3189       // a CONCAT_VECTORS operation.
3190       if (IsConcat) {
3191         SmallVector<SDValue, 8> ConcatOps;
3192         for (auto Src : ConcatSrcs) {
3193           if (Src < 0)
3194             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3195           else if (Src == 0)
3196             ConcatOps.push_back(Src1);
3197           else
3198             ConcatOps.push_back(Src2);
3199         }
3200         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3201         return;
3202       }
3203     }
3204 
3205     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3206     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3207     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3208                                     PaddedMaskNumElts);
3209 
3210     // Pad both vectors with undefs to make them the same length as the mask.
3211     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3212 
3213     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3214     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3215     MOps1[0] = Src1;
3216     MOps2[0] = Src2;
3217 
3218     Src1 = Src1.isUndef()
3219                ? DAG.getUNDEF(PaddedVT)
3220                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3221     Src2 = Src2.isUndef()
3222                ? DAG.getUNDEF(PaddedVT)
3223                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3224 
3225     // Readjust mask for new input vector length.
3226     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3227     for (unsigned i = 0; i != MaskNumElts; ++i) {
3228       int Idx = Mask[i];
3229       if (Idx >= (int)SrcNumElts)
3230         Idx -= SrcNumElts - PaddedMaskNumElts;
3231       MappedOps[i] = Idx;
3232     }
3233 
3234     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3235 
3236     // If the concatenated vector was padded, extract a subvector with the
3237     // correct number of elements.
3238     if (MaskNumElts != PaddedMaskNumElts)
3239       Result = DAG.getNode(
3240           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3241           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3242 
3243     setValue(&I, Result);
3244     return;
3245   }
3246 
3247   if (SrcNumElts > MaskNumElts) {
3248     // Analyze the access pattern of the vector to see if we can extract
3249     // two subvectors and do the shuffle.
3250     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3251     bool CanExtract = true;
3252     for (int Idx : Mask) {
3253       unsigned Input = 0;
3254       if (Idx < 0)
3255         continue;
3256 
3257       if (Idx >= (int)SrcNumElts) {
3258         Input = 1;
3259         Idx -= SrcNumElts;
3260       }
3261 
3262       // If all the indices come from the same MaskNumElts sized portion of
3263       // the sources we can use extract. Also make sure the extract wouldn't
3264       // extract past the end of the source.
3265       int NewStartIdx = alignDown(Idx, MaskNumElts);
3266       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3267           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3268         CanExtract = false;
3269       // Make sure we always update StartIdx as we use it to track if all
3270       // elements are undef.
3271       StartIdx[Input] = NewStartIdx;
3272     }
3273 
3274     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3275       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3276       return;
3277     }
3278     if (CanExtract) {
3279       // Extract appropriate subvector and generate a vector shuffle
3280       for (unsigned Input = 0; Input < 2; ++Input) {
3281         SDValue &Src = Input == 0 ? Src1 : Src2;
3282         if (StartIdx[Input] < 0)
3283           Src = DAG.getUNDEF(VT);
3284         else {
3285           Src = DAG.getNode(
3286               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3287               DAG.getConstant(StartIdx[Input], DL,
3288                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3289         }
3290       }
3291 
3292       // Calculate new mask.
3293       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3294       for (int &Idx : MappedOps) {
3295         if (Idx >= (int)SrcNumElts)
3296           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3297         else if (Idx >= 0)
3298           Idx -= StartIdx[0];
3299       }
3300 
3301       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3302       return;
3303     }
3304   }
3305 
3306   // We can't use either concat vectors or extract subvectors so fall back to
3307   // replacing the shuffle with extract and build vector.
3308   // to insert and build vector.
3309   EVT EltVT = VT.getVectorElementType();
3310   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3311   SmallVector<SDValue,8> Ops;
3312   for (int Idx : Mask) {
3313     SDValue Res;
3314 
3315     if (Idx < 0) {
3316       Res = DAG.getUNDEF(EltVT);
3317     } else {
3318       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3319       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3320 
3321       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3322                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3323     }
3324 
3325     Ops.push_back(Res);
3326   }
3327 
3328   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3329 }
3330 
3331 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3332   ArrayRef<unsigned> Indices;
3333   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3334     Indices = IV->getIndices();
3335   else
3336     Indices = cast<ConstantExpr>(&I)->getIndices();
3337 
3338   const Value *Op0 = I.getOperand(0);
3339   const Value *Op1 = I.getOperand(1);
3340   Type *AggTy = I.getType();
3341   Type *ValTy = Op1->getType();
3342   bool IntoUndef = isa<UndefValue>(Op0);
3343   bool FromUndef = isa<UndefValue>(Op1);
3344 
3345   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3346 
3347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3348   SmallVector<EVT, 4> AggValueVTs;
3349   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3350   SmallVector<EVT, 4> ValValueVTs;
3351   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3352 
3353   unsigned NumAggValues = AggValueVTs.size();
3354   unsigned NumValValues = ValValueVTs.size();
3355   SmallVector<SDValue, 4> Values(NumAggValues);
3356 
3357   // Ignore an insertvalue that produces an empty object
3358   if (!NumAggValues) {
3359     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3360     return;
3361   }
3362 
3363   SDValue Agg = getValue(Op0);
3364   unsigned i = 0;
3365   // Copy the beginning value(s) from the original aggregate.
3366   for (; i != LinearIndex; ++i)
3367     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3368                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3369   // Copy values from the inserted value(s).
3370   if (NumValValues) {
3371     SDValue Val = getValue(Op1);
3372     for (; i != LinearIndex + NumValValues; ++i)
3373       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3374                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3375   }
3376   // Copy remaining value(s) from the original aggregate.
3377   for (; i != NumAggValues; ++i)
3378     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3379                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3380 
3381   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3382                            DAG.getVTList(AggValueVTs), Values));
3383 }
3384 
3385 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3386   ArrayRef<unsigned> Indices;
3387   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3388     Indices = EV->getIndices();
3389   else
3390     Indices = cast<ConstantExpr>(&I)->getIndices();
3391 
3392   const Value *Op0 = I.getOperand(0);
3393   Type *AggTy = Op0->getType();
3394   Type *ValTy = I.getType();
3395   bool OutOfUndef = isa<UndefValue>(Op0);
3396 
3397   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3398 
3399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3400   SmallVector<EVT, 4> ValValueVTs;
3401   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3402 
3403   unsigned NumValValues = ValValueVTs.size();
3404 
3405   // Ignore a extractvalue that produces an empty object
3406   if (!NumValValues) {
3407     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3408     return;
3409   }
3410 
3411   SmallVector<SDValue, 4> Values(NumValValues);
3412 
3413   SDValue Agg = getValue(Op0);
3414   // Copy out the selected value(s).
3415   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3416     Values[i - LinearIndex] =
3417       OutOfUndef ?
3418         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3419         SDValue(Agg.getNode(), Agg.getResNo() + i);
3420 
3421   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3422                            DAG.getVTList(ValValueVTs), Values));
3423 }
3424 
3425 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3426   Value *Op0 = I.getOperand(0);
3427   // Note that the pointer operand may be a vector of pointers. Take the scalar
3428   // element which holds a pointer.
3429   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3430   SDValue N = getValue(Op0);
3431   SDLoc dl = getCurSDLoc();
3432 
3433   // Normalize Vector GEP - all scalar operands should be converted to the
3434   // splat vector.
3435   unsigned VectorWidth = I.getType()->isVectorTy() ?
3436     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3437 
3438   if (VectorWidth && !N.getValueType().isVector()) {
3439     LLVMContext &Context = *DAG.getContext();
3440     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3441     N = DAG.getSplatBuildVector(VT, dl, N);
3442   }
3443 
3444   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3445        GTI != E; ++GTI) {
3446     const Value *Idx = GTI.getOperand();
3447     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3448       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3449       if (Field) {
3450         // N = N + Offset
3451         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3452 
3453         // In an inbounds GEP with an offset that is nonnegative even when
3454         // interpreted as signed, assume there is no unsigned overflow.
3455         SDNodeFlags Flags;
3456         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3457           Flags.setNoUnsignedWrap(true);
3458 
3459         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3460                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3461       }
3462     } else {
3463       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3464       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3465       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3466 
3467       // If this is a scalar constant or a splat vector of constants,
3468       // handle it quickly.
3469       const auto *CI = dyn_cast<ConstantInt>(Idx);
3470       if (!CI && isa<ConstantDataVector>(Idx) &&
3471           cast<ConstantDataVector>(Idx)->getSplatValue())
3472         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3473 
3474       if (CI) {
3475         if (CI->isZero())
3476           continue;
3477         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3478         LLVMContext &Context = *DAG.getContext();
3479         SDValue OffsVal = VectorWidth ?
3480           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3481           DAG.getConstant(Offs, dl, IdxTy);
3482 
3483         // In an inbouds GEP with an offset that is nonnegative even when
3484         // interpreted as signed, assume there is no unsigned overflow.
3485         SDNodeFlags Flags;
3486         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3487           Flags.setNoUnsignedWrap(true);
3488 
3489         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3490         continue;
3491       }
3492 
3493       // N = N + Idx * ElementSize;
3494       SDValue IdxN = getValue(Idx);
3495 
3496       if (!IdxN.getValueType().isVector() && VectorWidth) {
3497         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3498         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3499       }
3500 
3501       // If the index is smaller or larger than intptr_t, truncate or extend
3502       // it.
3503       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3504 
3505       // If this is a multiply by a power of two, turn it into a shl
3506       // immediately.  This is a very common case.
3507       if (ElementSize != 1) {
3508         if (ElementSize.isPowerOf2()) {
3509           unsigned Amt = ElementSize.logBase2();
3510           IdxN = DAG.getNode(ISD::SHL, dl,
3511                              N.getValueType(), IdxN,
3512                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3513         } else {
3514           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3515           IdxN = DAG.getNode(ISD::MUL, dl,
3516                              N.getValueType(), IdxN, Scale);
3517         }
3518       }
3519 
3520       N = DAG.getNode(ISD::ADD, dl,
3521                       N.getValueType(), N, IdxN);
3522     }
3523   }
3524 
3525   setValue(&I, N);
3526 }
3527 
3528 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3529   // If this is a fixed sized alloca in the entry block of the function,
3530   // allocate it statically on the stack.
3531   if (FuncInfo.StaticAllocaMap.count(&I))
3532     return;   // getValue will auto-populate this.
3533 
3534   SDLoc dl = getCurSDLoc();
3535   Type *Ty = I.getAllocatedType();
3536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3537   auto &DL = DAG.getDataLayout();
3538   uint64_t TySize = DL.getTypeAllocSize(Ty);
3539   unsigned Align =
3540       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3541 
3542   SDValue AllocSize = getValue(I.getArraySize());
3543 
3544   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3545   if (AllocSize.getValueType() != IntPtr)
3546     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3547 
3548   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3549                           AllocSize,
3550                           DAG.getConstant(TySize, dl, IntPtr));
3551 
3552   // Handle alignment.  If the requested alignment is less than or equal to
3553   // the stack alignment, ignore it.  If the size is greater than or equal to
3554   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3555   unsigned StackAlign =
3556       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3557   if (Align <= StackAlign)
3558     Align = 0;
3559 
3560   // Round the size of the allocation up to the stack alignment size
3561   // by add SA-1 to the size. This doesn't overflow because we're computing
3562   // an address inside an alloca.
3563   SDNodeFlags Flags;
3564   Flags.setNoUnsignedWrap(true);
3565   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3566                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3567 
3568   // Mask out the low bits for alignment purposes.
3569   AllocSize =
3570       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3571                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3572 
3573   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3574   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3575   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3576   setValue(&I, DSA);
3577   DAG.setRoot(DSA.getValue(1));
3578 
3579   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3580 }
3581 
3582 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3583   if (I.isAtomic())
3584     return visitAtomicLoad(I);
3585 
3586   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3587   const Value *SV = I.getOperand(0);
3588   if (TLI.supportSwiftError()) {
3589     // Swifterror values can come from either a function parameter with
3590     // swifterror attribute or an alloca with swifterror attribute.
3591     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3592       if (Arg->hasSwiftErrorAttr())
3593         return visitLoadFromSwiftError(I);
3594     }
3595 
3596     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3597       if (Alloca->isSwiftError())
3598         return visitLoadFromSwiftError(I);
3599     }
3600   }
3601 
3602   SDValue Ptr = getValue(SV);
3603 
3604   Type *Ty = I.getType();
3605 
3606   bool isVolatile = I.isVolatile();
3607   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3608   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3609   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3610   unsigned Alignment = I.getAlignment();
3611 
3612   AAMDNodes AAInfo;
3613   I.getAAMetadata(AAInfo);
3614   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3615 
3616   SmallVector<EVT, 4> ValueVTs;
3617   SmallVector<uint64_t, 4> Offsets;
3618   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3619   unsigned NumValues = ValueVTs.size();
3620   if (NumValues == 0)
3621     return;
3622 
3623   SDValue Root;
3624   bool ConstantMemory = false;
3625   if (isVolatile || NumValues > MaxParallelChains)
3626     // Serialize volatile loads with other side effects.
3627     Root = getRoot();
3628   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3629                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3630     // Do not serialize (non-volatile) loads of constant memory with anything.
3631     Root = DAG.getEntryNode();
3632     ConstantMemory = true;
3633   } else {
3634     // Do not serialize non-volatile loads against each other.
3635     Root = DAG.getRoot();
3636   }
3637 
3638   SDLoc dl = getCurSDLoc();
3639 
3640   if (isVolatile)
3641     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3642 
3643   // An aggregate load cannot wrap around the address space, so offsets to its
3644   // parts don't wrap either.
3645   SDNodeFlags Flags;
3646   Flags.setNoUnsignedWrap(true);
3647 
3648   SmallVector<SDValue, 4> Values(NumValues);
3649   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3650   EVT PtrVT = Ptr.getValueType();
3651   unsigned ChainI = 0;
3652   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3653     // Serializing loads here may result in excessive register pressure, and
3654     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3655     // could recover a bit by hoisting nodes upward in the chain by recognizing
3656     // they are side-effect free or do not alias. The optimizer should really
3657     // avoid this case by converting large object/array copies to llvm.memcpy
3658     // (MaxParallelChains should always remain as failsafe).
3659     if (ChainI == MaxParallelChains) {
3660       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3661       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3662                                   makeArrayRef(Chains.data(), ChainI));
3663       Root = Chain;
3664       ChainI = 0;
3665     }
3666     SDValue A = DAG.getNode(ISD::ADD, dl,
3667                             PtrVT, Ptr,
3668                             DAG.getConstant(Offsets[i], dl, PtrVT),
3669                             Flags);
3670     auto MMOFlags = MachineMemOperand::MONone;
3671     if (isVolatile)
3672       MMOFlags |= MachineMemOperand::MOVolatile;
3673     if (isNonTemporal)
3674       MMOFlags |= MachineMemOperand::MONonTemporal;
3675     if (isInvariant)
3676       MMOFlags |= MachineMemOperand::MOInvariant;
3677     if (isDereferenceable)
3678       MMOFlags |= MachineMemOperand::MODereferenceable;
3679     MMOFlags |= TLI.getMMOFlags(I);
3680 
3681     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3682                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3683                             MMOFlags, AAInfo, Ranges);
3684 
3685     Values[i] = L;
3686     Chains[ChainI] = L.getValue(1);
3687   }
3688 
3689   if (!ConstantMemory) {
3690     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3691                                 makeArrayRef(Chains.data(), ChainI));
3692     if (isVolatile)
3693       DAG.setRoot(Chain);
3694     else
3695       PendingLoads.push_back(Chain);
3696   }
3697 
3698   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3699                            DAG.getVTList(ValueVTs), Values));
3700 }
3701 
3702 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3703   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3704          "call visitStoreToSwiftError when backend supports swifterror");
3705 
3706   SmallVector<EVT, 4> ValueVTs;
3707   SmallVector<uint64_t, 4> Offsets;
3708   const Value *SrcV = I.getOperand(0);
3709   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3710                   SrcV->getType(), ValueVTs, &Offsets);
3711   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3712          "expect a single EVT for swifterror");
3713 
3714   SDValue Src = getValue(SrcV);
3715   // Create a virtual register, then update the virtual register.
3716   unsigned VReg; bool CreatedVReg;
3717   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3718   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3719   // Chain can be getRoot or getControlRoot.
3720   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3721                                       SDValue(Src.getNode(), Src.getResNo()));
3722   DAG.setRoot(CopyNode);
3723   if (CreatedVReg)
3724     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3725 }
3726 
3727 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3728   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3729          "call visitLoadFromSwiftError when backend supports swifterror");
3730 
3731   assert(!I.isVolatile() &&
3732          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3733          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3734          "Support volatile, non temporal, invariant for load_from_swift_error");
3735 
3736   const Value *SV = I.getOperand(0);
3737   Type *Ty = I.getType();
3738   AAMDNodes AAInfo;
3739   I.getAAMetadata(AAInfo);
3740   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3741              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3742          "load_from_swift_error should not be constant memory");
3743 
3744   SmallVector<EVT, 4> ValueVTs;
3745   SmallVector<uint64_t, 4> Offsets;
3746   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3747                   ValueVTs, &Offsets);
3748   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3749          "expect a single EVT for swifterror");
3750 
3751   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3752   SDValue L = DAG.getCopyFromReg(
3753       getRoot(), getCurSDLoc(),
3754       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3755       ValueVTs[0]);
3756 
3757   setValue(&I, L);
3758 }
3759 
3760 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3761   if (I.isAtomic())
3762     return visitAtomicStore(I);
3763 
3764   const Value *SrcV = I.getOperand(0);
3765   const Value *PtrV = I.getOperand(1);
3766 
3767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3768   if (TLI.supportSwiftError()) {
3769     // Swifterror values can come from either a function parameter with
3770     // swifterror attribute or an alloca with swifterror attribute.
3771     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3772       if (Arg->hasSwiftErrorAttr())
3773         return visitStoreToSwiftError(I);
3774     }
3775 
3776     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3777       if (Alloca->isSwiftError())
3778         return visitStoreToSwiftError(I);
3779     }
3780   }
3781 
3782   SmallVector<EVT, 4> ValueVTs;
3783   SmallVector<uint64_t, 4> Offsets;
3784   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3785                   SrcV->getType(), ValueVTs, &Offsets);
3786   unsigned NumValues = ValueVTs.size();
3787   if (NumValues == 0)
3788     return;
3789 
3790   // Get the lowered operands. Note that we do this after
3791   // checking if NumResults is zero, because with zero results
3792   // the operands won't have values in the map.
3793   SDValue Src = getValue(SrcV);
3794   SDValue Ptr = getValue(PtrV);
3795 
3796   SDValue Root = getRoot();
3797   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3798   SDLoc dl = getCurSDLoc();
3799   EVT PtrVT = Ptr.getValueType();
3800   unsigned Alignment = I.getAlignment();
3801   AAMDNodes AAInfo;
3802   I.getAAMetadata(AAInfo);
3803 
3804   auto MMOFlags = MachineMemOperand::MONone;
3805   if (I.isVolatile())
3806     MMOFlags |= MachineMemOperand::MOVolatile;
3807   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3808     MMOFlags |= MachineMemOperand::MONonTemporal;
3809   MMOFlags |= TLI.getMMOFlags(I);
3810 
3811   // An aggregate load cannot wrap around the address space, so offsets to its
3812   // parts don't wrap either.
3813   SDNodeFlags Flags;
3814   Flags.setNoUnsignedWrap(true);
3815 
3816   unsigned ChainI = 0;
3817   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3818     // See visitLoad comments.
3819     if (ChainI == MaxParallelChains) {
3820       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3821                                   makeArrayRef(Chains.data(), ChainI));
3822       Root = Chain;
3823       ChainI = 0;
3824     }
3825     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3826                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3827     SDValue St = DAG.getStore(
3828         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3829         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3830     Chains[ChainI] = St;
3831   }
3832 
3833   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3834                                   makeArrayRef(Chains.data(), ChainI));
3835   DAG.setRoot(StoreNode);
3836 }
3837 
3838 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3839                                            bool IsCompressing) {
3840   SDLoc sdl = getCurSDLoc();
3841 
3842   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3843                            unsigned& Alignment) {
3844     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3845     Src0 = I.getArgOperand(0);
3846     Ptr = I.getArgOperand(1);
3847     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3848     Mask = I.getArgOperand(3);
3849   };
3850   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3851                            unsigned& Alignment) {
3852     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3853     Src0 = I.getArgOperand(0);
3854     Ptr = I.getArgOperand(1);
3855     Mask = I.getArgOperand(2);
3856     Alignment = 0;
3857   };
3858 
3859   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3860   unsigned Alignment;
3861   if (IsCompressing)
3862     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3863   else
3864     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3865 
3866   SDValue Ptr = getValue(PtrOperand);
3867   SDValue Src0 = getValue(Src0Operand);
3868   SDValue Mask = getValue(MaskOperand);
3869 
3870   EVT VT = Src0.getValueType();
3871   if (!Alignment)
3872     Alignment = DAG.getEVTAlignment(VT);
3873 
3874   AAMDNodes AAInfo;
3875   I.getAAMetadata(AAInfo);
3876 
3877   MachineMemOperand *MMO =
3878     DAG.getMachineFunction().
3879     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3880                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3881                           Alignment, AAInfo);
3882   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3883                                          MMO, false /* Truncating */,
3884                                          IsCompressing);
3885   DAG.setRoot(StoreNode);
3886   setValue(&I, StoreNode);
3887 }
3888 
3889 // Get a uniform base for the Gather/Scatter intrinsic.
3890 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3891 // We try to represent it as a base pointer + vector of indices.
3892 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3893 // The first operand of the GEP may be a single pointer or a vector of pointers
3894 // Example:
3895 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3896 //  or
3897 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3898 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3899 //
3900 // When the first GEP operand is a single pointer - it is the uniform base we
3901 // are looking for. If first operand of the GEP is a splat vector - we
3902 // extract the splat value and use it as a uniform base.
3903 // In all other cases the function returns 'false'.
3904 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3905                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3906   SelectionDAG& DAG = SDB->DAG;
3907   LLVMContext &Context = *DAG.getContext();
3908 
3909   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3910   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3911   if (!GEP)
3912     return false;
3913 
3914   const Value *GEPPtr = GEP->getPointerOperand();
3915   if (!GEPPtr->getType()->isVectorTy())
3916     Ptr = GEPPtr;
3917   else if (!(Ptr = getSplatValue(GEPPtr)))
3918     return false;
3919 
3920   unsigned FinalIndex = GEP->getNumOperands() - 1;
3921   Value *IndexVal = GEP->getOperand(FinalIndex);
3922 
3923   // Ensure all the other indices are 0.
3924   for (unsigned i = 1; i < FinalIndex; ++i) {
3925     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3926     if (!C || !C->isZero())
3927       return false;
3928   }
3929 
3930   // The operands of the GEP may be defined in another basic block.
3931   // In this case we'll not find nodes for the operands.
3932   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3933     return false;
3934 
3935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3936   const DataLayout &DL = DAG.getDataLayout();
3937   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3938                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3939   Base = SDB->getValue(Ptr);
3940   Index = SDB->getValue(IndexVal);
3941 
3942   if (!Index.getValueType().isVector()) {
3943     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3944     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3945     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
3946   }
3947   return true;
3948 }
3949 
3950 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3951   SDLoc sdl = getCurSDLoc();
3952 
3953   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3954   const Value *Ptr = I.getArgOperand(1);
3955   SDValue Src0 = getValue(I.getArgOperand(0));
3956   SDValue Mask = getValue(I.getArgOperand(3));
3957   EVT VT = Src0.getValueType();
3958   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3959   if (!Alignment)
3960     Alignment = DAG.getEVTAlignment(VT);
3961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3962 
3963   AAMDNodes AAInfo;
3964   I.getAAMetadata(AAInfo);
3965 
3966   SDValue Base;
3967   SDValue Index;
3968   SDValue Scale;
3969   const Value *BasePtr = Ptr;
3970   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
3971 
3972   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3973   MachineMemOperand *MMO = DAG.getMachineFunction().
3974     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3975                          MachineMemOperand::MOStore,  VT.getStoreSize(),
3976                          Alignment, AAInfo);
3977   if (!UniformBase) {
3978     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3979     Index = getValue(Ptr);
3980     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3981   }
3982   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
3983   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3984                                          Ops, MMO);
3985   DAG.setRoot(Scatter);
3986   setValue(&I, Scatter);
3987 }
3988 
3989 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
3990   SDLoc sdl = getCurSDLoc();
3991 
3992   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3993                            unsigned& Alignment) {
3994     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
3995     Ptr = I.getArgOperand(0);
3996     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
3997     Mask = I.getArgOperand(2);
3998     Src0 = I.getArgOperand(3);
3999   };
4000   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4001                            unsigned& Alignment) {
4002     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4003     Ptr = I.getArgOperand(0);
4004     Alignment = 0;
4005     Mask = I.getArgOperand(1);
4006     Src0 = I.getArgOperand(2);
4007   };
4008 
4009   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4010   unsigned Alignment;
4011   if (IsExpanding)
4012     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4013   else
4014     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4015 
4016   SDValue Ptr = getValue(PtrOperand);
4017   SDValue Src0 = getValue(Src0Operand);
4018   SDValue Mask = getValue(MaskOperand);
4019 
4020   EVT VT = Src0.getValueType();
4021   if (!Alignment)
4022     Alignment = DAG.getEVTAlignment(VT);
4023 
4024   AAMDNodes AAInfo;
4025   I.getAAMetadata(AAInfo);
4026   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4027 
4028   // Do not serialize masked loads of constant memory with anything.
4029   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
4030       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
4031   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4032 
4033   MachineMemOperand *MMO =
4034     DAG.getMachineFunction().
4035     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4036                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4037                           Alignment, AAInfo, Ranges);
4038 
4039   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4040                                    ISD::NON_EXTLOAD, IsExpanding);
4041   if (AddToChain) {
4042     SDValue OutChain = Load.getValue(1);
4043     DAG.setRoot(OutChain);
4044   }
4045   setValue(&I, Load);
4046 }
4047 
4048 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4049   SDLoc sdl = getCurSDLoc();
4050 
4051   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4052   const Value *Ptr = I.getArgOperand(0);
4053   SDValue Src0 = getValue(I.getArgOperand(3));
4054   SDValue Mask = getValue(I.getArgOperand(2));
4055 
4056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4057   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4058   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4059   if (!Alignment)
4060     Alignment = DAG.getEVTAlignment(VT);
4061 
4062   AAMDNodes AAInfo;
4063   I.getAAMetadata(AAInfo);
4064   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4065 
4066   SDValue Root = DAG.getRoot();
4067   SDValue Base;
4068   SDValue Index;
4069   SDValue Scale;
4070   const Value *BasePtr = Ptr;
4071   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4072   bool ConstantMemory = false;
4073   if (UniformBase &&
4074       AA && AA->pointsToConstantMemory(MemoryLocation(
4075           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4076           AAInfo))) {
4077     // Do not serialize (non-volatile) loads of constant memory with anything.
4078     Root = DAG.getEntryNode();
4079     ConstantMemory = true;
4080   }
4081 
4082   MachineMemOperand *MMO =
4083     DAG.getMachineFunction().
4084     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4085                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4086                          Alignment, AAInfo, Ranges);
4087 
4088   if (!UniformBase) {
4089     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4090     Index = getValue(Ptr);
4091     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4092   }
4093   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4094   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4095                                        Ops, MMO);
4096 
4097   SDValue OutChain = Gather.getValue(1);
4098   if (!ConstantMemory)
4099     PendingLoads.push_back(OutChain);
4100   setValue(&I, Gather);
4101 }
4102 
4103 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4104   SDLoc dl = getCurSDLoc();
4105   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4106   AtomicOrdering FailureOrder = I.getFailureOrdering();
4107   SyncScope::ID SSID = I.getSyncScopeID();
4108 
4109   SDValue InChain = getRoot();
4110 
4111   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4112   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4113   SDValue L = DAG.getAtomicCmpSwap(
4114       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4115       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4116       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4117       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4118 
4119   SDValue OutChain = L.getValue(2);
4120 
4121   setValue(&I, L);
4122   DAG.setRoot(OutChain);
4123 }
4124 
4125 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4126   SDLoc dl = getCurSDLoc();
4127   ISD::NodeType NT;
4128   switch (I.getOperation()) {
4129   default: llvm_unreachable("Unknown atomicrmw operation");
4130   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4131   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4132   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4133   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4134   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4135   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4136   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4137   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4138   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4139   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4140   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4141   }
4142   AtomicOrdering Order = I.getOrdering();
4143   SyncScope::ID SSID = I.getSyncScopeID();
4144 
4145   SDValue InChain = getRoot();
4146 
4147   SDValue L =
4148     DAG.getAtomic(NT, dl,
4149                   getValue(I.getValOperand()).getSimpleValueType(),
4150                   InChain,
4151                   getValue(I.getPointerOperand()),
4152                   getValue(I.getValOperand()),
4153                   I.getPointerOperand(),
4154                   /* Alignment=*/ 0, Order, SSID);
4155 
4156   SDValue OutChain = L.getValue(1);
4157 
4158   setValue(&I, L);
4159   DAG.setRoot(OutChain);
4160 }
4161 
4162 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4163   SDLoc dl = getCurSDLoc();
4164   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4165   SDValue Ops[3];
4166   Ops[0] = getRoot();
4167   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4168                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4169   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4170                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4171   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4172 }
4173 
4174 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4175   SDLoc dl = getCurSDLoc();
4176   AtomicOrdering Order = I.getOrdering();
4177   SyncScope::ID SSID = I.getSyncScopeID();
4178 
4179   SDValue InChain = getRoot();
4180 
4181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4182   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4183 
4184   if (!TLI.supportsUnalignedAtomics() &&
4185       I.getAlignment() < VT.getStoreSize())
4186     report_fatal_error("Cannot generate unaligned atomic load");
4187 
4188   MachineMemOperand *MMO =
4189       DAG.getMachineFunction().
4190       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4191                            MachineMemOperand::MOVolatile |
4192                            MachineMemOperand::MOLoad,
4193                            VT.getStoreSize(),
4194                            I.getAlignment() ? I.getAlignment() :
4195                                               DAG.getEVTAlignment(VT),
4196                            AAMDNodes(), nullptr, SSID, Order);
4197 
4198   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4199   SDValue L =
4200       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4201                     getValue(I.getPointerOperand()), MMO);
4202 
4203   SDValue OutChain = L.getValue(1);
4204 
4205   setValue(&I, L);
4206   DAG.setRoot(OutChain);
4207 }
4208 
4209 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4210   SDLoc dl = getCurSDLoc();
4211 
4212   AtomicOrdering Order = I.getOrdering();
4213   SyncScope::ID SSID = I.getSyncScopeID();
4214 
4215   SDValue InChain = getRoot();
4216 
4217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4218   EVT VT =
4219       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4220 
4221   if (I.getAlignment() < VT.getStoreSize())
4222     report_fatal_error("Cannot generate unaligned atomic store");
4223 
4224   SDValue OutChain =
4225     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4226                   InChain,
4227                   getValue(I.getPointerOperand()),
4228                   getValue(I.getValueOperand()),
4229                   I.getPointerOperand(), I.getAlignment(),
4230                   Order, SSID);
4231 
4232   DAG.setRoot(OutChain);
4233 }
4234 
4235 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4236 /// node.
4237 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4238                                                unsigned Intrinsic) {
4239   // Ignore the callsite's attributes. A specific call site may be marked with
4240   // readnone, but the lowering code will expect the chain based on the
4241   // definition.
4242   const Function *F = I.getCalledFunction();
4243   bool HasChain = !F->doesNotAccessMemory();
4244   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4245 
4246   // Build the operand list.
4247   SmallVector<SDValue, 8> Ops;
4248   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4249     if (OnlyLoad) {
4250       // We don't need to serialize loads against other loads.
4251       Ops.push_back(DAG.getRoot());
4252     } else {
4253       Ops.push_back(getRoot());
4254     }
4255   }
4256 
4257   // Info is set by getTgtMemInstrinsic
4258   TargetLowering::IntrinsicInfo Info;
4259   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4260   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4261                                                DAG.getMachineFunction(),
4262                                                Intrinsic);
4263 
4264   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4265   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4266       Info.opc == ISD::INTRINSIC_W_CHAIN)
4267     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4268                                         TLI.getPointerTy(DAG.getDataLayout())));
4269 
4270   // Add all operands of the call to the operand list.
4271   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4272     SDValue Op = getValue(I.getArgOperand(i));
4273     Ops.push_back(Op);
4274   }
4275 
4276   SmallVector<EVT, 4> ValueVTs;
4277   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4278 
4279   if (HasChain)
4280     ValueVTs.push_back(MVT::Other);
4281 
4282   SDVTList VTs = DAG.getVTList(ValueVTs);
4283 
4284   // Create the node.
4285   SDValue Result;
4286   if (IsTgtIntrinsic) {
4287     // This is target intrinsic that touches memory
4288     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4289       Ops, Info.memVT,
4290       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4291       Info.flags, Info.size);
4292   } else if (!HasChain) {
4293     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4294   } else if (!I.getType()->isVoidTy()) {
4295     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4296   } else {
4297     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4298   }
4299 
4300   if (HasChain) {
4301     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4302     if (OnlyLoad)
4303       PendingLoads.push_back(Chain);
4304     else
4305       DAG.setRoot(Chain);
4306   }
4307 
4308   if (!I.getType()->isVoidTy()) {
4309     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4310       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4311       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4312     } else
4313       Result = lowerRangeToAssertZExt(DAG, I, Result);
4314 
4315     setValue(&I, Result);
4316   }
4317 }
4318 
4319 /// GetSignificand - Get the significand and build it into a floating-point
4320 /// number with exponent of 1:
4321 ///
4322 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4323 ///
4324 /// where Op is the hexadecimal representation of floating point value.
4325 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4326   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4327                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4328   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4329                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4330   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4331 }
4332 
4333 /// GetExponent - Get the exponent:
4334 ///
4335 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4336 ///
4337 /// where Op is the hexadecimal representation of floating point value.
4338 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4339                            const TargetLowering &TLI, const SDLoc &dl) {
4340   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4341                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4342   SDValue t1 = DAG.getNode(
4343       ISD::SRL, dl, MVT::i32, t0,
4344       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4345   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4346                            DAG.getConstant(127, dl, MVT::i32));
4347   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4348 }
4349 
4350 /// getF32Constant - Get 32-bit floating point constant.
4351 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4352                               const SDLoc &dl) {
4353   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4354                            MVT::f32);
4355 }
4356 
4357 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4358                                        SelectionDAG &DAG) {
4359   // TODO: What fast-math-flags should be set on the floating-point nodes?
4360 
4361   //   IntegerPartOfX = ((int32_t)(t0);
4362   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4363 
4364   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4365   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4366   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4367 
4368   //   IntegerPartOfX <<= 23;
4369   IntegerPartOfX = DAG.getNode(
4370       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4371       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4372                                   DAG.getDataLayout())));
4373 
4374   SDValue TwoToFractionalPartOfX;
4375   if (LimitFloatPrecision <= 6) {
4376     // For floating-point precision of 6:
4377     //
4378     //   TwoToFractionalPartOfX =
4379     //     0.997535578f +
4380     //       (0.735607626f + 0.252464424f * x) * x;
4381     //
4382     // error 0.0144103317, which is 6 bits
4383     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4384                              getF32Constant(DAG, 0x3e814304, dl));
4385     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4386                              getF32Constant(DAG, 0x3f3c50c8, dl));
4387     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4388     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4389                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4390   } else if (LimitFloatPrecision <= 12) {
4391     // For floating-point precision of 12:
4392     //
4393     //   TwoToFractionalPartOfX =
4394     //     0.999892986f +
4395     //       (0.696457318f +
4396     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4397     //
4398     // error 0.000107046256, which is 13 to 14 bits
4399     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4400                              getF32Constant(DAG, 0x3da235e3, dl));
4401     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4402                              getF32Constant(DAG, 0x3e65b8f3, dl));
4403     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4404     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4405                              getF32Constant(DAG, 0x3f324b07, dl));
4406     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4407     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4408                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4409   } else { // LimitFloatPrecision <= 18
4410     // For floating-point precision of 18:
4411     //
4412     //   TwoToFractionalPartOfX =
4413     //     0.999999982f +
4414     //       (0.693148872f +
4415     //         (0.240227044f +
4416     //           (0.554906021e-1f +
4417     //             (0.961591928e-2f +
4418     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4419     // error 2.47208000*10^(-7), which is better than 18 bits
4420     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4421                              getF32Constant(DAG, 0x3924b03e, dl));
4422     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4423                              getF32Constant(DAG, 0x3ab24b87, 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, 0x3c1d8c17, dl));
4427     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4428     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4429                              getF32Constant(DAG, 0x3d634a1d, dl));
4430     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4431     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4432                              getF32Constant(DAG, 0x3e75fe14, dl));
4433     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4434     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4435                               getF32Constant(DAG, 0x3f317234, dl));
4436     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4437     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4438                                          getF32Constant(DAG, 0x3f800000, dl));
4439   }
4440 
4441   // Add the exponent into the result in integer domain.
4442   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4443   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4444                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4445 }
4446 
4447 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4448 /// limited-precision mode.
4449 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4450                          const TargetLowering &TLI) {
4451   if (Op.getValueType() == MVT::f32 &&
4452       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4453 
4454     // Put the exponent in the right bit position for later addition to the
4455     // final result:
4456     //
4457     //   #define LOG2OFe 1.4426950f
4458     //   t0 = Op * LOG2OFe
4459 
4460     // TODO: What fast-math-flags should be set here?
4461     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4462                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4463     return getLimitedPrecisionExp2(t0, dl, DAG);
4464   }
4465 
4466   // No special expansion.
4467   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4468 }
4469 
4470 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4471 /// limited-precision mode.
4472 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4473                          const TargetLowering &TLI) {
4474   // TODO: What fast-math-flags should be set on the floating-point nodes?
4475 
4476   if (Op.getValueType() == MVT::f32 &&
4477       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4478     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4479 
4480     // Scale the exponent by log(2) [0.69314718f].
4481     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4482     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4483                                         getF32Constant(DAG, 0x3f317218, dl));
4484 
4485     // Get the significand and build it into a floating-point number with
4486     // exponent of 1.
4487     SDValue X = GetSignificand(DAG, Op1, dl);
4488 
4489     SDValue LogOfMantissa;
4490     if (LimitFloatPrecision <= 6) {
4491       // For floating-point precision of 6:
4492       //
4493       //   LogofMantissa =
4494       //     -1.1609546f +
4495       //       (1.4034025f - 0.23903021f * x) * x;
4496       //
4497       // error 0.0034276066, which is better than 8 bits
4498       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4499                                getF32Constant(DAG, 0xbe74c456, dl));
4500       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4501                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4502       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4503       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4504                                   getF32Constant(DAG, 0x3f949a29, dl));
4505     } else if (LimitFloatPrecision <= 12) {
4506       // For floating-point precision of 12:
4507       //
4508       //   LogOfMantissa =
4509       //     -1.7417939f +
4510       //       (2.8212026f +
4511       //         (-1.4699568f +
4512       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4513       //
4514       // error 0.000061011436, which is 14 bits
4515       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4516                                getF32Constant(DAG, 0xbd67b6d6, dl));
4517       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4518                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4519       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4520       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4521                                getF32Constant(DAG, 0x3fbc278b, dl));
4522       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4523       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4524                                getF32Constant(DAG, 0x40348e95, dl));
4525       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4526       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4527                                   getF32Constant(DAG, 0x3fdef31a, dl));
4528     } else { // LimitFloatPrecision <= 18
4529       // For floating-point precision of 18:
4530       //
4531       //   LogOfMantissa =
4532       //     -2.1072184f +
4533       //       (4.2372794f +
4534       //         (-3.7029485f +
4535       //           (2.2781945f +
4536       //             (-0.87823314f +
4537       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4538       //
4539       // error 0.0000023660568, which is better than 18 bits
4540       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4541                                getF32Constant(DAG, 0xbc91e5ac, dl));
4542       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4543                                getF32Constant(DAG, 0x3e4350aa, dl));
4544       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4545       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4546                                getF32Constant(DAG, 0x3f60d3e3, dl));
4547       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4548       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4549                                getF32Constant(DAG, 0x4011cdf0, dl));
4550       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4551       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4552                                getF32Constant(DAG, 0x406cfd1c, dl));
4553       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4554       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4555                                getF32Constant(DAG, 0x408797cb, dl));
4556       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4557       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4558                                   getF32Constant(DAG, 0x4006dcab, dl));
4559     }
4560 
4561     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4562   }
4563 
4564   // No special expansion.
4565   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4566 }
4567 
4568 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4569 /// limited-precision mode.
4570 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4571                           const TargetLowering &TLI) {
4572   // TODO: What fast-math-flags should be set on the floating-point nodes?
4573 
4574   if (Op.getValueType() == MVT::f32 &&
4575       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4576     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4577 
4578     // Get the exponent.
4579     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4580 
4581     // Get the significand and build it into a floating-point number with
4582     // exponent of 1.
4583     SDValue X = GetSignificand(DAG, Op1, dl);
4584 
4585     // Different possible minimax approximations of significand in
4586     // floating-point for various degrees of accuracy over [1,2].
4587     SDValue Log2ofMantissa;
4588     if (LimitFloatPrecision <= 6) {
4589       // For floating-point precision of 6:
4590       //
4591       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4592       //
4593       // error 0.0049451742, which is more than 7 bits
4594       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4595                                getF32Constant(DAG, 0xbeb08fe0, dl));
4596       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4597                                getF32Constant(DAG, 0x40019463, dl));
4598       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4599       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4600                                    getF32Constant(DAG, 0x3fd6633d, dl));
4601     } else if (LimitFloatPrecision <= 12) {
4602       // For floating-point precision of 12:
4603       //
4604       //   Log2ofMantissa =
4605       //     -2.51285454f +
4606       //       (4.07009056f +
4607       //         (-2.12067489f +
4608       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4609       //
4610       // error 0.0000876136000, which is better than 13 bits
4611       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4612                                getF32Constant(DAG, 0xbda7262e, dl));
4613       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4614                                getF32Constant(DAG, 0x3f25280b, dl));
4615       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4616       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4617                                getF32Constant(DAG, 0x4007b923, dl));
4618       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4619       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4620                                getF32Constant(DAG, 0x40823e2f, dl));
4621       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4622       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4623                                    getF32Constant(DAG, 0x4020d29c, dl));
4624     } else { // LimitFloatPrecision <= 18
4625       // For floating-point precision of 18:
4626       //
4627       //   Log2ofMantissa =
4628       //     -3.0400495f +
4629       //       (6.1129976f +
4630       //         (-5.3420409f +
4631       //           (3.2865683f +
4632       //             (-1.2669343f +
4633       //               (0.27515199f -
4634       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4635       //
4636       // error 0.0000018516, which is better than 18 bits
4637       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4638                                getF32Constant(DAG, 0xbcd2769e, dl));
4639       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4640                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4641       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4642       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4643                                getF32Constant(DAG, 0x3fa22ae7, dl));
4644       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4645       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4646                                getF32Constant(DAG, 0x40525723, dl));
4647       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4648       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4649                                getF32Constant(DAG, 0x40aaf200, dl));
4650       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4651       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4652                                getF32Constant(DAG, 0x40c39dad, dl));
4653       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4654       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4655                                    getF32Constant(DAG, 0x4042902c, dl));
4656     }
4657 
4658     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4659   }
4660 
4661   // No special expansion.
4662   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4663 }
4664 
4665 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4666 /// limited-precision mode.
4667 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4668                            const TargetLowering &TLI) {
4669   // TODO: What fast-math-flags should be set on the floating-point nodes?
4670 
4671   if (Op.getValueType() == MVT::f32 &&
4672       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4673     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4674 
4675     // Scale the exponent by log10(2) [0.30102999f].
4676     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4677     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4678                                         getF32Constant(DAG, 0x3e9a209a, dl));
4679 
4680     // Get the significand and build it into a floating-point number with
4681     // exponent of 1.
4682     SDValue X = GetSignificand(DAG, Op1, dl);
4683 
4684     SDValue Log10ofMantissa;
4685     if (LimitFloatPrecision <= 6) {
4686       // For floating-point precision of 6:
4687       //
4688       //   Log10ofMantissa =
4689       //     -0.50419619f +
4690       //       (0.60948995f - 0.10380950f * x) * x;
4691       //
4692       // error 0.0014886165, which is 6 bits
4693       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4694                                getF32Constant(DAG, 0xbdd49a13, dl));
4695       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4696                                getF32Constant(DAG, 0x3f1c0789, dl));
4697       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4698       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4699                                     getF32Constant(DAG, 0x3f011300, dl));
4700     } else if (LimitFloatPrecision <= 12) {
4701       // For floating-point precision of 12:
4702       //
4703       //   Log10ofMantissa =
4704       //     -0.64831180f +
4705       //       (0.91751397f +
4706       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4707       //
4708       // error 0.00019228036, which is better than 12 bits
4709       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4710                                getF32Constant(DAG, 0x3d431f31, dl));
4711       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4712                                getF32Constant(DAG, 0x3ea21fb2, dl));
4713       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4714       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4715                                getF32Constant(DAG, 0x3f6ae232, dl));
4716       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4717       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4718                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4719     } else { // LimitFloatPrecision <= 18
4720       // For floating-point precision of 18:
4721       //
4722       //   Log10ofMantissa =
4723       //     -0.84299375f +
4724       //       (1.5327582f +
4725       //         (-1.0688956f +
4726       //           (0.49102474f +
4727       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4728       //
4729       // error 0.0000037995730, which is better than 18 bits
4730       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4731                                getF32Constant(DAG, 0x3c5d51ce, dl));
4732       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4733                                getF32Constant(DAG, 0x3e00685a, 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, 0x3efb6798, dl));
4737       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4738       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4739                                getF32Constant(DAG, 0x3f88d192, dl));
4740       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4741       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4742                                getF32Constant(DAG, 0x3fc4316c, dl));
4743       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4744       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4745                                     getF32Constant(DAG, 0x3f57ce70, dl));
4746     }
4747 
4748     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4749   }
4750 
4751   // No special expansion.
4752   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4753 }
4754 
4755 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4756 /// limited-precision mode.
4757 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4758                           const TargetLowering &TLI) {
4759   if (Op.getValueType() == MVT::f32 &&
4760       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4761     return getLimitedPrecisionExp2(Op, dl, DAG);
4762 
4763   // No special expansion.
4764   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4765 }
4766 
4767 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4768 /// limited-precision mode with x == 10.0f.
4769 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4770                          SelectionDAG &DAG, const TargetLowering &TLI) {
4771   bool IsExp10 = false;
4772   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4773       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4774     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4775       APFloat Ten(10.0f);
4776       IsExp10 = LHSC->isExactlyValue(Ten);
4777     }
4778   }
4779 
4780   // TODO: What fast-math-flags should be set on the FMUL node?
4781   if (IsExp10) {
4782     // Put the exponent in the right bit position for later addition to the
4783     // final result:
4784     //
4785     //   #define LOG2OF10 3.3219281f
4786     //   t0 = Op * LOG2OF10;
4787     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4788                              getF32Constant(DAG, 0x40549a78, dl));
4789     return getLimitedPrecisionExp2(t0, dl, DAG);
4790   }
4791 
4792   // No special expansion.
4793   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4794 }
4795 
4796 /// ExpandPowI - Expand a llvm.powi intrinsic.
4797 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4798                           SelectionDAG &DAG) {
4799   // If RHS is a constant, we can expand this out to a multiplication tree,
4800   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4801   // optimizing for size, we only want to do this if the expansion would produce
4802   // a small number of multiplies, otherwise we do the full expansion.
4803   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4804     // Get the exponent as a positive value.
4805     unsigned Val = RHSC->getSExtValue();
4806     if ((int)Val < 0) Val = -Val;
4807 
4808     // powi(x, 0) -> 1.0
4809     if (Val == 0)
4810       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4811 
4812     const Function &F = DAG.getMachineFunction().getFunction();
4813     if (!F.optForSize() ||
4814         // If optimizing for size, don't insert too many multiplies.
4815         // This inserts up to 5 multiplies.
4816         countPopulation(Val) + Log2_32(Val) < 7) {
4817       // We use the simple binary decomposition method to generate the multiply
4818       // sequence.  There are more optimal ways to do this (for example,
4819       // powi(x,15) generates one more multiply than it should), but this has
4820       // the benefit of being both really simple and much better than a libcall.
4821       SDValue Res;  // Logically starts equal to 1.0
4822       SDValue CurSquare = LHS;
4823       // TODO: Intrinsics should have fast-math-flags that propagate to these
4824       // nodes.
4825       while (Val) {
4826         if (Val & 1) {
4827           if (Res.getNode())
4828             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4829           else
4830             Res = CurSquare;  // 1.0*CurSquare.
4831         }
4832 
4833         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4834                                 CurSquare, CurSquare);
4835         Val >>= 1;
4836       }
4837 
4838       // If the original was negative, invert the result, producing 1/(x*x*x).
4839       if (RHSC->getSExtValue() < 0)
4840         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4841                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4842       return Res;
4843     }
4844   }
4845 
4846   // Otherwise, expand to a libcall.
4847   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4848 }
4849 
4850 // getUnderlyingArgReg - Find underlying register used for a truncated or
4851 // bitcasted argument.
4852 static unsigned getUnderlyingArgReg(const SDValue &N) {
4853   switch (N.getOpcode()) {
4854   case ISD::CopyFromReg:
4855     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4856   case ISD::BITCAST:
4857   case ISD::AssertZext:
4858   case ISD::AssertSext:
4859   case ISD::TRUNCATE:
4860     return getUnderlyingArgReg(N.getOperand(0));
4861   default:
4862     return 0;
4863   }
4864 }
4865 
4866 /// If the DbgValueInst is a dbg_value of a function argument, create the
4867 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4868 /// instruction selection, they will be inserted to the entry BB.
4869 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4870     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4871     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4872   const Argument *Arg = dyn_cast<Argument>(V);
4873   if (!Arg)
4874     return false;
4875 
4876   MachineFunction &MF = DAG.getMachineFunction();
4877   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4878 
4879   bool IsIndirect = false;
4880   Optional<MachineOperand> Op;
4881   // Some arguments' frame index is recorded during argument lowering.
4882   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4883   if (FI != std::numeric_limits<int>::max())
4884     Op = MachineOperand::CreateFI(FI);
4885 
4886   if (!Op && N.getNode()) {
4887     unsigned Reg = getUnderlyingArgReg(N);
4888     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4889       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4890       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4891       if (PR)
4892         Reg = PR;
4893     }
4894     if (Reg) {
4895       Op = MachineOperand::CreateReg(Reg, false);
4896       IsIndirect = IsDbgDeclare;
4897     }
4898   }
4899 
4900   if (!Op && N.getNode())
4901     // Check if frame index is available.
4902     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4903       if (FrameIndexSDNode *FINode =
4904           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4905         Op = MachineOperand::CreateFI(FINode->getIndex());
4906 
4907   if (!Op) {
4908     // Check if ValueMap has reg number.
4909     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4910     if (VMI != FuncInfo.ValueMap.end()) {
4911       const auto &TLI = DAG.getTargetLoweringInfo();
4912       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4913                        V->getType(), isABIRegCopy(V));
4914       unsigned NumRegs =
4915           std::accumulate(RFV.RegCount.begin(), RFV.RegCount.end(), 0);
4916       if (NumRegs > 1) {
4917         unsigned I = 0;
4918         unsigned Offset = 0;
4919         auto RegisterVT = RFV.RegVTs.begin();
4920         for (auto RegCount : RFV.RegCount) {
4921           unsigned RegisterSize = (RegisterVT++)->getSizeInBits();
4922           for (unsigned E = I + RegCount; I != E; ++I) {
4923             // The vregs are guaranteed to be allocated in sequence.
4924             Op = MachineOperand::CreateReg(VMI->second + I, false);
4925             auto FragmentExpr = DIExpression::createFragmentExpression(
4926                 Expr, Offset, RegisterSize);
4927             if (!FragmentExpr)
4928               continue;
4929             FuncInfo.ArgDbgValues.push_back(
4930                 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4931                         Op->getReg(), Variable, *FragmentExpr));
4932             Offset += RegisterSize;
4933           }
4934         }
4935         return true;
4936       }
4937       Op = MachineOperand::CreateReg(VMI->second, false);
4938       IsIndirect = IsDbgDeclare;
4939     }
4940   }
4941 
4942   if (!Op)
4943     return false;
4944 
4945   assert(Variable->isValidLocationForIntrinsic(DL) &&
4946          "Expected inlined-at fields to agree");
4947   if (Op->isReg())
4948     FuncInfo.ArgDbgValues.push_back(
4949         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4950                 Op->getReg(), Variable, Expr));
4951   else
4952     FuncInfo.ArgDbgValues.push_back(
4953         BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4954             .add(*Op)
4955             .addImm(0)
4956             .addMetadata(Variable)
4957             .addMetadata(Expr));
4958 
4959   return true;
4960 }
4961 
4962 /// Return the appropriate SDDbgValue based on N.
4963 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
4964                                              DILocalVariable *Variable,
4965                                              DIExpression *Expr,
4966                                              const DebugLoc &dl,
4967                                              unsigned DbgSDNodeOrder) {
4968   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
4969     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
4970     // stack slot locations as such instead of as indirectly addressed
4971     // locations.
4972     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl,
4973                                      DbgSDNodeOrder);
4974   }
4975   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl,
4976                          DbgSDNodeOrder);
4977 }
4978 
4979 // VisualStudio defines setjmp as _setjmp
4980 #if defined(_MSC_VER) && defined(setjmp) && \
4981                          !defined(setjmp_undefined_for_msvc)
4982 #  pragma push_macro("setjmp")
4983 #  undef setjmp
4984 #  define setjmp_undefined_for_msvc
4985 #endif
4986 
4987 /// Lower the call to the specified intrinsic function. If we want to emit this
4988 /// as a call to a named external function, return the name. Otherwise, lower it
4989 /// and return null.
4990 const char *
4991 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4992   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4993   SDLoc sdl = getCurSDLoc();
4994   DebugLoc dl = getCurDebugLoc();
4995   SDValue Res;
4996 
4997   switch (Intrinsic) {
4998   default:
4999     // By default, turn this into a target intrinsic node.
5000     visitTargetIntrinsic(I, Intrinsic);
5001     return nullptr;
5002   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5003   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5004   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5005   case Intrinsic::returnaddress:
5006     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5007                              TLI.getPointerTy(DAG.getDataLayout()),
5008                              getValue(I.getArgOperand(0))));
5009     return nullptr;
5010   case Intrinsic::addressofreturnaddress:
5011     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5012                              TLI.getPointerTy(DAG.getDataLayout())));
5013     return nullptr;
5014   case Intrinsic::frameaddress:
5015     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5016                              TLI.getPointerTy(DAG.getDataLayout()),
5017                              getValue(I.getArgOperand(0))));
5018     return nullptr;
5019   case Intrinsic::read_register: {
5020     Value *Reg = I.getArgOperand(0);
5021     SDValue Chain = getRoot();
5022     SDValue RegName =
5023         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5024     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5025     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5026       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5027     setValue(&I, Res);
5028     DAG.setRoot(Res.getValue(1));
5029     return nullptr;
5030   }
5031   case Intrinsic::write_register: {
5032     Value *Reg = I.getArgOperand(0);
5033     Value *RegValue = I.getArgOperand(1);
5034     SDValue Chain = getRoot();
5035     SDValue RegName =
5036         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5037     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5038                             RegName, getValue(RegValue)));
5039     return nullptr;
5040   }
5041   case Intrinsic::setjmp:
5042     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5043   case Intrinsic::longjmp:
5044     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5045   case Intrinsic::memcpy: {
5046     const auto &MCI = cast<MemCpyInst>(I);
5047     SDValue Op1 = getValue(I.getArgOperand(0));
5048     SDValue Op2 = getValue(I.getArgOperand(1));
5049     SDValue Op3 = getValue(I.getArgOperand(2));
5050     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5051     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5052     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5053     unsigned Align = MinAlign(DstAlign, SrcAlign);
5054     bool isVol = MCI.isVolatile();
5055     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5056     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5057     // node.
5058     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5059                                false, isTC,
5060                                MachinePointerInfo(I.getArgOperand(0)),
5061                                MachinePointerInfo(I.getArgOperand(1)));
5062     updateDAGForMaybeTailCall(MC);
5063     return nullptr;
5064   }
5065   case Intrinsic::memset: {
5066     const auto &MSI = cast<MemSetInst>(I);
5067     SDValue Op1 = getValue(I.getArgOperand(0));
5068     SDValue Op2 = getValue(I.getArgOperand(1));
5069     SDValue Op3 = getValue(I.getArgOperand(2));
5070     // @llvm.memset defines 0 and 1 to both mean no alignment.
5071     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5072     bool isVol = MSI.isVolatile();
5073     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5074     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5075                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5076     updateDAGForMaybeTailCall(MS);
5077     return nullptr;
5078   }
5079   case Intrinsic::memmove: {
5080     const auto &MMI = cast<MemMoveInst>(I);
5081     SDValue Op1 = getValue(I.getArgOperand(0));
5082     SDValue Op2 = getValue(I.getArgOperand(1));
5083     SDValue Op3 = getValue(I.getArgOperand(2));
5084     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5085     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5086     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5087     unsigned Align = MinAlign(DstAlign, SrcAlign);
5088     bool isVol = MMI.isVolatile();
5089     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5090     // FIXME: Support passing different dest/src alignments to the memmove DAG
5091     // node.
5092     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5093                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5094                                 MachinePointerInfo(I.getArgOperand(1)));
5095     updateDAGForMaybeTailCall(MM);
5096     return nullptr;
5097   }
5098   case Intrinsic::memcpy_element_unordered_atomic: {
5099     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5100     SDValue Dst = getValue(MI.getRawDest());
5101     SDValue Src = getValue(MI.getRawSource());
5102     SDValue Length = getValue(MI.getLength());
5103 
5104     // Emit a library call.
5105     TargetLowering::ArgListTy Args;
5106     TargetLowering::ArgListEntry Entry;
5107     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
5108     Entry.Node = Dst;
5109     Args.push_back(Entry);
5110 
5111     Entry.Node = Src;
5112     Args.push_back(Entry);
5113 
5114     Entry.Ty = MI.getLength()->getType();
5115     Entry.Node = Length;
5116     Args.push_back(Entry);
5117 
5118     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
5119     RTLIB::Libcall LibraryCall =
5120         RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
5121     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5122       report_fatal_error("Unsupported element size");
5123 
5124     TargetLowering::CallLoweringInfo CLI(DAG);
5125     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5126         TLI.getLibcallCallingConv(LibraryCall),
5127         Type::getVoidTy(*DAG.getContext()),
5128         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
5129                               TLI.getPointerTy(DAG.getDataLayout())),
5130         std::move(Args));
5131 
5132     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
5133     DAG.setRoot(CallResult.second);
5134     return nullptr;
5135   }
5136   case Intrinsic::memmove_element_unordered_atomic: {
5137     auto &MI = cast<AtomicMemMoveInst>(I);
5138     SDValue Dst = getValue(MI.getRawDest());
5139     SDValue Src = getValue(MI.getRawSource());
5140     SDValue Length = getValue(MI.getLength());
5141 
5142     // Emit a library call.
5143     TargetLowering::ArgListTy Args;
5144     TargetLowering::ArgListEntry Entry;
5145     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
5146     Entry.Node = Dst;
5147     Args.push_back(Entry);
5148 
5149     Entry.Node = Src;
5150     Args.push_back(Entry);
5151 
5152     Entry.Ty = MI.getLength()->getType();
5153     Entry.Node = Length;
5154     Args.push_back(Entry);
5155 
5156     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
5157     RTLIB::Libcall LibraryCall =
5158         RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
5159     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5160       report_fatal_error("Unsupported element size");
5161 
5162     TargetLowering::CallLoweringInfo CLI(DAG);
5163     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5164         TLI.getLibcallCallingConv(LibraryCall),
5165         Type::getVoidTy(*DAG.getContext()),
5166         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
5167                               TLI.getPointerTy(DAG.getDataLayout())),
5168         std::move(Args));
5169 
5170     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
5171     DAG.setRoot(CallResult.second);
5172     return nullptr;
5173   }
5174   case Intrinsic::memset_element_unordered_atomic: {
5175     auto &MI = cast<AtomicMemSetInst>(I);
5176     SDValue Dst = getValue(MI.getRawDest());
5177     SDValue Val = getValue(MI.getValue());
5178     SDValue Length = getValue(MI.getLength());
5179 
5180     // Emit a library call.
5181     TargetLowering::ArgListTy Args;
5182     TargetLowering::ArgListEntry Entry;
5183     Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
5184     Entry.Node = Dst;
5185     Args.push_back(Entry);
5186 
5187     Entry.Ty = Type::getInt8Ty(*DAG.getContext());
5188     Entry.Node = Val;
5189     Args.push_back(Entry);
5190 
5191     Entry.Ty = MI.getLength()->getType();
5192     Entry.Node = Length;
5193     Args.push_back(Entry);
5194 
5195     uint64_t ElementSizeConstant = MI.getElementSizeInBytes();
5196     RTLIB::Libcall LibraryCall =
5197         RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant);
5198     if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5199       report_fatal_error("Unsupported element size");
5200 
5201     TargetLowering::CallLoweringInfo CLI(DAG);
5202     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5203         TLI.getLibcallCallingConv(LibraryCall),
5204         Type::getVoidTy(*DAG.getContext()),
5205         DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall),
5206                               TLI.getPointerTy(DAG.getDataLayout())),
5207         std::move(Args));
5208 
5209     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
5210     DAG.setRoot(CallResult.second);
5211     return nullptr;
5212   }
5213   case Intrinsic::dbg_addr:
5214   case Intrinsic::dbg_declare: {
5215     const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I);
5216     DILocalVariable *Variable = DI.getVariable();
5217     DIExpression *Expression = DI.getExpression();
5218     dropDanglingDebugInfo(Variable, Expression);
5219     assert(Variable && "Missing variable");
5220 
5221     // Check if address has undef value.
5222     const Value *Address = DI.getVariableLocation();
5223     if (!Address || isa<UndefValue>(Address) ||
5224         (Address->use_empty() && !isa<Argument>(Address))) {
5225       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5226       return nullptr;
5227     }
5228 
5229     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5230 
5231     // Check if this variable can be described by a frame index, typically
5232     // either as a static alloca or a byval parameter.
5233     int FI = std::numeric_limits<int>::max();
5234     if (const auto *AI =
5235             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5236       if (AI->isStaticAlloca()) {
5237         auto I = FuncInfo.StaticAllocaMap.find(AI);
5238         if (I != FuncInfo.StaticAllocaMap.end())
5239           FI = I->second;
5240       }
5241     } else if (const auto *Arg = dyn_cast<Argument>(
5242                    Address->stripInBoundsConstantOffsets())) {
5243       FI = FuncInfo.getArgumentFrameIndex(Arg);
5244     }
5245 
5246     // llvm.dbg.addr is control dependent and always generates indirect
5247     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5248     // the MachineFunction variable table.
5249     if (FI != std::numeric_limits<int>::max()) {
5250       if (Intrinsic == Intrinsic::dbg_addr) {
5251          SDDbgValue *SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5252                                                      FI, dl, SDNodeOrder);
5253          DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5254       }
5255       return nullptr;
5256     }
5257 
5258     SDValue &N = NodeMap[Address];
5259     if (!N.getNode() && isa<Argument>(Address))
5260       // Check unused arguments map.
5261       N = UnusedArgNodeMap[Address];
5262     SDDbgValue *SDV;
5263     if (N.getNode()) {
5264       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5265         Address = BCI->getOperand(0);
5266       // Parameters are handled specially.
5267       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5268       if (isParameter && FINode) {
5269         // Byval parameter. We have a frame index at this point.
5270         SDV = DAG.getFrameIndexDbgValue(Variable, Expression,
5271                                         FINode->getIndex(), dl, SDNodeOrder);
5272       } else if (isa<Argument>(Address)) {
5273         // Address is an argument, so try to emit its dbg value using
5274         // virtual register info from the FuncInfo.ValueMap.
5275         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5276         return nullptr;
5277       } else {
5278         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5279                               true, dl, SDNodeOrder);
5280       }
5281       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5282     } else {
5283       // If Address is an argument then try to emit its dbg value using
5284       // virtual register info from the FuncInfo.ValueMap.
5285       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5286                                     N)) {
5287         DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5288       }
5289     }
5290     return nullptr;
5291   }
5292   case Intrinsic::dbg_value: {
5293     const DbgValueInst &DI = cast<DbgValueInst>(I);
5294     assert(DI.getVariable() && "Missing variable");
5295 
5296     DILocalVariable *Variable = DI.getVariable();
5297     DIExpression *Expression = DI.getExpression();
5298     dropDanglingDebugInfo(Variable, Expression);
5299     const Value *V = DI.getValue();
5300     if (!V)
5301       return nullptr;
5302 
5303     SDDbgValue *SDV;
5304     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5305       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5306       DAG.AddDbgValue(SDV, nullptr, false);
5307       return nullptr;
5308     }
5309 
5310     // Do not use getValue() in here; we don't want to generate code at
5311     // this point if it hasn't been done yet.
5312     SDValue N = NodeMap[V];
5313     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5314       N = UnusedArgNodeMap[V];
5315     if (N.getNode()) {
5316       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5317         return nullptr;
5318       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5319       DAG.AddDbgValue(SDV, N.getNode(), false);
5320       return nullptr;
5321     }
5322 
5323     // TODO: When we get here we will either drop the dbg.value completely, or
5324     // we try to move it forward by letting it dangle for awhile. So we should
5325     // probably add an extra DbgValue to the DAG here, with a reference to
5326     // "noreg", to indicate that we have lost the debug location for the
5327     // variable.
5328 
5329     if (!V->use_empty() ) {
5330       // Do not call getValue(V) yet, as we don't want to generate code.
5331       // Remember it for later.
5332       DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
5333       DanglingDebugInfoMap[V] = DDI;
5334       return nullptr;
5335     }
5336 
5337     DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5338     DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5339     return nullptr;
5340   }
5341 
5342   case Intrinsic::eh_typeid_for: {
5343     // Find the type id for the given typeinfo.
5344     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5345     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5346     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5347     setValue(&I, Res);
5348     return nullptr;
5349   }
5350 
5351   case Intrinsic::eh_return_i32:
5352   case Intrinsic::eh_return_i64:
5353     DAG.getMachineFunction().setCallsEHReturn(true);
5354     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5355                             MVT::Other,
5356                             getControlRoot(),
5357                             getValue(I.getArgOperand(0)),
5358                             getValue(I.getArgOperand(1))));
5359     return nullptr;
5360   case Intrinsic::eh_unwind_init:
5361     DAG.getMachineFunction().setCallsUnwindInit(true);
5362     return nullptr;
5363   case Intrinsic::eh_dwarf_cfa:
5364     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5365                              TLI.getPointerTy(DAG.getDataLayout()),
5366                              getValue(I.getArgOperand(0))));
5367     return nullptr;
5368   case Intrinsic::eh_sjlj_callsite: {
5369     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5370     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5371     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5372     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5373 
5374     MMI.setCurrentCallSite(CI->getZExtValue());
5375     return nullptr;
5376   }
5377   case Intrinsic::eh_sjlj_functioncontext: {
5378     // Get and store the index of the function context.
5379     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5380     AllocaInst *FnCtx =
5381       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5382     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5383     MFI.setFunctionContextIndex(FI);
5384     return nullptr;
5385   }
5386   case Intrinsic::eh_sjlj_setjmp: {
5387     SDValue Ops[2];
5388     Ops[0] = getRoot();
5389     Ops[1] = getValue(I.getArgOperand(0));
5390     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5391                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5392     setValue(&I, Op.getValue(0));
5393     DAG.setRoot(Op.getValue(1));
5394     return nullptr;
5395   }
5396   case Intrinsic::eh_sjlj_longjmp:
5397     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5398                             getRoot(), getValue(I.getArgOperand(0))));
5399     return nullptr;
5400   case Intrinsic::eh_sjlj_setup_dispatch:
5401     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5402                             getRoot()));
5403     return nullptr;
5404   case Intrinsic::masked_gather:
5405     visitMaskedGather(I);
5406     return nullptr;
5407   case Intrinsic::masked_load:
5408     visitMaskedLoad(I);
5409     return nullptr;
5410   case Intrinsic::masked_scatter:
5411     visitMaskedScatter(I);
5412     return nullptr;
5413   case Intrinsic::masked_store:
5414     visitMaskedStore(I);
5415     return nullptr;
5416   case Intrinsic::masked_expandload:
5417     visitMaskedLoad(I, true /* IsExpanding */);
5418     return nullptr;
5419   case Intrinsic::masked_compressstore:
5420     visitMaskedStore(I, true /* IsCompressing */);
5421     return nullptr;
5422   case Intrinsic::x86_mmx_pslli_w:
5423   case Intrinsic::x86_mmx_pslli_d:
5424   case Intrinsic::x86_mmx_pslli_q:
5425   case Intrinsic::x86_mmx_psrli_w:
5426   case Intrinsic::x86_mmx_psrli_d:
5427   case Intrinsic::x86_mmx_psrli_q:
5428   case Intrinsic::x86_mmx_psrai_w:
5429   case Intrinsic::x86_mmx_psrai_d: {
5430     SDValue ShAmt = getValue(I.getArgOperand(1));
5431     if (isa<ConstantSDNode>(ShAmt)) {
5432       visitTargetIntrinsic(I, Intrinsic);
5433       return nullptr;
5434     }
5435     unsigned NewIntrinsic = 0;
5436     EVT ShAmtVT = MVT::v2i32;
5437     switch (Intrinsic) {
5438     case Intrinsic::x86_mmx_pslli_w:
5439       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5440       break;
5441     case Intrinsic::x86_mmx_pslli_d:
5442       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5443       break;
5444     case Intrinsic::x86_mmx_pslli_q:
5445       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5446       break;
5447     case Intrinsic::x86_mmx_psrli_w:
5448       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5449       break;
5450     case Intrinsic::x86_mmx_psrli_d:
5451       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5452       break;
5453     case Intrinsic::x86_mmx_psrli_q:
5454       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5455       break;
5456     case Intrinsic::x86_mmx_psrai_w:
5457       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5458       break;
5459     case Intrinsic::x86_mmx_psrai_d:
5460       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5461       break;
5462     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5463     }
5464 
5465     // The vector shift intrinsics with scalars uses 32b shift amounts but
5466     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5467     // to be zero.
5468     // We must do this early because v2i32 is not a legal type.
5469     SDValue ShOps[2];
5470     ShOps[0] = ShAmt;
5471     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5472     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5473     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5474     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5475     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5476                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5477                        getValue(I.getArgOperand(0)), ShAmt);
5478     setValue(&I, Res);
5479     return nullptr;
5480   }
5481   case Intrinsic::powi:
5482     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5483                             getValue(I.getArgOperand(1)), DAG));
5484     return nullptr;
5485   case Intrinsic::log:
5486     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5487     return nullptr;
5488   case Intrinsic::log2:
5489     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5490     return nullptr;
5491   case Intrinsic::log10:
5492     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5493     return nullptr;
5494   case Intrinsic::exp:
5495     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5496     return nullptr;
5497   case Intrinsic::exp2:
5498     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5499     return nullptr;
5500   case Intrinsic::pow:
5501     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5502                            getValue(I.getArgOperand(1)), DAG, TLI));
5503     return nullptr;
5504   case Intrinsic::sqrt:
5505   case Intrinsic::fabs:
5506   case Intrinsic::sin:
5507   case Intrinsic::cos:
5508   case Intrinsic::floor:
5509   case Intrinsic::ceil:
5510   case Intrinsic::trunc:
5511   case Intrinsic::rint:
5512   case Intrinsic::nearbyint:
5513   case Intrinsic::round:
5514   case Intrinsic::canonicalize: {
5515     unsigned Opcode;
5516     switch (Intrinsic) {
5517     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5518     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5519     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5520     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5521     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5522     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5523     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5524     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5525     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5526     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5527     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5528     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5529     }
5530 
5531     setValue(&I, DAG.getNode(Opcode, sdl,
5532                              getValue(I.getArgOperand(0)).getValueType(),
5533                              getValue(I.getArgOperand(0))));
5534     return nullptr;
5535   }
5536   case Intrinsic::minnum: {
5537     auto VT = getValue(I.getArgOperand(0)).getValueType();
5538     unsigned Opc =
5539         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)
5540             ? ISD::FMINNAN
5541             : ISD::FMINNUM;
5542     setValue(&I, DAG.getNode(Opc, sdl, VT,
5543                              getValue(I.getArgOperand(0)),
5544                              getValue(I.getArgOperand(1))));
5545     return nullptr;
5546   }
5547   case Intrinsic::maxnum: {
5548     auto VT = getValue(I.getArgOperand(0)).getValueType();
5549     unsigned Opc =
5550         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)
5551             ? ISD::FMAXNAN
5552             : ISD::FMAXNUM;
5553     setValue(&I, DAG.getNode(Opc, sdl, VT,
5554                              getValue(I.getArgOperand(0)),
5555                              getValue(I.getArgOperand(1))));
5556     return nullptr;
5557   }
5558   case Intrinsic::copysign:
5559     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5560                              getValue(I.getArgOperand(0)).getValueType(),
5561                              getValue(I.getArgOperand(0)),
5562                              getValue(I.getArgOperand(1))));
5563     return nullptr;
5564   case Intrinsic::fma:
5565     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5566                              getValue(I.getArgOperand(0)).getValueType(),
5567                              getValue(I.getArgOperand(0)),
5568                              getValue(I.getArgOperand(1)),
5569                              getValue(I.getArgOperand(2))));
5570     return nullptr;
5571   case Intrinsic::experimental_constrained_fadd:
5572   case Intrinsic::experimental_constrained_fsub:
5573   case Intrinsic::experimental_constrained_fmul:
5574   case Intrinsic::experimental_constrained_fdiv:
5575   case Intrinsic::experimental_constrained_frem:
5576   case Intrinsic::experimental_constrained_fma:
5577   case Intrinsic::experimental_constrained_sqrt:
5578   case Intrinsic::experimental_constrained_pow:
5579   case Intrinsic::experimental_constrained_powi:
5580   case Intrinsic::experimental_constrained_sin:
5581   case Intrinsic::experimental_constrained_cos:
5582   case Intrinsic::experimental_constrained_exp:
5583   case Intrinsic::experimental_constrained_exp2:
5584   case Intrinsic::experimental_constrained_log:
5585   case Intrinsic::experimental_constrained_log10:
5586   case Intrinsic::experimental_constrained_log2:
5587   case Intrinsic::experimental_constrained_rint:
5588   case Intrinsic::experimental_constrained_nearbyint:
5589     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5590     return nullptr;
5591   case Intrinsic::fmuladd: {
5592     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5593     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5594         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5595       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5596                                getValue(I.getArgOperand(0)).getValueType(),
5597                                getValue(I.getArgOperand(0)),
5598                                getValue(I.getArgOperand(1)),
5599                                getValue(I.getArgOperand(2))));
5600     } else {
5601       // TODO: Intrinsic calls should have fast-math-flags.
5602       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5603                                 getValue(I.getArgOperand(0)).getValueType(),
5604                                 getValue(I.getArgOperand(0)),
5605                                 getValue(I.getArgOperand(1)));
5606       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5607                                 getValue(I.getArgOperand(0)).getValueType(),
5608                                 Mul,
5609                                 getValue(I.getArgOperand(2)));
5610       setValue(&I, Add);
5611     }
5612     return nullptr;
5613   }
5614   case Intrinsic::convert_to_fp16:
5615     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5616                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5617                                          getValue(I.getArgOperand(0)),
5618                                          DAG.getTargetConstant(0, sdl,
5619                                                                MVT::i32))));
5620     return nullptr;
5621   case Intrinsic::convert_from_fp16:
5622     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5623                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5624                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5625                                          getValue(I.getArgOperand(0)))));
5626     return nullptr;
5627   case Intrinsic::pcmarker: {
5628     SDValue Tmp = getValue(I.getArgOperand(0));
5629     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5630     return nullptr;
5631   }
5632   case Intrinsic::readcyclecounter: {
5633     SDValue Op = getRoot();
5634     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5635                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5636     setValue(&I, Res);
5637     DAG.setRoot(Res.getValue(1));
5638     return nullptr;
5639   }
5640   case Intrinsic::bitreverse:
5641     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5642                              getValue(I.getArgOperand(0)).getValueType(),
5643                              getValue(I.getArgOperand(0))));
5644     return nullptr;
5645   case Intrinsic::bswap:
5646     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5647                              getValue(I.getArgOperand(0)).getValueType(),
5648                              getValue(I.getArgOperand(0))));
5649     return nullptr;
5650   case Intrinsic::cttz: {
5651     SDValue Arg = getValue(I.getArgOperand(0));
5652     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5653     EVT Ty = Arg.getValueType();
5654     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5655                              sdl, Ty, Arg));
5656     return nullptr;
5657   }
5658   case Intrinsic::ctlz: {
5659     SDValue Arg = getValue(I.getArgOperand(0));
5660     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5661     EVT Ty = Arg.getValueType();
5662     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5663                              sdl, Ty, Arg));
5664     return nullptr;
5665   }
5666   case Intrinsic::ctpop: {
5667     SDValue Arg = getValue(I.getArgOperand(0));
5668     EVT Ty = Arg.getValueType();
5669     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5670     return nullptr;
5671   }
5672   case Intrinsic::stacksave: {
5673     SDValue Op = getRoot();
5674     Res = DAG.getNode(
5675         ISD::STACKSAVE, sdl,
5676         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5677     setValue(&I, Res);
5678     DAG.setRoot(Res.getValue(1));
5679     return nullptr;
5680   }
5681   case Intrinsic::stackrestore:
5682     Res = getValue(I.getArgOperand(0));
5683     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5684     return nullptr;
5685   case Intrinsic::get_dynamic_area_offset: {
5686     SDValue Op = getRoot();
5687     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5688     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5689     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5690     // target.
5691     if (PtrTy != ResTy)
5692       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5693                          " intrinsic!");
5694     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5695                       Op);
5696     DAG.setRoot(Op);
5697     setValue(&I, Res);
5698     return nullptr;
5699   }
5700   case Intrinsic::stackguard: {
5701     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5702     MachineFunction &MF = DAG.getMachineFunction();
5703     const Module &M = *MF.getFunction().getParent();
5704     SDValue Chain = getRoot();
5705     if (TLI.useLoadStackGuardNode()) {
5706       Res = getLoadStackGuard(DAG, sdl, Chain);
5707     } else {
5708       const Value *Global = TLI.getSDagStackGuard(M);
5709       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5710       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5711                         MachinePointerInfo(Global, 0), Align,
5712                         MachineMemOperand::MOVolatile);
5713     }
5714     if (TLI.useStackGuardXorFP())
5715       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5716     DAG.setRoot(Chain);
5717     setValue(&I, Res);
5718     return nullptr;
5719   }
5720   case Intrinsic::stackprotector: {
5721     // Emit code into the DAG to store the stack guard onto the stack.
5722     MachineFunction &MF = DAG.getMachineFunction();
5723     MachineFrameInfo &MFI = MF.getFrameInfo();
5724     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5725     SDValue Src, Chain = getRoot();
5726 
5727     if (TLI.useLoadStackGuardNode())
5728       Src = getLoadStackGuard(DAG, sdl, Chain);
5729     else
5730       Src = getValue(I.getArgOperand(0));   // The guard's value.
5731 
5732     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5733 
5734     int FI = FuncInfo.StaticAllocaMap[Slot];
5735     MFI.setStackProtectorIndex(FI);
5736 
5737     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5738 
5739     // Store the stack protector onto the stack.
5740     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5741                                                  DAG.getMachineFunction(), FI),
5742                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5743     setValue(&I, Res);
5744     DAG.setRoot(Res);
5745     return nullptr;
5746   }
5747   case Intrinsic::objectsize: {
5748     // If we don't know by now, we're never going to know.
5749     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5750 
5751     assert(CI && "Non-constant type in __builtin_object_size?");
5752 
5753     SDValue Arg = getValue(I.getCalledValue());
5754     EVT Ty = Arg.getValueType();
5755 
5756     if (CI->isZero())
5757       Res = DAG.getConstant(-1ULL, sdl, Ty);
5758     else
5759       Res = DAG.getConstant(0, sdl, Ty);
5760 
5761     setValue(&I, Res);
5762     return nullptr;
5763   }
5764   case Intrinsic::annotation:
5765   case Intrinsic::ptr_annotation:
5766   case Intrinsic::invariant_group_barrier:
5767     // Drop the intrinsic, but forward the value
5768     setValue(&I, getValue(I.getOperand(0)));
5769     return nullptr;
5770   case Intrinsic::assume:
5771   case Intrinsic::var_annotation:
5772   case Intrinsic::sideeffect:
5773     // Discard annotate attributes, assumptions, and artificial side-effects.
5774     return nullptr;
5775 
5776   case Intrinsic::codeview_annotation: {
5777     // Emit a label associated with this metadata.
5778     MachineFunction &MF = DAG.getMachineFunction();
5779     MCSymbol *Label =
5780         MF.getMMI().getContext().createTempSymbol("annotation", true);
5781     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5782     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5783     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5784     DAG.setRoot(Res);
5785     return nullptr;
5786   }
5787 
5788   case Intrinsic::init_trampoline: {
5789     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5790 
5791     SDValue Ops[6];
5792     Ops[0] = getRoot();
5793     Ops[1] = getValue(I.getArgOperand(0));
5794     Ops[2] = getValue(I.getArgOperand(1));
5795     Ops[3] = getValue(I.getArgOperand(2));
5796     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5797     Ops[5] = DAG.getSrcValue(F);
5798 
5799     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5800 
5801     DAG.setRoot(Res);
5802     return nullptr;
5803   }
5804   case Intrinsic::adjust_trampoline:
5805     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5806                              TLI.getPointerTy(DAG.getDataLayout()),
5807                              getValue(I.getArgOperand(0))));
5808     return nullptr;
5809   case Intrinsic::gcroot: {
5810     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5811            "only valid in functions with gc specified, enforced by Verifier");
5812     assert(GFI && "implied by previous");
5813     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5814     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5815 
5816     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5817     GFI->addStackRoot(FI->getIndex(), TypeMap);
5818     return nullptr;
5819   }
5820   case Intrinsic::gcread:
5821   case Intrinsic::gcwrite:
5822     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5823   case Intrinsic::flt_rounds:
5824     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5825     return nullptr;
5826 
5827   case Intrinsic::expect:
5828     // Just replace __builtin_expect(exp, c) with EXP.
5829     setValue(&I, getValue(I.getArgOperand(0)));
5830     return nullptr;
5831 
5832   case Intrinsic::debugtrap:
5833   case Intrinsic::trap: {
5834     StringRef TrapFuncName =
5835         I.getAttributes()
5836             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5837             .getValueAsString();
5838     if (TrapFuncName.empty()) {
5839       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5840         ISD::TRAP : ISD::DEBUGTRAP;
5841       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5842       return nullptr;
5843     }
5844     TargetLowering::ArgListTy Args;
5845 
5846     TargetLowering::CallLoweringInfo CLI(DAG);
5847     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
5848         CallingConv::C, I.getType(),
5849         DAG.getExternalSymbol(TrapFuncName.data(),
5850                               TLI.getPointerTy(DAG.getDataLayout())),
5851         std::move(Args));
5852 
5853     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5854     DAG.setRoot(Result.second);
5855     return nullptr;
5856   }
5857 
5858   case Intrinsic::uadd_with_overflow:
5859   case Intrinsic::sadd_with_overflow:
5860   case Intrinsic::usub_with_overflow:
5861   case Intrinsic::ssub_with_overflow:
5862   case Intrinsic::umul_with_overflow:
5863   case Intrinsic::smul_with_overflow: {
5864     ISD::NodeType Op;
5865     switch (Intrinsic) {
5866     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5867     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5868     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5869     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5870     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5871     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5872     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5873     }
5874     SDValue Op1 = getValue(I.getArgOperand(0));
5875     SDValue Op2 = getValue(I.getArgOperand(1));
5876 
5877     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5878     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5879     return nullptr;
5880   }
5881   case Intrinsic::prefetch: {
5882     SDValue Ops[5];
5883     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5884     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
5885     Ops[0] = DAG.getRoot();
5886     Ops[1] = getValue(I.getArgOperand(0));
5887     Ops[2] = getValue(I.getArgOperand(1));
5888     Ops[3] = getValue(I.getArgOperand(2));
5889     Ops[4] = getValue(I.getArgOperand(3));
5890     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5891                                              DAG.getVTList(MVT::Other), Ops,
5892                                              EVT::getIntegerVT(*Context, 8),
5893                                              MachinePointerInfo(I.getArgOperand(0)),
5894                                              0, /* align */
5895                                              Flags);
5896 
5897     // Chain the prefetch in parallell with any pending loads, to stay out of
5898     // the way of later optimizations.
5899     PendingLoads.push_back(Result);
5900     Result = getRoot();
5901     DAG.setRoot(Result);
5902     return nullptr;
5903   }
5904   case Intrinsic::lifetime_start:
5905   case Intrinsic::lifetime_end: {
5906     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5907     // Stack coloring is not enabled in O0, discard region information.
5908     if (TM.getOptLevel() == CodeGenOpt::None)
5909       return nullptr;
5910 
5911     SmallVector<Value *, 4> Allocas;
5912     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5913 
5914     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5915            E = Allocas.end(); Object != E; ++Object) {
5916       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5917 
5918       // Could not find an Alloca.
5919       if (!LifetimeObject)
5920         continue;
5921 
5922       // First check that the Alloca is static, otherwise it won't have a
5923       // valid frame index.
5924       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5925       if (SI == FuncInfo.StaticAllocaMap.end())
5926         return nullptr;
5927 
5928       int FI = SI->second;
5929 
5930       SDValue Ops[2];
5931       Ops[0] = getRoot();
5932       Ops[1] =
5933           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
5934       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5935 
5936       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5937       DAG.setRoot(Res);
5938     }
5939     return nullptr;
5940   }
5941   case Intrinsic::invariant_start:
5942     // Discard region information.
5943     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5944     return nullptr;
5945   case Intrinsic::invariant_end:
5946     // Discard region information.
5947     return nullptr;
5948   case Intrinsic::clear_cache:
5949     return TLI.getClearCacheBuiltinName();
5950   case Intrinsic::donothing:
5951     // ignore
5952     return nullptr;
5953   case Intrinsic::experimental_stackmap:
5954     visitStackmap(I);
5955     return nullptr;
5956   case Intrinsic::experimental_patchpoint_void:
5957   case Intrinsic::experimental_patchpoint_i64:
5958     visitPatchpoint(&I);
5959     return nullptr;
5960   case Intrinsic::experimental_gc_statepoint:
5961     LowerStatepoint(ImmutableStatepoint(&I));
5962     return nullptr;
5963   case Intrinsic::experimental_gc_result:
5964     visitGCResult(cast<GCResultInst>(I));
5965     return nullptr;
5966   case Intrinsic::experimental_gc_relocate:
5967     visitGCRelocate(cast<GCRelocateInst>(I));
5968     return nullptr;
5969   case Intrinsic::instrprof_increment:
5970     llvm_unreachable("instrprof failed to lower an increment");
5971   case Intrinsic::instrprof_value_profile:
5972     llvm_unreachable("instrprof failed to lower a value profiling call");
5973   case Intrinsic::localescape: {
5974     MachineFunction &MF = DAG.getMachineFunction();
5975     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5976 
5977     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5978     // is the same on all targets.
5979     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5980       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5981       if (isa<ConstantPointerNull>(Arg))
5982         continue; // Skip null pointers. They represent a hole in index space.
5983       AllocaInst *Slot = cast<AllocaInst>(Arg);
5984       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5985              "can only escape static allocas");
5986       int FI = FuncInfo.StaticAllocaMap[Slot];
5987       MCSymbol *FrameAllocSym =
5988           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5989               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
5990       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5991               TII->get(TargetOpcode::LOCAL_ESCAPE))
5992           .addSym(FrameAllocSym)
5993           .addFrameIndex(FI);
5994     }
5995 
5996     return nullptr;
5997   }
5998 
5999   case Intrinsic::localrecover: {
6000     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6001     MachineFunction &MF = DAG.getMachineFunction();
6002     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6003 
6004     // Get the symbol that defines the frame offset.
6005     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6006     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6007     unsigned IdxVal =
6008         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6009     MCSymbol *FrameAllocSym =
6010         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6011             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6012 
6013     // Create a MCSymbol for the label to avoid any target lowering
6014     // that would make this PC relative.
6015     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6016     SDValue OffsetVal =
6017         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6018 
6019     // Add the offset to the FP.
6020     Value *FP = I.getArgOperand(1);
6021     SDValue FPVal = getValue(FP);
6022     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6023     setValue(&I, Add);
6024 
6025     return nullptr;
6026   }
6027 
6028   case Intrinsic::eh_exceptionpointer:
6029   case Intrinsic::eh_exceptioncode: {
6030     // Get the exception pointer vreg, copy from it, and resize it to fit.
6031     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6032     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6033     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6034     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6035     SDValue N =
6036         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6037     if (Intrinsic == Intrinsic::eh_exceptioncode)
6038       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6039     setValue(&I, N);
6040     return nullptr;
6041   }
6042   case Intrinsic::xray_customevent: {
6043     // Here we want to make sure that the intrinsic behaves as if it has a
6044     // specific calling convention, and only for x86_64.
6045     // FIXME: Support other platforms later.
6046     const auto &Triple = DAG.getTarget().getTargetTriple();
6047     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6048       return nullptr;
6049 
6050     SDLoc DL = getCurSDLoc();
6051     SmallVector<SDValue, 8> Ops;
6052 
6053     // We want to say that we always want the arguments in registers.
6054     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6055     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6056     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6057     SDValue Chain = getRoot();
6058     Ops.push_back(LogEntryVal);
6059     Ops.push_back(StrSizeVal);
6060     Ops.push_back(Chain);
6061 
6062     // We need to enforce the calling convention for the callsite, so that
6063     // argument ordering is enforced correctly, and that register allocation can
6064     // see that some registers may be assumed clobbered and have to preserve
6065     // them across calls to the intrinsic.
6066     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6067                                            DL, NodeTys, Ops);
6068     SDValue patchableNode = SDValue(MN, 0);
6069     DAG.setRoot(patchableNode);
6070     setValue(&I, patchableNode);
6071     return nullptr;
6072   }
6073   case Intrinsic::experimental_deoptimize:
6074     LowerDeoptimizeCall(&I);
6075     return nullptr;
6076 
6077   case Intrinsic::experimental_vector_reduce_fadd:
6078   case Intrinsic::experimental_vector_reduce_fmul:
6079   case Intrinsic::experimental_vector_reduce_add:
6080   case Intrinsic::experimental_vector_reduce_mul:
6081   case Intrinsic::experimental_vector_reduce_and:
6082   case Intrinsic::experimental_vector_reduce_or:
6083   case Intrinsic::experimental_vector_reduce_xor:
6084   case Intrinsic::experimental_vector_reduce_smax:
6085   case Intrinsic::experimental_vector_reduce_smin:
6086   case Intrinsic::experimental_vector_reduce_umax:
6087   case Intrinsic::experimental_vector_reduce_umin:
6088   case Intrinsic::experimental_vector_reduce_fmax:
6089   case Intrinsic::experimental_vector_reduce_fmin:
6090     visitVectorReduce(I, Intrinsic);
6091     return nullptr;
6092 
6093   case Intrinsic::icall_branch_funnel: {
6094     SmallVector<SDValue, 16> Ops;
6095     Ops.push_back(DAG.getRoot());
6096     Ops.push_back(getValue(I.getArgOperand(0)));
6097 
6098     int64_t Offset;
6099     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6100         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6101     if (!Base)
6102       report_fatal_error(
6103           "llvm.icall.branch.funnel operand must be a GlobalValue");
6104     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6105 
6106     struct BranchFunnelTarget {
6107       int64_t Offset;
6108       SDValue Target;
6109     };
6110     SmallVector<BranchFunnelTarget, 8> Targets;
6111 
6112     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6113       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6114           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6115       if (ElemBase != Base)
6116         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6117                            "to the same GlobalValue");
6118 
6119       SDValue Val = getValue(I.getArgOperand(Op + 1));
6120       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6121       if (!GA)
6122         report_fatal_error(
6123             "llvm.icall.branch.funnel operand must be a GlobalValue");
6124       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6125                                      GA->getGlobal(), getCurSDLoc(),
6126                                      Val.getValueType(), GA->getOffset())});
6127     }
6128     std::sort(Targets.begin(), Targets.end(),
6129               [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6130                 return T1.Offset < T2.Offset;
6131               });
6132 
6133     for (auto &T : Targets) {
6134       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6135       Ops.push_back(T.Target);
6136     }
6137 
6138     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6139                                  getCurSDLoc(), MVT::Other, Ops),
6140               0);
6141     DAG.setRoot(N);
6142     setValue(&I, N);
6143     HasTailCall = true;
6144     return nullptr;
6145   }
6146   }
6147 }
6148 
6149 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6150     const ConstrainedFPIntrinsic &FPI) {
6151   SDLoc sdl = getCurSDLoc();
6152   unsigned Opcode;
6153   switch (FPI.getIntrinsicID()) {
6154   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6155   case Intrinsic::experimental_constrained_fadd:
6156     Opcode = ISD::STRICT_FADD;
6157     break;
6158   case Intrinsic::experimental_constrained_fsub:
6159     Opcode = ISD::STRICT_FSUB;
6160     break;
6161   case Intrinsic::experimental_constrained_fmul:
6162     Opcode = ISD::STRICT_FMUL;
6163     break;
6164   case Intrinsic::experimental_constrained_fdiv:
6165     Opcode = ISD::STRICT_FDIV;
6166     break;
6167   case Intrinsic::experimental_constrained_frem:
6168     Opcode = ISD::STRICT_FREM;
6169     break;
6170   case Intrinsic::experimental_constrained_fma:
6171     Opcode = ISD::STRICT_FMA;
6172     break;
6173   case Intrinsic::experimental_constrained_sqrt:
6174     Opcode = ISD::STRICT_FSQRT;
6175     break;
6176   case Intrinsic::experimental_constrained_pow:
6177     Opcode = ISD::STRICT_FPOW;
6178     break;
6179   case Intrinsic::experimental_constrained_powi:
6180     Opcode = ISD::STRICT_FPOWI;
6181     break;
6182   case Intrinsic::experimental_constrained_sin:
6183     Opcode = ISD::STRICT_FSIN;
6184     break;
6185   case Intrinsic::experimental_constrained_cos:
6186     Opcode = ISD::STRICT_FCOS;
6187     break;
6188   case Intrinsic::experimental_constrained_exp:
6189     Opcode = ISD::STRICT_FEXP;
6190     break;
6191   case Intrinsic::experimental_constrained_exp2:
6192     Opcode = ISD::STRICT_FEXP2;
6193     break;
6194   case Intrinsic::experimental_constrained_log:
6195     Opcode = ISD::STRICT_FLOG;
6196     break;
6197   case Intrinsic::experimental_constrained_log10:
6198     Opcode = ISD::STRICT_FLOG10;
6199     break;
6200   case Intrinsic::experimental_constrained_log2:
6201     Opcode = ISD::STRICT_FLOG2;
6202     break;
6203   case Intrinsic::experimental_constrained_rint:
6204     Opcode = ISD::STRICT_FRINT;
6205     break;
6206   case Intrinsic::experimental_constrained_nearbyint:
6207     Opcode = ISD::STRICT_FNEARBYINT;
6208     break;
6209   }
6210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6211   SDValue Chain = getRoot();
6212   SmallVector<EVT, 4> ValueVTs;
6213   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6214   ValueVTs.push_back(MVT::Other); // Out chain
6215 
6216   SDVTList VTs = DAG.getVTList(ValueVTs);
6217   SDValue Result;
6218   if (FPI.isUnaryOp())
6219     Result = DAG.getNode(Opcode, sdl, VTs,
6220                          { Chain, getValue(FPI.getArgOperand(0)) });
6221   else if (FPI.isTernaryOp())
6222     Result = DAG.getNode(Opcode, sdl, VTs,
6223                          { Chain, getValue(FPI.getArgOperand(0)),
6224                                   getValue(FPI.getArgOperand(1)),
6225                                   getValue(FPI.getArgOperand(2)) });
6226   else
6227     Result = DAG.getNode(Opcode, sdl, VTs,
6228                          { Chain, getValue(FPI.getArgOperand(0)),
6229                            getValue(FPI.getArgOperand(1))  });
6230 
6231   assert(Result.getNode()->getNumValues() == 2);
6232   SDValue OutChain = Result.getValue(1);
6233   DAG.setRoot(OutChain);
6234   SDValue FPResult = Result.getValue(0);
6235   setValue(&FPI, FPResult);
6236 }
6237 
6238 std::pair<SDValue, SDValue>
6239 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6240                                     const BasicBlock *EHPadBB) {
6241   MachineFunction &MF = DAG.getMachineFunction();
6242   MachineModuleInfo &MMI = MF.getMMI();
6243   MCSymbol *BeginLabel = nullptr;
6244 
6245   if (EHPadBB) {
6246     // Insert a label before the invoke call to mark the try range.  This can be
6247     // used to detect deletion of the invoke via the MachineModuleInfo.
6248     BeginLabel = MMI.getContext().createTempSymbol();
6249 
6250     // For SjLj, keep track of which landing pads go with which invokes
6251     // so as to maintain the ordering of pads in the LSDA.
6252     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6253     if (CallSiteIndex) {
6254       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6255       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6256 
6257       // Now that the call site is handled, stop tracking it.
6258       MMI.setCurrentCallSite(0);
6259     }
6260 
6261     // Both PendingLoads and PendingExports must be flushed here;
6262     // this call might not return.
6263     (void)getRoot();
6264     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6265 
6266     CLI.setChain(getRoot());
6267   }
6268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6269   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6270 
6271   assert((CLI.IsTailCall || Result.second.getNode()) &&
6272          "Non-null chain expected with non-tail call!");
6273   assert((Result.second.getNode() || !Result.first.getNode()) &&
6274          "Null value expected with tail call!");
6275 
6276   if (!Result.second.getNode()) {
6277     // As a special case, a null chain means that a tail call has been emitted
6278     // and the DAG root is already updated.
6279     HasTailCall = true;
6280 
6281     // Since there's no actual continuation from this block, nothing can be
6282     // relying on us setting vregs for them.
6283     PendingExports.clear();
6284   } else {
6285     DAG.setRoot(Result.second);
6286   }
6287 
6288   if (EHPadBB) {
6289     // Insert a label at the end of the invoke call to mark the try range.  This
6290     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6291     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6292     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6293 
6294     // Inform MachineModuleInfo of range.
6295     if (MF.hasEHFunclets()) {
6296       assert(CLI.CS);
6297       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6298       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6299                                 BeginLabel, EndLabel);
6300     } else {
6301       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6302     }
6303   }
6304 
6305   return Result;
6306 }
6307 
6308 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6309                                       bool isTailCall,
6310                                       const BasicBlock *EHPadBB) {
6311   auto &DL = DAG.getDataLayout();
6312   FunctionType *FTy = CS.getFunctionType();
6313   Type *RetTy = CS.getType();
6314 
6315   TargetLowering::ArgListTy Args;
6316   Args.reserve(CS.arg_size());
6317 
6318   const Value *SwiftErrorVal = nullptr;
6319   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6320 
6321   // We can't tail call inside a function with a swifterror argument. Lowering
6322   // does not support this yet. It would have to move into the swifterror
6323   // register before the call.
6324   auto *Caller = CS.getInstruction()->getParent()->getParent();
6325   if (TLI.supportSwiftError() &&
6326       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6327     isTailCall = false;
6328 
6329   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6330        i != e; ++i) {
6331     TargetLowering::ArgListEntry Entry;
6332     const Value *V = *i;
6333 
6334     // Skip empty types
6335     if (V->getType()->isEmptyTy())
6336       continue;
6337 
6338     SDValue ArgNode = getValue(V);
6339     Entry.Node = ArgNode; Entry.Ty = V->getType();
6340 
6341     Entry.setAttributes(&CS, i - CS.arg_begin());
6342 
6343     // Use swifterror virtual register as input to the call.
6344     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6345       SwiftErrorVal = V;
6346       // We find the virtual register for the actual swifterror argument.
6347       // Instead of using the Value, we use the virtual register instead.
6348       Entry.Node = DAG.getRegister(FuncInfo
6349                                        .getOrCreateSwiftErrorVRegUseAt(
6350                                            CS.getInstruction(), FuncInfo.MBB, V)
6351                                        .first,
6352                                    EVT(TLI.getPointerTy(DL)));
6353     }
6354 
6355     Args.push_back(Entry);
6356 
6357     // If we have an explicit sret argument that is an Instruction, (i.e., it
6358     // might point to function-local memory), we can't meaningfully tail-call.
6359     if (Entry.IsSRet && isa<Instruction>(V))
6360       isTailCall = false;
6361   }
6362 
6363   // Check if target-independent constraints permit a tail call here.
6364   // Target-dependent constraints are checked within TLI->LowerCallTo.
6365   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6366     isTailCall = false;
6367 
6368   // Disable tail calls if there is an swifterror argument. Targets have not
6369   // been updated to support tail calls.
6370   if (TLI.supportSwiftError() && SwiftErrorVal)
6371     isTailCall = false;
6372 
6373   TargetLowering::CallLoweringInfo CLI(DAG);
6374   CLI.setDebugLoc(getCurSDLoc())
6375       .setChain(getRoot())
6376       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6377       .setTailCall(isTailCall)
6378       .setConvergent(CS.isConvergent());
6379   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6380 
6381   if (Result.first.getNode()) {
6382     const Instruction *Inst = CS.getInstruction();
6383     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6384     setValue(Inst, Result.first);
6385   }
6386 
6387   // The last element of CLI.InVals has the SDValue for swifterror return.
6388   // Here we copy it to a virtual register and update SwiftErrorMap for
6389   // book-keeping.
6390   if (SwiftErrorVal && TLI.supportSwiftError()) {
6391     // Get the last element of InVals.
6392     SDValue Src = CLI.InVals.back();
6393     unsigned VReg; bool CreatedVReg;
6394     std::tie(VReg, CreatedVReg) =
6395         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6396     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6397     // We update the virtual register for the actual swifterror argument.
6398     if (CreatedVReg)
6399       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6400     DAG.setRoot(CopyNode);
6401   }
6402 }
6403 
6404 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6405                              SelectionDAGBuilder &Builder) {
6406   // Check to see if this load can be trivially constant folded, e.g. if the
6407   // input is from a string literal.
6408   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6409     // Cast pointer to the type we really want to load.
6410     Type *LoadTy =
6411         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6412     if (LoadVT.isVector())
6413       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6414 
6415     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6416                                          PointerType::getUnqual(LoadTy));
6417 
6418     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6419             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6420       return Builder.getValue(LoadCst);
6421   }
6422 
6423   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6424   // still constant memory, the input chain can be the entry node.
6425   SDValue Root;
6426   bool ConstantMemory = false;
6427 
6428   // Do not serialize (non-volatile) loads of constant memory with anything.
6429   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6430     Root = Builder.DAG.getEntryNode();
6431     ConstantMemory = true;
6432   } else {
6433     // Do not serialize non-volatile loads against each other.
6434     Root = Builder.DAG.getRoot();
6435   }
6436 
6437   SDValue Ptr = Builder.getValue(PtrVal);
6438   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6439                                         Ptr, MachinePointerInfo(PtrVal),
6440                                         /* Alignment = */ 1);
6441 
6442   if (!ConstantMemory)
6443     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6444   return LoadVal;
6445 }
6446 
6447 /// Record the value for an instruction that produces an integer result,
6448 /// converting the type where necessary.
6449 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6450                                                   SDValue Value,
6451                                                   bool IsSigned) {
6452   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6453                                                     I.getType(), true);
6454   if (IsSigned)
6455     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6456   else
6457     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6458   setValue(&I, Value);
6459 }
6460 
6461 /// See if we can lower a memcmp call into an optimized form. If so, return
6462 /// true and lower it. Otherwise return false, and it will be lowered like a
6463 /// normal call.
6464 /// The caller already checked that \p I calls the appropriate LibFunc with a
6465 /// correct prototype.
6466 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6467   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6468   const Value *Size = I.getArgOperand(2);
6469   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6470   if (CSize && CSize->getZExtValue() == 0) {
6471     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6472                                                           I.getType(), true);
6473     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6474     return true;
6475   }
6476 
6477   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6478   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6479       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6480       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6481   if (Res.first.getNode()) {
6482     processIntegerCallValue(I, Res.first, true);
6483     PendingLoads.push_back(Res.second);
6484     return true;
6485   }
6486 
6487   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6488   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6489   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6490     return false;
6491 
6492   // If the target has a fast compare for the given size, it will return a
6493   // preferred load type for that size. Require that the load VT is legal and
6494   // that the target supports unaligned loads of that type. Otherwise, return
6495   // INVALID.
6496   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6497     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6498     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6499     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6500       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6501       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6502       // TODO: Check alignment of src and dest ptrs.
6503       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6504       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6505       if (!TLI.isTypeLegal(LVT) ||
6506           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6507           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6508         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6509     }
6510 
6511     return LVT;
6512   };
6513 
6514   // This turns into unaligned loads. We only do this if the target natively
6515   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6516   // we'll only produce a small number of byte loads.
6517   MVT LoadVT;
6518   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6519   switch (NumBitsToCompare) {
6520   default:
6521     return false;
6522   case 16:
6523     LoadVT = MVT::i16;
6524     break;
6525   case 32:
6526     LoadVT = MVT::i32;
6527     break;
6528   case 64:
6529   case 128:
6530   case 256:
6531     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6532     break;
6533   }
6534 
6535   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6536     return false;
6537 
6538   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6539   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6540 
6541   // Bitcast to a wide integer type if the loads are vectors.
6542   if (LoadVT.isVector()) {
6543     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6544     LoadL = DAG.getBitcast(CmpVT, LoadL);
6545     LoadR = DAG.getBitcast(CmpVT, LoadR);
6546   }
6547 
6548   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6549   processIntegerCallValue(I, Cmp, false);
6550   return true;
6551 }
6552 
6553 /// See if we can lower a memchr call into an optimized form. If so, return
6554 /// true and lower it. Otherwise return false, and it will be lowered like a
6555 /// normal call.
6556 /// The caller already checked that \p I calls the appropriate LibFunc with a
6557 /// correct prototype.
6558 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6559   const Value *Src = I.getArgOperand(0);
6560   const Value *Char = I.getArgOperand(1);
6561   const Value *Length = I.getArgOperand(2);
6562 
6563   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6564   std::pair<SDValue, SDValue> Res =
6565     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6566                                 getValue(Src), getValue(Char), getValue(Length),
6567                                 MachinePointerInfo(Src));
6568   if (Res.first.getNode()) {
6569     setValue(&I, Res.first);
6570     PendingLoads.push_back(Res.second);
6571     return true;
6572   }
6573 
6574   return false;
6575 }
6576 
6577 /// See if we can lower a mempcpy call into an optimized form. If so, return
6578 /// true and lower it. Otherwise return false, and it will be lowered like a
6579 /// normal call.
6580 /// The caller already checked that \p I calls the appropriate LibFunc with a
6581 /// correct prototype.
6582 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6583   SDValue Dst = getValue(I.getArgOperand(0));
6584   SDValue Src = getValue(I.getArgOperand(1));
6585   SDValue Size = getValue(I.getArgOperand(2));
6586 
6587   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6588   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6589   unsigned Align = std::min(DstAlign, SrcAlign);
6590   if (Align == 0) // Alignment of one or both could not be inferred.
6591     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6592 
6593   bool isVol = false;
6594   SDLoc sdl = getCurSDLoc();
6595 
6596   // In the mempcpy context we need to pass in a false value for isTailCall
6597   // because the return pointer needs to be adjusted by the size of
6598   // the copied memory.
6599   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6600                              false, /*isTailCall=*/false,
6601                              MachinePointerInfo(I.getArgOperand(0)),
6602                              MachinePointerInfo(I.getArgOperand(1)));
6603   assert(MC.getNode() != nullptr &&
6604          "** memcpy should not be lowered as TailCall in mempcpy context **");
6605   DAG.setRoot(MC);
6606 
6607   // Check if Size needs to be truncated or extended.
6608   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6609 
6610   // Adjust return pointer to point just past the last dst byte.
6611   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6612                                     Dst, Size);
6613   setValue(&I, DstPlusSize);
6614   return true;
6615 }
6616 
6617 /// See if we can lower a strcpy call into an optimized form.  If so, return
6618 /// true and lower it, otherwise return false and it will be lowered like a
6619 /// normal call.
6620 /// The caller already checked that \p I calls the appropriate LibFunc with a
6621 /// correct prototype.
6622 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6623   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6624 
6625   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6626   std::pair<SDValue, SDValue> Res =
6627     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6628                                 getValue(Arg0), getValue(Arg1),
6629                                 MachinePointerInfo(Arg0),
6630                                 MachinePointerInfo(Arg1), isStpcpy);
6631   if (Res.first.getNode()) {
6632     setValue(&I, Res.first);
6633     DAG.setRoot(Res.second);
6634     return true;
6635   }
6636 
6637   return false;
6638 }
6639 
6640 /// See if we can lower a strcmp call into an optimized form.  If so, return
6641 /// true and lower it, otherwise return false and it will be lowered like a
6642 /// normal call.
6643 /// The caller already checked that \p I calls the appropriate LibFunc with a
6644 /// correct prototype.
6645 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6646   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6647 
6648   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6649   std::pair<SDValue, SDValue> Res =
6650     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6651                                 getValue(Arg0), getValue(Arg1),
6652                                 MachinePointerInfo(Arg0),
6653                                 MachinePointerInfo(Arg1));
6654   if (Res.first.getNode()) {
6655     processIntegerCallValue(I, Res.first, true);
6656     PendingLoads.push_back(Res.second);
6657     return true;
6658   }
6659 
6660   return false;
6661 }
6662 
6663 /// See if we can lower a strlen call into an optimized form.  If so, return
6664 /// true and lower it, otherwise return false and it will be lowered like a
6665 /// normal call.
6666 /// The caller already checked that \p I calls the appropriate LibFunc with a
6667 /// correct prototype.
6668 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6669   const Value *Arg0 = I.getArgOperand(0);
6670 
6671   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6672   std::pair<SDValue, SDValue> Res =
6673     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6674                                 getValue(Arg0), MachinePointerInfo(Arg0));
6675   if (Res.first.getNode()) {
6676     processIntegerCallValue(I, Res.first, false);
6677     PendingLoads.push_back(Res.second);
6678     return true;
6679   }
6680 
6681   return false;
6682 }
6683 
6684 /// See if we can lower a strnlen call into an optimized form.  If so, return
6685 /// true and lower it, otherwise return false and it will be lowered like a
6686 /// normal call.
6687 /// The caller already checked that \p I calls the appropriate LibFunc with a
6688 /// correct prototype.
6689 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6690   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6691 
6692   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6693   std::pair<SDValue, SDValue> Res =
6694     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6695                                  getValue(Arg0), getValue(Arg1),
6696                                  MachinePointerInfo(Arg0));
6697   if (Res.first.getNode()) {
6698     processIntegerCallValue(I, Res.first, false);
6699     PendingLoads.push_back(Res.second);
6700     return true;
6701   }
6702 
6703   return false;
6704 }
6705 
6706 /// See if we can lower a unary floating-point operation into an SDNode with
6707 /// the specified Opcode.  If so, return true and lower it, otherwise return
6708 /// false and it will be lowered like a normal call.
6709 /// The caller already checked that \p I calls the appropriate LibFunc with a
6710 /// correct prototype.
6711 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6712                                               unsigned Opcode) {
6713   // We already checked this call's prototype; verify it doesn't modify errno.
6714   if (!I.onlyReadsMemory())
6715     return false;
6716 
6717   SDValue Tmp = getValue(I.getArgOperand(0));
6718   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6719   return true;
6720 }
6721 
6722 /// See if we can lower a binary floating-point operation into an SDNode with
6723 /// the specified Opcode. If so, return true and lower it. Otherwise return
6724 /// false, and it will be lowered like a normal call.
6725 /// The caller already checked that \p I calls the appropriate LibFunc with a
6726 /// correct prototype.
6727 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6728                                                unsigned Opcode) {
6729   // We already checked this call's prototype; verify it doesn't modify errno.
6730   if (!I.onlyReadsMemory())
6731     return false;
6732 
6733   SDValue Tmp0 = getValue(I.getArgOperand(0));
6734   SDValue Tmp1 = getValue(I.getArgOperand(1));
6735   EVT VT = Tmp0.getValueType();
6736   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6737   return true;
6738 }
6739 
6740 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6741   // Handle inline assembly differently.
6742   if (isa<InlineAsm>(I.getCalledValue())) {
6743     visitInlineAsm(&I);
6744     return;
6745   }
6746 
6747   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6748   computeUsesVAFloatArgument(I, MMI);
6749 
6750   const char *RenameFn = nullptr;
6751   if (Function *F = I.getCalledFunction()) {
6752     if (F->isDeclaration()) {
6753       if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6754         if (unsigned IID = II->getIntrinsicID(F)) {
6755           RenameFn = visitIntrinsicCall(I, IID);
6756           if (!RenameFn)
6757             return;
6758         }
6759       }
6760       if (Intrinsic::ID IID = F->getIntrinsicID()) {
6761         RenameFn = visitIntrinsicCall(I, IID);
6762         if (!RenameFn)
6763           return;
6764       }
6765     }
6766 
6767     // Check for well-known libc/libm calls.  If the function is internal, it
6768     // can't be a library call.  Don't do the check if marked as nobuiltin for
6769     // some reason or the call site requires strict floating point semantics.
6770     LibFunc Func;
6771     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6772         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6773         LibInfo->hasOptimizedCodeGen(Func)) {
6774       switch (Func) {
6775       default: break;
6776       case LibFunc_copysign:
6777       case LibFunc_copysignf:
6778       case LibFunc_copysignl:
6779         // We already checked this call's prototype; verify it doesn't modify
6780         // errno.
6781         if (I.onlyReadsMemory()) {
6782           SDValue LHS = getValue(I.getArgOperand(0));
6783           SDValue RHS = getValue(I.getArgOperand(1));
6784           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6785                                    LHS.getValueType(), LHS, RHS));
6786           return;
6787         }
6788         break;
6789       case LibFunc_fabs:
6790       case LibFunc_fabsf:
6791       case LibFunc_fabsl:
6792         if (visitUnaryFloatCall(I, ISD::FABS))
6793           return;
6794         break;
6795       case LibFunc_fmin:
6796       case LibFunc_fminf:
6797       case LibFunc_fminl:
6798         if (visitBinaryFloatCall(I, ISD::FMINNUM))
6799           return;
6800         break;
6801       case LibFunc_fmax:
6802       case LibFunc_fmaxf:
6803       case LibFunc_fmaxl:
6804         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6805           return;
6806         break;
6807       case LibFunc_sin:
6808       case LibFunc_sinf:
6809       case LibFunc_sinl:
6810         if (visitUnaryFloatCall(I, ISD::FSIN))
6811           return;
6812         break;
6813       case LibFunc_cos:
6814       case LibFunc_cosf:
6815       case LibFunc_cosl:
6816         if (visitUnaryFloatCall(I, ISD::FCOS))
6817           return;
6818         break;
6819       case LibFunc_sqrt:
6820       case LibFunc_sqrtf:
6821       case LibFunc_sqrtl:
6822       case LibFunc_sqrt_finite:
6823       case LibFunc_sqrtf_finite:
6824       case LibFunc_sqrtl_finite:
6825         if (visitUnaryFloatCall(I, ISD::FSQRT))
6826           return;
6827         break;
6828       case LibFunc_floor:
6829       case LibFunc_floorf:
6830       case LibFunc_floorl:
6831         if (visitUnaryFloatCall(I, ISD::FFLOOR))
6832           return;
6833         break;
6834       case LibFunc_nearbyint:
6835       case LibFunc_nearbyintf:
6836       case LibFunc_nearbyintl:
6837         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6838           return;
6839         break;
6840       case LibFunc_ceil:
6841       case LibFunc_ceilf:
6842       case LibFunc_ceill:
6843         if (visitUnaryFloatCall(I, ISD::FCEIL))
6844           return;
6845         break;
6846       case LibFunc_rint:
6847       case LibFunc_rintf:
6848       case LibFunc_rintl:
6849         if (visitUnaryFloatCall(I, ISD::FRINT))
6850           return;
6851         break;
6852       case LibFunc_round:
6853       case LibFunc_roundf:
6854       case LibFunc_roundl:
6855         if (visitUnaryFloatCall(I, ISD::FROUND))
6856           return;
6857         break;
6858       case LibFunc_trunc:
6859       case LibFunc_truncf:
6860       case LibFunc_truncl:
6861         if (visitUnaryFloatCall(I, ISD::FTRUNC))
6862           return;
6863         break;
6864       case LibFunc_log2:
6865       case LibFunc_log2f:
6866       case LibFunc_log2l:
6867         if (visitUnaryFloatCall(I, ISD::FLOG2))
6868           return;
6869         break;
6870       case LibFunc_exp2:
6871       case LibFunc_exp2f:
6872       case LibFunc_exp2l:
6873         if (visitUnaryFloatCall(I, ISD::FEXP2))
6874           return;
6875         break;
6876       case LibFunc_memcmp:
6877         if (visitMemCmpCall(I))
6878           return;
6879         break;
6880       case LibFunc_mempcpy:
6881         if (visitMemPCpyCall(I))
6882           return;
6883         break;
6884       case LibFunc_memchr:
6885         if (visitMemChrCall(I))
6886           return;
6887         break;
6888       case LibFunc_strcpy:
6889         if (visitStrCpyCall(I, false))
6890           return;
6891         break;
6892       case LibFunc_stpcpy:
6893         if (visitStrCpyCall(I, true))
6894           return;
6895         break;
6896       case LibFunc_strcmp:
6897         if (visitStrCmpCall(I))
6898           return;
6899         break;
6900       case LibFunc_strlen:
6901         if (visitStrLenCall(I))
6902           return;
6903         break;
6904       case LibFunc_strnlen:
6905         if (visitStrNLenCall(I))
6906           return;
6907         break;
6908       }
6909     }
6910   }
6911 
6912   SDValue Callee;
6913   if (!RenameFn)
6914     Callee = getValue(I.getCalledValue());
6915   else
6916     Callee = DAG.getExternalSymbol(
6917         RenameFn,
6918         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6919 
6920   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
6921   // have to do anything here to lower funclet bundles.
6922   assert(!I.hasOperandBundlesOtherThan(
6923              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
6924          "Cannot lower calls with arbitrary operand bundles!");
6925 
6926   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
6927     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
6928   else
6929     // Check if we can potentially perform a tail call. More detailed checking
6930     // is be done within LowerCallTo, after more information about the call is
6931     // known.
6932     LowerCallTo(&I, Callee, I.isTailCall());
6933 }
6934 
6935 namespace {
6936 
6937 /// AsmOperandInfo - This contains information for each constraint that we are
6938 /// lowering.
6939 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6940 public:
6941   /// CallOperand - If this is the result output operand or a clobber
6942   /// this is null, otherwise it is the incoming operand to the CallInst.
6943   /// This gets modified as the asm is processed.
6944   SDValue CallOperand;
6945 
6946   /// AssignedRegs - If this is a register or register class operand, this
6947   /// contains the set of register corresponding to the operand.
6948   RegsForValue AssignedRegs;
6949 
6950   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6951     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
6952   }
6953 
6954   /// Whether or not this operand accesses memory
6955   bool hasMemory(const TargetLowering &TLI) const {
6956     // Indirect operand accesses access memory.
6957     if (isIndirect)
6958       return true;
6959 
6960     for (const auto &Code : Codes)
6961       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
6962         return true;
6963 
6964     return false;
6965   }
6966 
6967   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6968   /// corresponds to.  If there is no Value* for this operand, it returns
6969   /// MVT::Other.
6970   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
6971                            const DataLayout &DL) const {
6972     if (!CallOperandVal) return MVT::Other;
6973 
6974     if (isa<BasicBlock>(CallOperandVal))
6975       return TLI.getPointerTy(DL);
6976 
6977     llvm::Type *OpTy = CallOperandVal->getType();
6978 
6979     // FIXME: code duplicated from TargetLowering::ParseConstraints().
6980     // If this is an indirect operand, the operand is a pointer to the
6981     // accessed type.
6982     if (isIndirect) {
6983       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6984       if (!PtrTy)
6985         report_fatal_error("Indirect operand for inline asm not a pointer!");
6986       OpTy = PtrTy->getElementType();
6987     }
6988 
6989     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6990     if (StructType *STy = dyn_cast<StructType>(OpTy))
6991       if (STy->getNumElements() == 1)
6992         OpTy = STy->getElementType(0);
6993 
6994     // If OpTy is not a single value, it may be a struct/union that we
6995     // can tile with integers.
6996     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6997       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6998       switch (BitSize) {
6999       default: break;
7000       case 1:
7001       case 8:
7002       case 16:
7003       case 32:
7004       case 64:
7005       case 128:
7006         OpTy = IntegerType::get(Context, BitSize);
7007         break;
7008       }
7009     }
7010 
7011     return TLI.getValueType(DL, OpTy, true);
7012   }
7013 };
7014 
7015 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7016 
7017 } // end anonymous namespace
7018 
7019 /// Make sure that the output operand \p OpInfo and its corresponding input
7020 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7021 /// out).
7022 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7023                                SDISelAsmOperandInfo &MatchingOpInfo,
7024                                SelectionDAG &DAG) {
7025   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7026     return;
7027 
7028   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7029   const auto &TLI = DAG.getTargetLoweringInfo();
7030 
7031   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7032       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7033                                        OpInfo.ConstraintVT);
7034   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7035       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7036                                        MatchingOpInfo.ConstraintVT);
7037   if ((OpInfo.ConstraintVT.isInteger() !=
7038        MatchingOpInfo.ConstraintVT.isInteger()) ||
7039       (MatchRC.second != InputRC.second)) {
7040     // FIXME: error out in a more elegant fashion
7041     report_fatal_error("Unsupported asm: input constraint"
7042                        " with a matching output constraint of"
7043                        " incompatible type!");
7044   }
7045   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7046 }
7047 
7048 /// Get a direct memory input to behave well as an indirect operand.
7049 /// This may introduce stores, hence the need for a \p Chain.
7050 /// \return The (possibly updated) chain.
7051 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7052                                         SDISelAsmOperandInfo &OpInfo,
7053                                         SelectionDAG &DAG) {
7054   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7055 
7056   // If we don't have an indirect input, put it in the constpool if we can,
7057   // otherwise spill it to a stack slot.
7058   // TODO: This isn't quite right. We need to handle these according to
7059   // the addressing mode that the constraint wants. Also, this may take
7060   // an additional register for the computation and we don't want that
7061   // either.
7062 
7063   // If the operand is a float, integer, or vector constant, spill to a
7064   // constant pool entry to get its address.
7065   const Value *OpVal = OpInfo.CallOperandVal;
7066   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7067       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7068     OpInfo.CallOperand = DAG.getConstantPool(
7069         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7070     return Chain;
7071   }
7072 
7073   // Otherwise, create a stack slot and emit a store to it before the asm.
7074   Type *Ty = OpVal->getType();
7075   auto &DL = DAG.getDataLayout();
7076   uint64_t TySize = DL.getTypeAllocSize(Ty);
7077   unsigned Align = DL.getPrefTypeAlignment(Ty);
7078   MachineFunction &MF = DAG.getMachineFunction();
7079   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7080   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7081   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7082                        MachinePointerInfo::getFixedStack(MF, SSFI));
7083   OpInfo.CallOperand = StackSlot;
7084 
7085   return Chain;
7086 }
7087 
7088 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7089 /// specified operand.  We prefer to assign virtual registers, to allow the
7090 /// register allocator to handle the assignment process.  However, if the asm
7091 /// uses features that we can't model on machineinstrs, we have SDISel do the
7092 /// allocation.  This produces generally horrible, but correct, code.
7093 ///
7094 ///   OpInfo describes the operand.
7095 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
7096                                  const SDLoc &DL,
7097                                  SDISelAsmOperandInfo &OpInfo) {
7098   LLVMContext &Context = *DAG.getContext();
7099 
7100   MachineFunction &MF = DAG.getMachineFunction();
7101   SmallVector<unsigned, 4> Regs;
7102   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7103 
7104   // If this is a constraint for a single physreg, or a constraint for a
7105   // register class, find it.
7106   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7107       TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode,
7108                                        OpInfo.ConstraintVT);
7109 
7110   unsigned NumRegs = 1;
7111   if (OpInfo.ConstraintVT != MVT::Other) {
7112     // If this is a FP input in an integer register (or visa versa) insert a bit
7113     // cast of the input value.  More generally, handle any case where the input
7114     // value disagrees with the register class we plan to stick this in.
7115     if (OpInfo.Type == InlineAsm::isInput && PhysReg.second &&
7116         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7117       // Try to convert to the first EVT that the reg class contains.  If the
7118       // types are identical size, use a bitcast to convert (e.g. two differing
7119       // vector types).
7120       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7121       if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
7122         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7123                                          RegVT, OpInfo.CallOperand);
7124         OpInfo.ConstraintVT = RegVT;
7125       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7126         // If the input is a FP value and we want it in FP registers, do a
7127         // bitcast to the corresponding integer type.  This turns an f64 value
7128         // into i64, which can be passed with two i32 values on a 32-bit
7129         // machine.
7130         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7131         OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
7132                                          RegVT, OpInfo.CallOperand);
7133         OpInfo.ConstraintVT = RegVT;
7134       }
7135     }
7136 
7137     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7138   }
7139 
7140   MVT RegVT;
7141   EVT ValueVT = OpInfo.ConstraintVT;
7142 
7143   // If this is a constraint for a specific physical register, like {r17},
7144   // assign it now.
7145   if (unsigned AssignedReg = PhysReg.first) {
7146     const TargetRegisterClass *RC = PhysReg.second;
7147     if (OpInfo.ConstraintVT == MVT::Other)
7148       ValueVT = *TRI.legalclasstypes_begin(*RC);
7149 
7150     // Get the actual register value type.  This is important, because the user
7151     // may have asked for (e.g.) the AX register in i32 type.  We need to
7152     // remember that AX is actually i16 to get the right extension.
7153     RegVT = *TRI.legalclasstypes_begin(*RC);
7154 
7155     // This is a explicit reference to a physical register.
7156     Regs.push_back(AssignedReg);
7157 
7158     // If this is an expanded reference, add the rest of the regs to Regs.
7159     if (NumRegs != 1) {
7160       TargetRegisterClass::iterator I = RC->begin();
7161       for (; *I != AssignedReg; ++I)
7162         assert(I != RC->end() && "Didn't find reg!");
7163 
7164       // Already added the first reg.
7165       --NumRegs; ++I;
7166       for (; NumRegs; --NumRegs, ++I) {
7167         assert(I != RC->end() && "Ran out of registers to allocate!");
7168         Regs.push_back(*I);
7169       }
7170     }
7171 
7172     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7173     return;
7174   }
7175 
7176   // Otherwise, if this was a reference to an LLVM register class, create vregs
7177   // for this reference.
7178   if (const TargetRegisterClass *RC = PhysReg.second) {
7179     RegVT = *TRI.legalclasstypes_begin(*RC);
7180     if (OpInfo.ConstraintVT == MVT::Other)
7181       ValueVT = RegVT;
7182 
7183     // Create the appropriate number of virtual registers.
7184     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7185     for (; NumRegs; --NumRegs)
7186       Regs.push_back(RegInfo.createVirtualRegister(RC));
7187 
7188     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7189     return;
7190   }
7191 
7192   // Otherwise, we couldn't allocate enough registers for this.
7193 }
7194 
7195 static unsigned
7196 findMatchingInlineAsmOperand(unsigned OperandNo,
7197                              const std::vector<SDValue> &AsmNodeOperands) {
7198   // Scan until we find the definition we already emitted of this operand.
7199   unsigned CurOp = InlineAsm::Op_FirstOperand;
7200   for (; OperandNo; --OperandNo) {
7201     // Advance to the next operand.
7202     unsigned OpFlag =
7203         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7204     assert((InlineAsm::isRegDefKind(OpFlag) ||
7205             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7206             InlineAsm::isMemKind(OpFlag)) &&
7207            "Skipped past definitions?");
7208     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7209   }
7210   return CurOp;
7211 }
7212 
7213 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7214 /// \return true if it has succeeded, false otherwise
7215 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7216                               MVT RegVT, SelectionDAG &DAG) {
7217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7218   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7219   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7220     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7221       Regs.push_back(RegInfo.createVirtualRegister(RC));
7222     else
7223       return false;
7224   }
7225   return true;
7226 }
7227 
7228 namespace {
7229 
7230 class ExtraFlags {
7231   unsigned Flags = 0;
7232 
7233 public:
7234   explicit ExtraFlags(ImmutableCallSite CS) {
7235     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7236     if (IA->hasSideEffects())
7237       Flags |= InlineAsm::Extra_HasSideEffects;
7238     if (IA->isAlignStack())
7239       Flags |= InlineAsm::Extra_IsAlignStack;
7240     if (CS.isConvergent())
7241       Flags |= InlineAsm::Extra_IsConvergent;
7242     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7243   }
7244 
7245   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7246     // Ideally, we would only check against memory constraints.  However, the
7247     // meaning of an Other constraint can be target-specific and we can't easily
7248     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7249     // for Other constraints as well.
7250     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7251         OpInfo.ConstraintType == TargetLowering::C_Other) {
7252       if (OpInfo.Type == InlineAsm::isInput)
7253         Flags |= InlineAsm::Extra_MayLoad;
7254       else if (OpInfo.Type == InlineAsm::isOutput)
7255         Flags |= InlineAsm::Extra_MayStore;
7256       else if (OpInfo.Type == InlineAsm::isClobber)
7257         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7258     }
7259   }
7260 
7261   unsigned get() const { return Flags; }
7262 };
7263 
7264 } // end anonymous namespace
7265 
7266 /// visitInlineAsm - Handle a call to an InlineAsm object.
7267 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7268   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7269 
7270   /// ConstraintOperands - Information about all of the constraints.
7271   SDISelAsmOperandInfoVector ConstraintOperands;
7272 
7273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7274   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7275       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7276 
7277   bool hasMemory = false;
7278 
7279   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7280   ExtraFlags ExtraInfo(CS);
7281 
7282   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7283   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7284   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7285     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7286     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7287 
7288     MVT OpVT = MVT::Other;
7289 
7290     // Compute the value type for each operand.
7291     if (OpInfo.Type == InlineAsm::isInput ||
7292         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7293       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7294 
7295       // Process the call argument. BasicBlocks are labels, currently appearing
7296       // only in asm's.
7297       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7298         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7299       } else {
7300         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7301       }
7302 
7303       OpVT =
7304           OpInfo
7305               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7306               .getSimpleVT();
7307     }
7308 
7309     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7310       // The return value of the call is this value.  As such, there is no
7311       // corresponding argument.
7312       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7313       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7314         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7315                                       STy->getElementType(ResNo));
7316       } else {
7317         assert(ResNo == 0 && "Asm only has one result!");
7318         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7319       }
7320       ++ResNo;
7321     }
7322 
7323     OpInfo.ConstraintVT = OpVT;
7324 
7325     if (!hasMemory)
7326       hasMemory = OpInfo.hasMemory(TLI);
7327 
7328     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7329     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7330     auto TargetConstraint = TargetConstraints[i];
7331 
7332     // Compute the constraint code and ConstraintType to use.
7333     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7334 
7335     ExtraInfo.update(TargetConstraint);
7336   }
7337 
7338   SDValue Chain, Flag;
7339 
7340   // We won't need to flush pending loads if this asm doesn't touch
7341   // memory and is nonvolatile.
7342   if (hasMemory || IA->hasSideEffects())
7343     Chain = getRoot();
7344   else
7345     Chain = DAG.getRoot();
7346 
7347   // Second pass over the constraints: compute which constraint option to use
7348   // and assign registers to constraints that want a specific physreg.
7349   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7350     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7351 
7352     // If this is an output operand with a matching input operand, look up the
7353     // matching input. If their types mismatch, e.g. one is an integer, the
7354     // other is floating point, or their sizes are different, flag it as an
7355     // error.
7356     if (OpInfo.hasMatchingInput()) {
7357       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7358       patchMatchingInput(OpInfo, Input, DAG);
7359     }
7360 
7361     // Compute the constraint code and ConstraintType to use.
7362     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7363 
7364     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7365         OpInfo.Type == InlineAsm::isClobber)
7366       continue;
7367 
7368     // If this is a memory input, and if the operand is not indirect, do what we
7369     // need to provide an address for the memory input.
7370     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7371         !OpInfo.isIndirect) {
7372       assert((OpInfo.isMultipleAlternative ||
7373               (OpInfo.Type == InlineAsm::isInput)) &&
7374              "Can only indirectify direct input operands!");
7375 
7376       // Memory operands really want the address of the value.
7377       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7378 
7379       // There is no longer a Value* corresponding to this operand.
7380       OpInfo.CallOperandVal = nullptr;
7381 
7382       // It is now an indirect operand.
7383       OpInfo.isIndirect = true;
7384     }
7385 
7386     // If this constraint is for a specific register, allocate it before
7387     // anything else.
7388     if (OpInfo.ConstraintType == TargetLowering::C_Register)
7389       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7390   }
7391 
7392   // Third pass - Loop over all of the operands, assigning virtual or physregs
7393   // to register class operands.
7394   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7395     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7396 
7397     // C_Register operands have already been allocated, Other/Memory don't need
7398     // to be.
7399     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7400       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
7401   }
7402 
7403   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7404   std::vector<SDValue> AsmNodeOperands;
7405   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7406   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7407       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7408 
7409   // If we have a !srcloc metadata node associated with it, we want to attach
7410   // this to the ultimately generated inline asm machineinstr.  To do this, we
7411   // pass in the third operand as this (potentially null) inline asm MDNode.
7412   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7413   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7414 
7415   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7416   // bits as operand 3.
7417   AsmNodeOperands.push_back(DAG.getTargetConstant(
7418       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7419 
7420   // Loop over all of the inputs, copying the operand values into the
7421   // appropriate registers and processing the output regs.
7422   RegsForValue RetValRegs;
7423 
7424   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7425   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7426 
7427   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7428     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7429 
7430     switch (OpInfo.Type) {
7431     case InlineAsm::isOutput:
7432       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7433           OpInfo.ConstraintType != TargetLowering::C_Register) {
7434         // Memory output, or 'other' output (e.g. 'X' constraint).
7435         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7436 
7437         unsigned ConstraintID =
7438             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7439         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7440                "Failed to convert memory constraint code to constraint id.");
7441 
7442         // Add information to the INLINEASM node to know about this output.
7443         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7444         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7445         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7446                                                         MVT::i32));
7447         AsmNodeOperands.push_back(OpInfo.CallOperand);
7448         break;
7449       }
7450 
7451       // Otherwise, this is a register or register class output.
7452 
7453       // Copy the output from the appropriate register.  Find a register that
7454       // we can use.
7455       if (OpInfo.AssignedRegs.Regs.empty()) {
7456         emitInlineAsmError(
7457             CS, "couldn't allocate output register for constraint '" +
7458                     Twine(OpInfo.ConstraintCode) + "'");
7459         return;
7460       }
7461 
7462       // If this is an indirect operand, store through the pointer after the
7463       // asm.
7464       if (OpInfo.isIndirect) {
7465         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7466                                                       OpInfo.CallOperandVal));
7467       } else {
7468         // This is the result value of the call.
7469         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7470         // Concatenate this output onto the outputs list.
7471         RetValRegs.append(OpInfo.AssignedRegs);
7472       }
7473 
7474       // Add information to the INLINEASM node to know that this register is
7475       // set.
7476       OpInfo.AssignedRegs
7477           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7478                                     ? InlineAsm::Kind_RegDefEarlyClobber
7479                                     : InlineAsm::Kind_RegDef,
7480                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7481       break;
7482 
7483     case InlineAsm::isInput: {
7484       SDValue InOperandVal = OpInfo.CallOperand;
7485 
7486       if (OpInfo.isMatchingInputConstraint()) {
7487         // If this is required to match an output register we have already set,
7488         // just use its register.
7489         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7490                                                   AsmNodeOperands);
7491         unsigned OpFlag =
7492           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7493         if (InlineAsm::isRegDefKind(OpFlag) ||
7494             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7495           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7496           if (OpInfo.isIndirect) {
7497             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7498             emitInlineAsmError(CS, "inline asm not supported yet:"
7499                                    " don't know how to handle tied "
7500                                    "indirect register inputs");
7501             return;
7502           }
7503 
7504           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7505           SmallVector<unsigned, 4> Regs;
7506 
7507           if (!createVirtualRegs(Regs,
7508                                  InlineAsm::getNumOperandRegisters(OpFlag),
7509                                  RegVT, DAG)) {
7510             emitInlineAsmError(CS, "inline asm error: This value type register "
7511                                    "class is not natively supported!");
7512             return;
7513           }
7514 
7515           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7516 
7517           SDLoc dl = getCurSDLoc();
7518           // Use the produced MatchedRegs object to
7519           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7520                                     CS.getInstruction());
7521           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7522                                            true, OpInfo.getMatchedOperand(), dl,
7523                                            DAG, AsmNodeOperands);
7524           break;
7525         }
7526 
7527         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7528         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7529                "Unexpected number of operands");
7530         // Add information to the INLINEASM node to know about this input.
7531         // See InlineAsm.h isUseOperandTiedToDef.
7532         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7533         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7534                                                     OpInfo.getMatchedOperand());
7535         AsmNodeOperands.push_back(DAG.getTargetConstant(
7536             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7537         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7538         break;
7539       }
7540 
7541       // Treat indirect 'X' constraint as memory.
7542       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7543           OpInfo.isIndirect)
7544         OpInfo.ConstraintType = TargetLowering::C_Memory;
7545 
7546       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7547         std::vector<SDValue> Ops;
7548         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7549                                           Ops, DAG);
7550         if (Ops.empty()) {
7551           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7552                                      Twine(OpInfo.ConstraintCode) + "'");
7553           return;
7554         }
7555 
7556         // Add information to the INLINEASM node to know about this input.
7557         unsigned ResOpType =
7558           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7559         AsmNodeOperands.push_back(DAG.getTargetConstant(
7560             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7561         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7562         break;
7563       }
7564 
7565       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7566         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7567         assert(InOperandVal.getValueType() ==
7568                    TLI.getPointerTy(DAG.getDataLayout()) &&
7569                "Memory operands expect pointer values");
7570 
7571         unsigned ConstraintID =
7572             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7573         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7574                "Failed to convert memory constraint code to constraint id.");
7575 
7576         // Add information to the INLINEASM node to know about this input.
7577         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7578         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7579         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7580                                                         getCurSDLoc(),
7581                                                         MVT::i32));
7582         AsmNodeOperands.push_back(InOperandVal);
7583         break;
7584       }
7585 
7586       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7587               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7588              "Unknown constraint type!");
7589 
7590       // TODO: Support this.
7591       if (OpInfo.isIndirect) {
7592         emitInlineAsmError(
7593             CS, "Don't know how to handle indirect register inputs yet "
7594                 "for constraint '" +
7595                     Twine(OpInfo.ConstraintCode) + "'");
7596         return;
7597       }
7598 
7599       // Copy the input into the appropriate registers.
7600       if (OpInfo.AssignedRegs.Regs.empty()) {
7601         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7602                                    Twine(OpInfo.ConstraintCode) + "'");
7603         return;
7604       }
7605 
7606       SDLoc dl = getCurSDLoc();
7607 
7608       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7609                                         Chain, &Flag, CS.getInstruction());
7610 
7611       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7612                                                dl, DAG, AsmNodeOperands);
7613       break;
7614     }
7615     case InlineAsm::isClobber:
7616       // Add the clobbered value to the operand list, so that the register
7617       // allocator is aware that the physreg got clobbered.
7618       if (!OpInfo.AssignedRegs.Regs.empty())
7619         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7620                                                  false, 0, getCurSDLoc(), DAG,
7621                                                  AsmNodeOperands);
7622       break;
7623     }
7624   }
7625 
7626   // Finish up input operands.  Set the input chain and add the flag last.
7627   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7628   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7629 
7630   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7631                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7632   Flag = Chain.getValue(1);
7633 
7634   // If this asm returns a register value, copy the result from that register
7635   // and set it as the value of the call.
7636   if (!RetValRegs.Regs.empty()) {
7637     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7638                                              Chain, &Flag, CS.getInstruction());
7639 
7640     // FIXME: Why don't we do this for inline asms with MRVs?
7641     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
7642       EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7643 
7644       // If any of the results of the inline asm is a vector, it may have the
7645       // wrong width/num elts.  This can happen for register classes that can
7646       // contain multiple different value types.  The preg or vreg allocated may
7647       // not have the same VT as was expected.  Convert it to the right type
7648       // with bit_convert.
7649       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
7650         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
7651                           ResultType, Val);
7652 
7653       } else if (ResultType != Val.getValueType() &&
7654                  ResultType.isInteger() && Val.getValueType().isInteger()) {
7655         // If a result value was tied to an input value, the computed result may
7656         // have a wider width than the expected result.  Extract the relevant
7657         // portion.
7658         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
7659       }
7660 
7661       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
7662     }
7663 
7664     setValue(CS.getInstruction(), Val);
7665     // Don't need to use this as a chain in this case.
7666     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7667       return;
7668   }
7669 
7670   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7671 
7672   // Process indirect outputs, first output all of the flagged copies out of
7673   // physregs.
7674   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7675     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7676     const Value *Ptr = IndirectStoresToEmit[i].second;
7677     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7678                                              Chain, &Flag, IA);
7679     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7680   }
7681 
7682   // Emit the non-flagged stores from the physregs.
7683   SmallVector<SDValue, 8> OutChains;
7684   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7685     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7686                                getValue(StoresToEmit[i].second),
7687                                MachinePointerInfo(StoresToEmit[i].second));
7688     OutChains.push_back(Val);
7689   }
7690 
7691   if (!OutChains.empty())
7692     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7693 
7694   DAG.setRoot(Chain);
7695 }
7696 
7697 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7698                                              const Twine &Message) {
7699   LLVMContext &Ctx = *DAG.getContext();
7700   Ctx.emitError(CS.getInstruction(), Message);
7701 
7702   // Make sure we leave the DAG in a valid state
7703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7704   auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType());
7705   setValue(CS.getInstruction(), DAG.getUNDEF(VT));
7706 }
7707 
7708 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7709   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7710                           MVT::Other, getRoot(),
7711                           getValue(I.getArgOperand(0)),
7712                           DAG.getSrcValue(I.getArgOperand(0))));
7713 }
7714 
7715 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7717   const DataLayout &DL = DAG.getDataLayout();
7718   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7719                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7720                            DAG.getSrcValue(I.getOperand(0)),
7721                            DL.getABITypeAlignment(I.getType()));
7722   setValue(&I, V);
7723   DAG.setRoot(V.getValue(1));
7724 }
7725 
7726 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7727   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7728                           MVT::Other, getRoot(),
7729                           getValue(I.getArgOperand(0)),
7730                           DAG.getSrcValue(I.getArgOperand(0))));
7731 }
7732 
7733 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7734   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7735                           MVT::Other, getRoot(),
7736                           getValue(I.getArgOperand(0)),
7737                           getValue(I.getArgOperand(1)),
7738                           DAG.getSrcValue(I.getArgOperand(0)),
7739                           DAG.getSrcValue(I.getArgOperand(1))));
7740 }
7741 
7742 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7743                                                     const Instruction &I,
7744                                                     SDValue Op) {
7745   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7746   if (!Range)
7747     return Op;
7748 
7749   ConstantRange CR = getConstantRangeFromMetadata(*Range);
7750   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
7751     return Op;
7752 
7753   APInt Lo = CR.getUnsignedMin();
7754   if (!Lo.isMinValue())
7755     return Op;
7756 
7757   APInt Hi = CR.getUnsignedMax();
7758   unsigned Bits = Hi.getActiveBits();
7759 
7760   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7761 
7762   SDLoc SL = getCurSDLoc();
7763 
7764   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
7765                              DAG.getValueType(SmallVT));
7766   unsigned NumVals = Op.getNode()->getNumValues();
7767   if (NumVals == 1)
7768     return ZExt;
7769 
7770   SmallVector<SDValue, 4> Ops;
7771 
7772   Ops.push_back(ZExt);
7773   for (unsigned I = 1; I != NumVals; ++I)
7774     Ops.push_back(Op.getValue(I));
7775 
7776   return DAG.getMergeValues(Ops, SL);
7777 }
7778 
7779 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of
7780 /// the call being lowered.
7781 ///
7782 /// This is a helper for lowering intrinsics that follow a target calling
7783 /// convention or require stack pointer adjustment. Only a subset of the
7784 /// intrinsic's operands need to participate in the calling convention.
7785 void SelectionDAGBuilder::populateCallLoweringInfo(
7786     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
7787     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
7788     bool IsPatchPoint) {
7789   TargetLowering::ArgListTy Args;
7790   Args.reserve(NumArgs);
7791 
7792   // Populate the argument list.
7793   // Attributes for args start at offset 1, after the return attribute.
7794   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
7795        ArgI != ArgE; ++ArgI) {
7796     const Value *V = CS->getOperand(ArgI);
7797 
7798     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
7799 
7800     TargetLowering::ArgListEntry Entry;
7801     Entry.Node = getValue(V);
7802     Entry.Ty = V->getType();
7803     Entry.setAttributes(&CS, ArgI);
7804     Args.push_back(Entry);
7805   }
7806 
7807   CLI.setDebugLoc(getCurSDLoc())
7808       .setChain(getRoot())
7809       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
7810       .setDiscardResult(CS->use_empty())
7811       .setIsPatchPoint(IsPatchPoint);
7812 }
7813 
7814 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
7815 /// or patchpoint target node's operand list.
7816 ///
7817 /// Constants are converted to TargetConstants purely as an optimization to
7818 /// avoid constant materialization and register allocation.
7819 ///
7820 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
7821 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
7822 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
7823 /// address materialization and register allocation, but may also be required
7824 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7825 /// alloca in the entry block, then the runtime may assume that the alloca's
7826 /// StackMap location can be read immediately after compilation and that the
7827 /// location is valid at any point during execution (this is similar to the
7828 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7829 /// only available in a register, then the runtime would need to trap when
7830 /// execution reaches the StackMap in order to read the alloca's location.
7831 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7832                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
7833                                 SelectionDAGBuilder &Builder) {
7834   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7835     SDValue OpVal = Builder.getValue(CS.getArgument(i));
7836     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7837       Ops.push_back(
7838         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
7839       Ops.push_back(
7840         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
7841     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7842       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7843       Ops.push_back(Builder.DAG.getTargetFrameIndex(
7844           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
7845     } else
7846       Ops.push_back(OpVal);
7847   }
7848 }
7849 
7850 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7851 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7852   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7853   //                                  [live variables...])
7854 
7855   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7856 
7857   SDValue Chain, InFlag, Callee, NullPtr;
7858   SmallVector<SDValue, 32> Ops;
7859 
7860   SDLoc DL = getCurSDLoc();
7861   Callee = getValue(CI.getCalledValue());
7862   NullPtr = DAG.getIntPtrConstant(0, DL, true);
7863 
7864   // The stackmap intrinsic only records the live variables (the arguemnts
7865   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7866   // intrinsic, this won't be lowered to a function call. This means we don't
7867   // have to worry about calling conventions and target specific lowering code.
7868   // Instead we perform the call lowering right here.
7869   //
7870   // chain, flag = CALLSEQ_START(chain, 0, 0)
7871   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7872   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7873   //
7874   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
7875   InFlag = Chain.getValue(1);
7876 
7877   // Add the <id> and <numBytes> constants.
7878   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7879   Ops.push_back(DAG.getTargetConstant(
7880                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
7881   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7882   Ops.push_back(DAG.getTargetConstant(
7883                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
7884                   MVT::i32));
7885 
7886   // Push live variables for the stack map.
7887   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
7888 
7889   // We are not pushing any register mask info here on the operands list,
7890   // because the stackmap doesn't clobber anything.
7891 
7892   // Push the chain and the glue flag.
7893   Ops.push_back(Chain);
7894   Ops.push_back(InFlag);
7895 
7896   // Create the STACKMAP node.
7897   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7898   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7899   Chain = SDValue(SM, 0);
7900   InFlag = Chain.getValue(1);
7901 
7902   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7903 
7904   // Stackmaps don't generate values, so nothing goes into the NodeMap.
7905 
7906   // Set the root to the target-lowered call chain.
7907   DAG.setRoot(Chain);
7908 
7909   // Inform the Frame Information that we have a stackmap in this function.
7910   FuncInfo.MF->getFrameInfo().setHasStackMap();
7911 }
7912 
7913 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7914 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7915                                           const BasicBlock *EHPadBB) {
7916   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7917   //                                                 i32 <numBytes>,
7918   //                                                 i8* <target>,
7919   //                                                 i32 <numArgs>,
7920   //                                                 [Args...],
7921   //                                                 [live variables...])
7922 
7923   CallingConv::ID CC = CS.getCallingConv();
7924   bool IsAnyRegCC = CC == CallingConv::AnyReg;
7925   bool HasDef = !CS->getType()->isVoidTy();
7926   SDLoc dl = getCurSDLoc();
7927   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
7928 
7929   // Handle immediate and symbolic callees.
7930   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
7931     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
7932                                    /*isTarget=*/true);
7933   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
7934     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
7935                                          SDLoc(SymbolicCallee),
7936                                          SymbolicCallee->getValueType(0));
7937 
7938   // Get the real number of arguments participating in the call <numArgs>
7939   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7940   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7941 
7942   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7943   // Intrinsics include all meta-operands up to but not including CC.
7944   unsigned NumMetaOpers = PatchPointOpers::CCPos;
7945   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7946          "Not enough arguments provided to the patchpoint intrinsic");
7947 
7948   // For AnyRegCC the arguments are lowered later on manually.
7949   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7950   Type *ReturnTy =
7951     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
7952 
7953   TargetLowering::CallLoweringInfo CLI(DAG);
7954   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
7955                            true);
7956   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7957 
7958   SDNode *CallEnd = Result.second.getNode();
7959   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7960     CallEnd = CallEnd->getOperand(0).getNode();
7961 
7962   /// Get a call instruction from the call sequence chain.
7963   /// Tail calls are not allowed.
7964   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7965          "Expected a callseq node.");
7966   SDNode *Call = CallEnd->getOperand(0).getNode();
7967   bool HasGlue = Call->getGluedNode();
7968 
7969   // Replace the target specific call node with the patchable intrinsic.
7970   SmallVector<SDValue, 8> Ops;
7971 
7972   // Add the <id> and <numBytes> constants.
7973   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7974   Ops.push_back(DAG.getTargetConstant(
7975                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
7976   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7977   Ops.push_back(DAG.getTargetConstant(
7978                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
7979                   MVT::i32));
7980 
7981   // Add the callee.
7982   Ops.push_back(Callee);
7983 
7984   // Adjust <numArgs> to account for any arguments that have been passed on the
7985   // stack instead.
7986   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7987   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7988   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7989   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
7990 
7991   // Add the calling convention
7992   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
7993 
7994   // Add the arguments we omitted previously. The register allocator should
7995   // place these in any free register.
7996   if (IsAnyRegCC)
7997     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7998       Ops.push_back(getValue(CS.getArgument(i)));
7999 
8000   // Push the arguments from the call instruction up to the register mask.
8001   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8002   Ops.append(Call->op_begin() + 2, e);
8003 
8004   // Push live variables for the stack map.
8005   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8006 
8007   // Push the register mask info.
8008   if (HasGlue)
8009     Ops.push_back(*(Call->op_end()-2));
8010   else
8011     Ops.push_back(*(Call->op_end()-1));
8012 
8013   // Push the chain (this is originally the first operand of the call, but
8014   // becomes now the last or second to last operand).
8015   Ops.push_back(*(Call->op_begin()));
8016 
8017   // Push the glue flag (last operand).
8018   if (HasGlue)
8019     Ops.push_back(*(Call->op_end()-1));
8020 
8021   SDVTList NodeTys;
8022   if (IsAnyRegCC && HasDef) {
8023     // Create the return types based on the intrinsic definition
8024     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8025     SmallVector<EVT, 3> ValueVTs;
8026     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8027     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8028 
8029     // There is always a chain and a glue type at the end
8030     ValueVTs.push_back(MVT::Other);
8031     ValueVTs.push_back(MVT::Glue);
8032     NodeTys = DAG.getVTList(ValueVTs);
8033   } else
8034     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8035 
8036   // Replace the target specific call node with a PATCHPOINT node.
8037   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8038                                          dl, NodeTys, Ops);
8039 
8040   // Update the NodeMap.
8041   if (HasDef) {
8042     if (IsAnyRegCC)
8043       setValue(CS.getInstruction(), SDValue(MN, 0));
8044     else
8045       setValue(CS.getInstruction(), Result.first);
8046   }
8047 
8048   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8049   // call sequence. Furthermore the location of the chain and glue can change
8050   // when the AnyReg calling convention is used and the intrinsic returns a
8051   // value.
8052   if (IsAnyRegCC && HasDef) {
8053     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8054     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8055     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8056   } else
8057     DAG.ReplaceAllUsesWith(Call, MN);
8058   DAG.DeleteNode(Call);
8059 
8060   // Inform the Frame Information that we have a patchpoint in this function.
8061   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8062 }
8063 
8064 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8065                                             unsigned Intrinsic) {
8066   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8067   SDValue Op1 = getValue(I.getArgOperand(0));
8068   SDValue Op2;
8069   if (I.getNumArgOperands() > 1)
8070     Op2 = getValue(I.getArgOperand(1));
8071   SDLoc dl = getCurSDLoc();
8072   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8073   SDValue Res;
8074   FastMathFlags FMF;
8075   if (isa<FPMathOperator>(I))
8076     FMF = I.getFastMathFlags();
8077   SDNodeFlags SDFlags;
8078   SDFlags.setNoNaNs(FMF.noNaNs());
8079 
8080   switch (Intrinsic) {
8081   case Intrinsic::experimental_vector_reduce_fadd:
8082     if (FMF.isFast())
8083       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8084     else
8085       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8086     break;
8087   case Intrinsic::experimental_vector_reduce_fmul:
8088     if (FMF.isFast())
8089       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8090     else
8091       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8092     break;
8093   case Intrinsic::experimental_vector_reduce_add:
8094     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8095     break;
8096   case Intrinsic::experimental_vector_reduce_mul:
8097     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8098     break;
8099   case Intrinsic::experimental_vector_reduce_and:
8100     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8101     break;
8102   case Intrinsic::experimental_vector_reduce_or:
8103     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8104     break;
8105   case Intrinsic::experimental_vector_reduce_xor:
8106     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8107     break;
8108   case Intrinsic::experimental_vector_reduce_smax:
8109     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8110     break;
8111   case Intrinsic::experimental_vector_reduce_smin:
8112     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8113     break;
8114   case Intrinsic::experimental_vector_reduce_umax:
8115     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8116     break;
8117   case Intrinsic::experimental_vector_reduce_umin:
8118     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8119     break;
8120   case Intrinsic::experimental_vector_reduce_fmax:
8121     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
8122     break;
8123   case Intrinsic::experimental_vector_reduce_fmin:
8124     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
8125     break;
8126   default:
8127     llvm_unreachable("Unhandled vector reduce intrinsic");
8128   }
8129   setValue(&I, Res);
8130 }
8131 
8132 /// Returns an AttributeList representing the attributes applied to the return
8133 /// value of the given call.
8134 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8135   SmallVector<Attribute::AttrKind, 2> Attrs;
8136   if (CLI.RetSExt)
8137     Attrs.push_back(Attribute::SExt);
8138   if (CLI.RetZExt)
8139     Attrs.push_back(Attribute::ZExt);
8140   if (CLI.IsInReg)
8141     Attrs.push_back(Attribute::InReg);
8142 
8143   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8144                             Attrs);
8145 }
8146 
8147 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8148 /// implementation, which just calls LowerCall.
8149 /// FIXME: When all targets are
8150 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8151 std::pair<SDValue, SDValue>
8152 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8153   // Handle the incoming return values from the call.
8154   CLI.Ins.clear();
8155   Type *OrigRetTy = CLI.RetTy;
8156   SmallVector<EVT, 4> RetTys;
8157   SmallVector<uint64_t, 4> Offsets;
8158   auto &DL = CLI.DAG.getDataLayout();
8159   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8160 
8161   if (CLI.IsPostTypeLegalization) {
8162     // If we are lowering a libcall after legalization, split the return type.
8163     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8164     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8165     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8166       EVT RetVT = OldRetTys[i];
8167       uint64_t Offset = OldOffsets[i];
8168       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8169       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8170       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8171       RetTys.append(NumRegs, RegisterVT);
8172       for (unsigned j = 0; j != NumRegs; ++j)
8173         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8174     }
8175   }
8176 
8177   SmallVector<ISD::OutputArg, 4> Outs;
8178   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8179 
8180   bool CanLowerReturn =
8181       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8182                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8183 
8184   SDValue DemoteStackSlot;
8185   int DemoteStackIdx = -100;
8186   if (!CanLowerReturn) {
8187     // FIXME: equivalent assert?
8188     // assert(!CS.hasInAllocaArgument() &&
8189     //        "sret demotion is incompatible with inalloca");
8190     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8191     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8192     MachineFunction &MF = CLI.DAG.getMachineFunction();
8193     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8194     Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
8195 
8196     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8197     ArgListEntry Entry;
8198     Entry.Node = DemoteStackSlot;
8199     Entry.Ty = StackSlotPtrType;
8200     Entry.IsSExt = false;
8201     Entry.IsZExt = false;
8202     Entry.IsInReg = false;
8203     Entry.IsSRet = true;
8204     Entry.IsNest = false;
8205     Entry.IsByVal = false;
8206     Entry.IsReturned = false;
8207     Entry.IsSwiftSelf = false;
8208     Entry.IsSwiftError = false;
8209     Entry.Alignment = Align;
8210     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8211     CLI.NumFixedArgs += 1;
8212     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8213 
8214     // sret demotion isn't compatible with tail-calls, since the sret argument
8215     // points into the callers stack frame.
8216     CLI.IsTailCall = false;
8217   } else {
8218     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8219       EVT VT = RetTys[I];
8220       MVT RegisterVT =
8221           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8222       unsigned NumRegs =
8223           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8224       for (unsigned i = 0; i != NumRegs; ++i) {
8225         ISD::InputArg MyFlags;
8226         MyFlags.VT = RegisterVT;
8227         MyFlags.ArgVT = VT;
8228         MyFlags.Used = CLI.IsReturnValueUsed;
8229         if (CLI.RetSExt)
8230           MyFlags.Flags.setSExt();
8231         if (CLI.RetZExt)
8232           MyFlags.Flags.setZExt();
8233         if (CLI.IsInReg)
8234           MyFlags.Flags.setInReg();
8235         CLI.Ins.push_back(MyFlags);
8236       }
8237     }
8238   }
8239 
8240   // We push in swifterror return as the last element of CLI.Ins.
8241   ArgListTy &Args = CLI.getArgs();
8242   if (supportSwiftError()) {
8243     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8244       if (Args[i].IsSwiftError) {
8245         ISD::InputArg MyFlags;
8246         MyFlags.VT = getPointerTy(DL);
8247         MyFlags.ArgVT = EVT(getPointerTy(DL));
8248         MyFlags.Flags.setSwiftError();
8249         CLI.Ins.push_back(MyFlags);
8250       }
8251     }
8252   }
8253 
8254   // Handle all of the outgoing arguments.
8255   CLI.Outs.clear();
8256   CLI.OutVals.clear();
8257   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8258     SmallVector<EVT, 4> ValueVTs;
8259     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8260     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8261     Type *FinalType = Args[i].Ty;
8262     if (Args[i].IsByVal)
8263       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8264     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8265         FinalType, CLI.CallConv, CLI.IsVarArg);
8266     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8267          ++Value) {
8268       EVT VT = ValueVTs[Value];
8269       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8270       SDValue Op = SDValue(Args[i].Node.getNode(),
8271                            Args[i].Node.getResNo() + Value);
8272       ISD::ArgFlagsTy Flags;
8273 
8274       // Certain targets (such as MIPS), may have a different ABI alignment
8275       // for a type depending on the context. Give the target a chance to
8276       // specify the alignment it wants.
8277       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8278 
8279       if (Args[i].IsZExt)
8280         Flags.setZExt();
8281       if (Args[i].IsSExt)
8282         Flags.setSExt();
8283       if (Args[i].IsInReg) {
8284         // If we are using vectorcall calling convention, a structure that is
8285         // passed InReg - is surely an HVA
8286         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8287             isa<StructType>(FinalType)) {
8288           // The first value of a structure is marked
8289           if (0 == Value)
8290             Flags.setHvaStart();
8291           Flags.setHva();
8292         }
8293         // Set InReg Flag
8294         Flags.setInReg();
8295       }
8296       if (Args[i].IsSRet)
8297         Flags.setSRet();
8298       if (Args[i].IsSwiftSelf)
8299         Flags.setSwiftSelf();
8300       if (Args[i].IsSwiftError)
8301         Flags.setSwiftError();
8302       if (Args[i].IsByVal)
8303         Flags.setByVal();
8304       if (Args[i].IsInAlloca) {
8305         Flags.setInAlloca();
8306         // Set the byval flag for CCAssignFn callbacks that don't know about
8307         // inalloca.  This way we can know how many bytes we should've allocated
8308         // and how many bytes a callee cleanup function will pop.  If we port
8309         // inalloca to more targets, we'll have to add custom inalloca handling
8310         // in the various CC lowering callbacks.
8311         Flags.setByVal();
8312       }
8313       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8314         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8315         Type *ElementTy = Ty->getElementType();
8316         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8317         // For ByVal, alignment should come from FE.  BE will guess if this
8318         // info is not there but there are cases it cannot get right.
8319         unsigned FrameAlign;
8320         if (Args[i].Alignment)
8321           FrameAlign = Args[i].Alignment;
8322         else
8323           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8324         Flags.setByValAlign(FrameAlign);
8325       }
8326       if (Args[i].IsNest)
8327         Flags.setNest();
8328       if (NeedsRegBlock)
8329         Flags.setInConsecutiveRegs();
8330       Flags.setOrigAlign(OriginalAlignment);
8331 
8332       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8333       unsigned NumParts =
8334           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8335       SmallVector<SDValue, 4> Parts(NumParts);
8336       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8337 
8338       if (Args[i].IsSExt)
8339         ExtendKind = ISD::SIGN_EXTEND;
8340       else if (Args[i].IsZExt)
8341         ExtendKind = ISD::ZERO_EXTEND;
8342 
8343       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8344       // for now.
8345       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8346           CanLowerReturn) {
8347         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8348                "unexpected use of 'returned'");
8349         // Before passing 'returned' to the target lowering code, ensure that
8350         // either the register MVT and the actual EVT are the same size or that
8351         // the return value and argument are extended in the same way; in these
8352         // cases it's safe to pass the argument register value unchanged as the
8353         // return register value (although it's at the target's option whether
8354         // to do so)
8355         // TODO: allow code generation to take advantage of partially preserved
8356         // registers rather than clobbering the entire register when the
8357         // parameter extension method is not compatible with the return
8358         // extension method
8359         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8360             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8361              CLI.RetZExt == Args[i].IsZExt))
8362           Flags.setReturned();
8363       }
8364 
8365       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8366                      CLI.CS.getInstruction(), ExtendKind, true);
8367 
8368       for (unsigned j = 0; j != NumParts; ++j) {
8369         // if it isn't first piece, alignment must be 1
8370         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8371                                i < CLI.NumFixedArgs,
8372                                i, j*Parts[j].getValueType().getStoreSize());
8373         if (NumParts > 1 && j == 0)
8374           MyFlags.Flags.setSplit();
8375         else if (j != 0) {
8376           MyFlags.Flags.setOrigAlign(1);
8377           if (j == NumParts - 1)
8378             MyFlags.Flags.setSplitEnd();
8379         }
8380 
8381         CLI.Outs.push_back(MyFlags);
8382         CLI.OutVals.push_back(Parts[j]);
8383       }
8384 
8385       if (NeedsRegBlock && Value == NumValues - 1)
8386         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8387     }
8388   }
8389 
8390   SmallVector<SDValue, 4> InVals;
8391   CLI.Chain = LowerCall(CLI, InVals);
8392 
8393   // Update CLI.InVals to use outside of this function.
8394   CLI.InVals = InVals;
8395 
8396   // Verify that the target's LowerCall behaved as expected.
8397   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8398          "LowerCall didn't return a valid chain!");
8399   assert((!CLI.IsTailCall || InVals.empty()) &&
8400          "LowerCall emitted a return value for a tail call!");
8401   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8402          "LowerCall didn't emit the correct number of values!");
8403 
8404   // For a tail call, the return value is merely live-out and there aren't
8405   // any nodes in the DAG representing it. Return a special value to
8406   // indicate that a tail call has been emitted and no more Instructions
8407   // should be processed in the current block.
8408   if (CLI.IsTailCall) {
8409     CLI.DAG.setRoot(CLI.Chain);
8410     return std::make_pair(SDValue(), SDValue());
8411   }
8412 
8413 #ifndef NDEBUG
8414   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8415     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8416     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8417            "LowerCall emitted a value with the wrong type!");
8418   }
8419 #endif
8420 
8421   SmallVector<SDValue, 4> ReturnValues;
8422   if (!CanLowerReturn) {
8423     // The instruction result is the result of loading from the
8424     // hidden sret parameter.
8425     SmallVector<EVT, 1> PVTs;
8426     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8427 
8428     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8429     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8430     EVT PtrVT = PVTs[0];
8431 
8432     unsigned NumValues = RetTys.size();
8433     ReturnValues.resize(NumValues);
8434     SmallVector<SDValue, 4> Chains(NumValues);
8435 
8436     // An aggregate return value cannot wrap around the address space, so
8437     // offsets to its parts don't wrap either.
8438     SDNodeFlags Flags;
8439     Flags.setNoUnsignedWrap(true);
8440 
8441     for (unsigned i = 0; i < NumValues; ++i) {
8442       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8443                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8444                                                         PtrVT), Flags);
8445       SDValue L = CLI.DAG.getLoad(
8446           RetTys[i], CLI.DL, CLI.Chain, Add,
8447           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8448                                             DemoteStackIdx, Offsets[i]),
8449           /* Alignment = */ 1);
8450       ReturnValues[i] = L;
8451       Chains[i] = L.getValue(1);
8452     }
8453 
8454     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8455   } else {
8456     // Collect the legal value parts into potentially illegal values
8457     // that correspond to the original function's return values.
8458     Optional<ISD::NodeType> AssertOp;
8459     if (CLI.RetSExt)
8460       AssertOp = ISD::AssertSext;
8461     else if (CLI.RetZExt)
8462       AssertOp = ISD::AssertZext;
8463     unsigned CurReg = 0;
8464     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8465       EVT VT = RetTys[I];
8466       MVT RegisterVT =
8467           getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT);
8468       unsigned NumRegs =
8469           getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT);
8470 
8471       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8472                                               NumRegs, RegisterVT, VT, nullptr,
8473                                               AssertOp, true));
8474       CurReg += NumRegs;
8475     }
8476 
8477     // For a function returning void, there is no return value. We can't create
8478     // such a node, so we just return a null return value in that case. In
8479     // that case, nothing will actually look at the value.
8480     if (ReturnValues.empty())
8481       return std::make_pair(SDValue(), CLI.Chain);
8482   }
8483 
8484   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8485                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8486   return std::make_pair(Res, CLI.Chain);
8487 }
8488 
8489 void TargetLowering::LowerOperationWrapper(SDNode *N,
8490                                            SmallVectorImpl<SDValue> &Results,
8491                                            SelectionDAG &DAG) const {
8492   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8493     Results.push_back(Res);
8494 }
8495 
8496 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8497   llvm_unreachable("LowerOperation not implemented for this target!");
8498 }
8499 
8500 void
8501 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8502   SDValue Op = getNonRegisterValue(V);
8503   assert((Op.getOpcode() != ISD::CopyFromReg ||
8504           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8505          "Copy from a reg to the same reg!");
8506   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8507 
8508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8509   // If this is an InlineAsm we have to match the registers required, not the
8510   // notional registers required by the type.
8511 
8512   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
8513                    V->getType(), isABIRegCopy(V));
8514   SDValue Chain = DAG.getEntryNode();
8515 
8516   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8517                               FuncInfo.PreferredExtendType.end())
8518                                  ? ISD::ANY_EXTEND
8519                                  : FuncInfo.PreferredExtendType[V];
8520   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8521   PendingExports.push_back(Chain);
8522 }
8523 
8524 #include "llvm/CodeGen/SelectionDAGISel.h"
8525 
8526 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8527 /// entry block, return true.  This includes arguments used by switches, since
8528 /// the switch may expand into multiple basic blocks.
8529 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8530   // With FastISel active, we may be splitting blocks, so force creation
8531   // of virtual registers for all non-dead arguments.
8532   if (FastISel)
8533     return A->use_empty();
8534 
8535   const BasicBlock &Entry = A->getParent()->front();
8536   for (const User *U : A->users())
8537     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8538       return false;  // Use not in entry block.
8539 
8540   return true;
8541 }
8542 
8543 using ArgCopyElisionMapTy =
8544     DenseMap<const Argument *,
8545              std::pair<const AllocaInst *, const StoreInst *>>;
8546 
8547 /// Scan the entry block of the function in FuncInfo for arguments that look
8548 /// like copies into a local alloca. Record any copied arguments in
8549 /// ArgCopyElisionCandidates.
8550 static void
8551 findArgumentCopyElisionCandidates(const DataLayout &DL,
8552                                   FunctionLoweringInfo *FuncInfo,
8553                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8554   // Record the state of every static alloca used in the entry block. Argument
8555   // allocas are all used in the entry block, so we need approximately as many
8556   // entries as we have arguments.
8557   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8558   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8559   unsigned NumArgs = FuncInfo->Fn->arg_size();
8560   StaticAllocas.reserve(NumArgs * 2);
8561 
8562   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8563     if (!V)
8564       return nullptr;
8565     V = V->stripPointerCasts();
8566     const auto *AI = dyn_cast<AllocaInst>(V);
8567     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8568       return nullptr;
8569     auto Iter = StaticAllocas.insert({AI, Unknown});
8570     return &Iter.first->second;
8571   };
8572 
8573   // Look for stores of arguments to static allocas. Look through bitcasts and
8574   // GEPs to handle type coercions, as long as the alloca is fully initialized
8575   // by the store. Any non-store use of an alloca escapes it and any subsequent
8576   // unanalyzed store might write it.
8577   // FIXME: Handle structs initialized with multiple stores.
8578   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8579     // Look for stores, and handle non-store uses conservatively.
8580     const auto *SI = dyn_cast<StoreInst>(&I);
8581     if (!SI) {
8582       // We will look through cast uses, so ignore them completely.
8583       if (I.isCast())
8584         continue;
8585       // Ignore debug info intrinsics, they don't escape or store to allocas.
8586       if (isa<DbgInfoIntrinsic>(I))
8587         continue;
8588       // This is an unknown instruction. Assume it escapes or writes to all
8589       // static alloca operands.
8590       for (const Use &U : I.operands()) {
8591         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8592           *Info = StaticAllocaInfo::Clobbered;
8593       }
8594       continue;
8595     }
8596 
8597     // If the stored value is a static alloca, mark it as escaped.
8598     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8599       *Info = StaticAllocaInfo::Clobbered;
8600 
8601     // Check if the destination is a static alloca.
8602     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8603     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8604     if (!Info)
8605       continue;
8606     const AllocaInst *AI = cast<AllocaInst>(Dst);
8607 
8608     // Skip allocas that have been initialized or clobbered.
8609     if (*Info != StaticAllocaInfo::Unknown)
8610       continue;
8611 
8612     // Check if the stored value is an argument, and that this store fully
8613     // initializes the alloca. Don't elide copies from the same argument twice.
8614     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8615     const auto *Arg = dyn_cast<Argument>(Val);
8616     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8617         Arg->getType()->isEmptyTy() ||
8618         DL.getTypeStoreSize(Arg->getType()) !=
8619             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8620         ArgCopyElisionCandidates.count(Arg)) {
8621       *Info = StaticAllocaInfo::Clobbered;
8622       continue;
8623     }
8624 
8625     DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n');
8626 
8627     // Mark this alloca and store for argument copy elision.
8628     *Info = StaticAllocaInfo::Elidable;
8629     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8630 
8631     // Stop scanning if we've seen all arguments. This will happen early in -O0
8632     // builds, which is useful, because -O0 builds have large entry blocks and
8633     // many allocas.
8634     if (ArgCopyElisionCandidates.size() == NumArgs)
8635       break;
8636   }
8637 }
8638 
8639 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8640 /// ArgVal is a load from a suitable fixed stack object.
8641 static void tryToElideArgumentCopy(
8642     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8643     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8644     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8645     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8646     SDValue ArgVal, bool &ArgHasUses) {
8647   // Check if this is a load from a fixed stack object.
8648   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8649   if (!LNode)
8650     return;
8651   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8652   if (!FINode)
8653     return;
8654 
8655   // Check that the fixed stack object is the right size and alignment.
8656   // Look at the alignment that the user wrote on the alloca instead of looking
8657   // at the stack object.
8658   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8659   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8660   const AllocaInst *AI = ArgCopyIter->second.first;
8661   int FixedIndex = FINode->getIndex();
8662   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8663   int OldIndex = AllocaIndex;
8664   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8665   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8666     DEBUG(dbgs() << "  argument copy elision failed due to bad fixed stack "
8667                     "object size\n");
8668     return;
8669   }
8670   unsigned RequiredAlignment = AI->getAlignment();
8671   if (!RequiredAlignment) {
8672     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8673         AI->getAllocatedType());
8674   }
8675   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8676     DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8677                     "greater than stack argument alignment ("
8678                  << RequiredAlignment << " vs "
8679                  << MFI.getObjectAlignment(FixedIndex) << ")\n");
8680     return;
8681   }
8682 
8683   // Perform the elision. Delete the old stack object and replace its only use
8684   // in the variable info map. Mark the stack object as mutable.
8685   DEBUG({
8686     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8687            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8688            << '\n';
8689   });
8690   MFI.RemoveStackObject(OldIndex);
8691   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8692   AllocaIndex = FixedIndex;
8693   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8694   Chains.push_back(ArgVal.getValue(1));
8695 
8696   // Avoid emitting code for the store implementing the copy.
8697   const StoreInst *SI = ArgCopyIter->second.second;
8698   ElidedArgCopyInstrs.insert(SI);
8699 
8700   // Check for uses of the argument again so that we can avoid exporting ArgVal
8701   // if it is't used by anything other than the store.
8702   for (const Value *U : Arg.users()) {
8703     if (U != SI) {
8704       ArgHasUses = true;
8705       break;
8706     }
8707   }
8708 }
8709 
8710 void SelectionDAGISel::LowerArguments(const Function &F) {
8711   SelectionDAG &DAG = SDB->DAG;
8712   SDLoc dl = SDB->getCurSDLoc();
8713   const DataLayout &DL = DAG.getDataLayout();
8714   SmallVector<ISD::InputArg, 16> Ins;
8715 
8716   if (!FuncInfo->CanLowerReturn) {
8717     // Put in an sret pointer parameter before all the other parameters.
8718     SmallVector<EVT, 1> ValueVTs;
8719     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8720                     F.getReturnType()->getPointerTo(
8721                         DAG.getDataLayout().getAllocaAddrSpace()),
8722                     ValueVTs);
8723 
8724     // NOTE: Assuming that a pointer will never break down to more than one VT
8725     // or one register.
8726     ISD::ArgFlagsTy Flags;
8727     Flags.setSRet();
8728     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8729     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8730                          ISD::InputArg::NoArgIndex, 0);
8731     Ins.push_back(RetArg);
8732   }
8733 
8734   // Look for stores of arguments to static allocas. Mark such arguments with a
8735   // flag to ask the target to give us the memory location of that argument if
8736   // available.
8737   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8738   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8739 
8740   // Set up the incoming argument description vector.
8741   for (const Argument &Arg : F.args()) {
8742     unsigned ArgNo = Arg.getArgNo();
8743     SmallVector<EVT, 4> ValueVTs;
8744     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8745     bool isArgValueUsed = !Arg.use_empty();
8746     unsigned PartBase = 0;
8747     Type *FinalType = Arg.getType();
8748     if (Arg.hasAttribute(Attribute::ByVal))
8749       FinalType = cast<PointerType>(FinalType)->getElementType();
8750     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
8751         FinalType, F.getCallingConv(), F.isVarArg());
8752     for (unsigned Value = 0, NumValues = ValueVTs.size();
8753          Value != NumValues; ++Value) {
8754       EVT VT = ValueVTs[Value];
8755       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8756       ISD::ArgFlagsTy Flags;
8757 
8758       // Certain targets (such as MIPS), may have a different ABI alignment
8759       // for a type depending on the context. Give the target a chance to
8760       // specify the alignment it wants.
8761       unsigned OriginalAlignment =
8762           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
8763 
8764       if (Arg.hasAttribute(Attribute::ZExt))
8765         Flags.setZExt();
8766       if (Arg.hasAttribute(Attribute::SExt))
8767         Flags.setSExt();
8768       if (Arg.hasAttribute(Attribute::InReg)) {
8769         // If we are using vectorcall calling convention, a structure that is
8770         // passed InReg - is surely an HVA
8771         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
8772             isa<StructType>(Arg.getType())) {
8773           // The first value of a structure is marked
8774           if (0 == Value)
8775             Flags.setHvaStart();
8776           Flags.setHva();
8777         }
8778         // Set InReg Flag
8779         Flags.setInReg();
8780       }
8781       if (Arg.hasAttribute(Attribute::StructRet))
8782         Flags.setSRet();
8783       if (Arg.hasAttribute(Attribute::SwiftSelf))
8784         Flags.setSwiftSelf();
8785       if (Arg.hasAttribute(Attribute::SwiftError))
8786         Flags.setSwiftError();
8787       if (Arg.hasAttribute(Attribute::ByVal))
8788         Flags.setByVal();
8789       if (Arg.hasAttribute(Attribute::InAlloca)) {
8790         Flags.setInAlloca();
8791         // Set the byval flag for CCAssignFn callbacks that don't know about
8792         // inalloca.  This way we can know how many bytes we should've allocated
8793         // and how many bytes a callee cleanup function will pop.  If we port
8794         // inalloca to more targets, we'll have to add custom inalloca handling
8795         // in the various CC lowering callbacks.
8796         Flags.setByVal();
8797       }
8798       if (F.getCallingConv() == CallingConv::X86_INTR) {
8799         // IA Interrupt passes frame (1st parameter) by value in the stack.
8800         if (ArgNo == 0)
8801           Flags.setByVal();
8802       }
8803       if (Flags.isByVal() || Flags.isInAlloca()) {
8804         PointerType *Ty = cast<PointerType>(Arg.getType());
8805         Type *ElementTy = Ty->getElementType();
8806         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8807         // For ByVal, alignment should be passed from FE.  BE will guess if
8808         // this info is not there but there are cases it cannot get right.
8809         unsigned FrameAlign;
8810         if (Arg.getParamAlignment())
8811           FrameAlign = Arg.getParamAlignment();
8812         else
8813           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
8814         Flags.setByValAlign(FrameAlign);
8815       }
8816       if (Arg.hasAttribute(Attribute::Nest))
8817         Flags.setNest();
8818       if (NeedsRegBlock)
8819         Flags.setInConsecutiveRegs();
8820       Flags.setOrigAlign(OriginalAlignment);
8821       if (ArgCopyElisionCandidates.count(&Arg))
8822         Flags.setCopyElisionCandidate();
8823 
8824       MVT RegisterVT =
8825           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8826       unsigned NumRegs =
8827           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8828       for (unsigned i = 0; i != NumRegs; ++i) {
8829         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
8830                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
8831         if (NumRegs > 1 && i == 0)
8832           MyFlags.Flags.setSplit();
8833         // if it isn't first piece, alignment must be 1
8834         else if (i > 0) {
8835           MyFlags.Flags.setOrigAlign(1);
8836           if (i == NumRegs - 1)
8837             MyFlags.Flags.setSplitEnd();
8838         }
8839         Ins.push_back(MyFlags);
8840       }
8841       if (NeedsRegBlock && Value == NumValues - 1)
8842         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
8843       PartBase += VT.getStoreSize();
8844     }
8845   }
8846 
8847   // Call the target to set up the argument values.
8848   SmallVector<SDValue, 8> InVals;
8849   SDValue NewRoot = TLI->LowerFormalArguments(
8850       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
8851 
8852   // Verify that the target's LowerFormalArguments behaved as expected.
8853   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
8854          "LowerFormalArguments didn't return a valid chain!");
8855   assert(InVals.size() == Ins.size() &&
8856          "LowerFormalArguments didn't emit the correct number of values!");
8857   DEBUG({
8858       for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
8859         assert(InVals[i].getNode() &&
8860                "LowerFormalArguments emitted a null value!");
8861         assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
8862                "LowerFormalArguments emitted a value with the wrong type!");
8863       }
8864     });
8865 
8866   // Update the DAG with the new chain value resulting from argument lowering.
8867   DAG.setRoot(NewRoot);
8868 
8869   // Set up the argument values.
8870   unsigned i = 0;
8871   if (!FuncInfo->CanLowerReturn) {
8872     // Create a virtual register for the sret pointer, and put in a copy
8873     // from the sret argument into it.
8874     SmallVector<EVT, 1> ValueVTs;
8875     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8876                     F.getReturnType()->getPointerTo(
8877                         DAG.getDataLayout().getAllocaAddrSpace()),
8878                     ValueVTs);
8879     MVT VT = ValueVTs[0].getSimpleVT();
8880     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
8881     Optional<ISD::NodeType> AssertOp = None;
8882     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
8883                                         RegVT, VT, nullptr, AssertOp);
8884 
8885     MachineFunction& MF = SDB->DAG.getMachineFunction();
8886     MachineRegisterInfo& RegInfo = MF.getRegInfo();
8887     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
8888     FuncInfo->DemoteRegister = SRetReg;
8889     NewRoot =
8890         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
8891     DAG.setRoot(NewRoot);
8892 
8893     // i indexes lowered arguments.  Bump it past the hidden sret argument.
8894     ++i;
8895   }
8896 
8897   SmallVector<SDValue, 4> Chains;
8898   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
8899   for (const Argument &Arg : F.args()) {
8900     SmallVector<SDValue, 4> ArgValues;
8901     SmallVector<EVT, 4> ValueVTs;
8902     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
8903     unsigned NumValues = ValueVTs.size();
8904     if (NumValues == 0)
8905       continue;
8906 
8907     bool ArgHasUses = !Arg.use_empty();
8908 
8909     // Elide the copying store if the target loaded this argument from a
8910     // suitable fixed stack object.
8911     if (Ins[i].Flags.isCopyElisionCandidate()) {
8912       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
8913                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
8914                              InVals[i], ArgHasUses);
8915     }
8916 
8917     // If this argument is unused then remember its value. It is used to generate
8918     // debugging information.
8919     bool isSwiftErrorArg =
8920         TLI->supportSwiftError() &&
8921         Arg.hasAttribute(Attribute::SwiftError);
8922     if (!ArgHasUses && !isSwiftErrorArg) {
8923       SDB->setUnusedArgValue(&Arg, InVals[i]);
8924 
8925       // Also remember any frame index for use in FastISel.
8926       if (FrameIndexSDNode *FI =
8927           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
8928         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8929     }
8930 
8931     for (unsigned Val = 0; Val != NumValues; ++Val) {
8932       EVT VT = ValueVTs[Val];
8933       MVT PartVT =
8934           TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT);
8935       unsigned NumParts =
8936           TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT);
8937 
8938       // Even an apparant 'unused' swifterror argument needs to be returned. So
8939       // we do generate a copy for it that can be used on return from the
8940       // function.
8941       if (ArgHasUses || isSwiftErrorArg) {
8942         Optional<ISD::NodeType> AssertOp;
8943         if (Arg.hasAttribute(Attribute::SExt))
8944           AssertOp = ISD::AssertSext;
8945         else if (Arg.hasAttribute(Attribute::ZExt))
8946           AssertOp = ISD::AssertZext;
8947 
8948         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
8949                                              PartVT, VT, nullptr, AssertOp,
8950                                              true));
8951       }
8952 
8953       i += NumParts;
8954     }
8955 
8956     // We don't need to do anything else for unused arguments.
8957     if (ArgValues.empty())
8958       continue;
8959 
8960     // Note down frame index.
8961     if (FrameIndexSDNode *FI =
8962         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
8963       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8964 
8965     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
8966                                      SDB->getCurSDLoc());
8967 
8968     SDB->setValue(&Arg, Res);
8969     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
8970       // We want to associate the argument with the frame index, among
8971       // involved operands, that correspond to the lowest address. The
8972       // getCopyFromParts function, called earlier, is swapping the order of
8973       // the operands to BUILD_PAIR depending on endianness. The result of
8974       // that swapping is that the least significant bits of the argument will
8975       // be in the first operand of the BUILD_PAIR node, and the most
8976       // significant bits will be in the second operand.
8977       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8978       if (LoadSDNode *LNode =
8979           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
8980         if (FrameIndexSDNode *FI =
8981             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
8982           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
8983     }
8984 
8985     // Update the SwiftErrorVRegDefMap.
8986     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
8987       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
8988       if (TargetRegisterInfo::isVirtualRegister(Reg))
8989         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
8990                                            FuncInfo->SwiftErrorArg, Reg);
8991     }
8992 
8993     // If this argument is live outside of the entry block, insert a copy from
8994     // wherever we got it to the vreg that other BB's will reference it as.
8995     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
8996       // If we can, though, try to skip creating an unnecessary vreg.
8997       // FIXME: This isn't very clean... it would be nice to make this more
8998       // general.  It's also subtly incompatible with the hacks FastISel
8999       // uses with vregs.
9000       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9001       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9002         FuncInfo->ValueMap[&Arg] = Reg;
9003         continue;
9004       }
9005     }
9006     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9007       FuncInfo->InitializeRegForValue(&Arg);
9008       SDB->CopyToExportRegsIfNeeded(&Arg);
9009     }
9010   }
9011 
9012   if (!Chains.empty()) {
9013     Chains.push_back(NewRoot);
9014     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9015   }
9016 
9017   DAG.setRoot(NewRoot);
9018 
9019   assert(i == InVals.size() && "Argument register count mismatch!");
9020 
9021   // If any argument copy elisions occurred and we have debug info, update the
9022   // stale frame indices used in the dbg.declare variable info table.
9023   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9024   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9025     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9026       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9027       if (I != ArgCopyElisionFrameIndexMap.end())
9028         VI.Slot = I->second;
9029     }
9030   }
9031 
9032   // Finally, if the target has anything special to do, allow it to do so.
9033   EmitFunctionEntryCode();
9034 }
9035 
9036 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9037 /// ensure constants are generated when needed.  Remember the virtual registers
9038 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9039 /// directly add them, because expansion might result in multiple MBB's for one
9040 /// BB.  As such, the start of the BB might correspond to a different MBB than
9041 /// the end.
9042 void
9043 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9044   const TerminatorInst *TI = LLVMBB->getTerminator();
9045 
9046   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9047 
9048   // Check PHI nodes in successors that expect a value to be available from this
9049   // block.
9050   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9051     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9052     if (!isa<PHINode>(SuccBB->begin())) continue;
9053     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9054 
9055     // If this terminator has multiple identical successors (common for
9056     // switches), only handle each succ once.
9057     if (!SuccsHandled.insert(SuccMBB).second)
9058       continue;
9059 
9060     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9061 
9062     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9063     // nodes and Machine PHI nodes, but the incoming operands have not been
9064     // emitted yet.
9065     for (const PHINode &PN : SuccBB->phis()) {
9066       // Ignore dead phi's.
9067       if (PN.use_empty())
9068         continue;
9069 
9070       // Skip empty types
9071       if (PN.getType()->isEmptyTy())
9072         continue;
9073 
9074       unsigned Reg;
9075       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9076 
9077       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9078         unsigned &RegOut = ConstantsOut[C];
9079         if (RegOut == 0) {
9080           RegOut = FuncInfo.CreateRegs(C->getType());
9081           CopyValueToVirtualRegister(C, RegOut);
9082         }
9083         Reg = RegOut;
9084       } else {
9085         DenseMap<const Value *, unsigned>::iterator I =
9086           FuncInfo.ValueMap.find(PHIOp);
9087         if (I != FuncInfo.ValueMap.end())
9088           Reg = I->second;
9089         else {
9090           assert(isa<AllocaInst>(PHIOp) &&
9091                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9092                  "Didn't codegen value into a register!??");
9093           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9094           CopyValueToVirtualRegister(PHIOp, Reg);
9095         }
9096       }
9097 
9098       // Remember that this register needs to added to the machine PHI node as
9099       // the input for this MBB.
9100       SmallVector<EVT, 4> ValueVTs;
9101       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9102       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9103       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9104         EVT VT = ValueVTs[vti];
9105         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9106         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9107           FuncInfo.PHINodesToUpdate.push_back(
9108               std::make_pair(&*MBBI++, Reg + i));
9109         Reg += NumRegisters;
9110       }
9111     }
9112   }
9113 
9114   ConstantsOut.clear();
9115 }
9116 
9117 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9118 /// is 0.
9119 MachineBasicBlock *
9120 SelectionDAGBuilder::StackProtectorDescriptor::
9121 AddSuccessorMBB(const BasicBlock *BB,
9122                 MachineBasicBlock *ParentMBB,
9123                 bool IsLikely,
9124                 MachineBasicBlock *SuccMBB) {
9125   // If SuccBB has not been created yet, create it.
9126   if (!SuccMBB) {
9127     MachineFunction *MF = ParentMBB->getParent();
9128     MachineFunction::iterator BBI(ParentMBB);
9129     SuccMBB = MF->CreateMachineBasicBlock(BB);
9130     MF->insert(++BBI, SuccMBB);
9131   }
9132   // Add it as a successor of ParentMBB.
9133   ParentMBB->addSuccessor(
9134       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9135   return SuccMBB;
9136 }
9137 
9138 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9139   MachineFunction::iterator I(MBB);
9140   if (++I == FuncInfo.MF->end())
9141     return nullptr;
9142   return &*I;
9143 }
9144 
9145 /// During lowering new call nodes can be created (such as memset, etc.).
9146 /// Those will become new roots of the current DAG, but complications arise
9147 /// when they are tail calls. In such cases, the call lowering will update
9148 /// the root, but the builder still needs to know that a tail call has been
9149 /// lowered in order to avoid generating an additional return.
9150 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9151   // If the node is null, we do have a tail call.
9152   if (MaybeTC.getNode() != nullptr)
9153     DAG.setRoot(MaybeTC);
9154   else
9155     HasTailCall = true;
9156 }
9157 
9158 uint64_t
9159 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9160                                        unsigned First, unsigned Last) const {
9161   assert(Last >= First);
9162   const APInt &LowCase = Clusters[First].Low->getValue();
9163   const APInt &HighCase = Clusters[Last].High->getValue();
9164   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9165 
9166   // FIXME: A range of consecutive cases has 100% density, but only requires one
9167   // comparison to lower. We should discriminate against such consecutive ranges
9168   // in jump tables.
9169 
9170   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9171 }
9172 
9173 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9174     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9175     unsigned Last) const {
9176   assert(Last >= First);
9177   assert(TotalCases[Last] >= TotalCases[First]);
9178   uint64_t NumCases =
9179       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9180   return NumCases;
9181 }
9182 
9183 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9184                                          unsigned First, unsigned Last,
9185                                          const SwitchInst *SI,
9186                                          MachineBasicBlock *DefaultMBB,
9187                                          CaseCluster &JTCluster) {
9188   assert(First <= Last);
9189 
9190   auto Prob = BranchProbability::getZero();
9191   unsigned NumCmps = 0;
9192   std::vector<MachineBasicBlock*> Table;
9193   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9194 
9195   // Initialize probabilities in JTProbs.
9196   for (unsigned I = First; I <= Last; ++I)
9197     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9198 
9199   for (unsigned I = First; I <= Last; ++I) {
9200     assert(Clusters[I].Kind == CC_Range);
9201     Prob += Clusters[I].Prob;
9202     const APInt &Low = Clusters[I].Low->getValue();
9203     const APInt &High = Clusters[I].High->getValue();
9204     NumCmps += (Low == High) ? 1 : 2;
9205     if (I != First) {
9206       // Fill the gap between this and the previous cluster.
9207       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9208       assert(PreviousHigh.slt(Low));
9209       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9210       for (uint64_t J = 0; J < Gap; J++)
9211         Table.push_back(DefaultMBB);
9212     }
9213     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9214     for (uint64_t J = 0; J < ClusterSize; ++J)
9215       Table.push_back(Clusters[I].MBB);
9216     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9217   }
9218 
9219   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9220   unsigned NumDests = JTProbs.size();
9221   if (TLI.isSuitableForBitTests(
9222           NumDests, NumCmps, Clusters[First].Low->getValue(),
9223           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9224     // Clusters[First..Last] should be lowered as bit tests instead.
9225     return false;
9226   }
9227 
9228   // Create the MBB that will load from and jump through the table.
9229   // Note: We create it here, but it's not inserted into the function yet.
9230   MachineFunction *CurMF = FuncInfo.MF;
9231   MachineBasicBlock *JumpTableMBB =
9232       CurMF->CreateMachineBasicBlock(SI->getParent());
9233 
9234   // Add successors. Note: use table order for determinism.
9235   SmallPtrSet<MachineBasicBlock *, 8> Done;
9236   for (MachineBasicBlock *Succ : Table) {
9237     if (Done.count(Succ))
9238       continue;
9239     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9240     Done.insert(Succ);
9241   }
9242   JumpTableMBB->normalizeSuccProbs();
9243 
9244   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9245                      ->createJumpTableIndex(Table);
9246 
9247   // Set up the jump table info.
9248   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9249   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9250                       Clusters[Last].High->getValue(), SI->getCondition(),
9251                       nullptr, false);
9252   JTCases.emplace_back(std::move(JTH), std::move(JT));
9253 
9254   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9255                                      JTCases.size() - 1, Prob);
9256   return true;
9257 }
9258 
9259 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9260                                          const SwitchInst *SI,
9261                                          MachineBasicBlock *DefaultMBB) {
9262 #ifndef NDEBUG
9263   // Clusters must be non-empty, sorted, and only contain Range clusters.
9264   assert(!Clusters.empty());
9265   for (CaseCluster &C : Clusters)
9266     assert(C.Kind == CC_Range);
9267   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9268     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9269 #endif
9270 
9271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9272   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9273     return;
9274 
9275   const int64_t N = Clusters.size();
9276   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9277   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9278 
9279   if (N < 2 || N < MinJumpTableEntries)
9280     return;
9281 
9282   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9283   SmallVector<unsigned, 8> TotalCases(N);
9284   for (unsigned i = 0; i < N; ++i) {
9285     const APInt &Hi = Clusters[i].High->getValue();
9286     const APInt &Lo = Clusters[i].Low->getValue();
9287     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9288     if (i != 0)
9289       TotalCases[i] += TotalCases[i - 1];
9290   }
9291 
9292   // Cheap case: the whole range may be suitable for jump table.
9293   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9294   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9295   assert(NumCases < UINT64_MAX / 100);
9296   assert(Range >= NumCases);
9297   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9298     CaseCluster JTCluster;
9299     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9300       Clusters[0] = JTCluster;
9301       Clusters.resize(1);
9302       return;
9303     }
9304   }
9305 
9306   // The algorithm below is not suitable for -O0.
9307   if (TM.getOptLevel() == CodeGenOpt::None)
9308     return;
9309 
9310   // Split Clusters into minimum number of dense partitions. The algorithm uses
9311   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9312   // for the Case Statement'" (1994), but builds the MinPartitions array in
9313   // reverse order to make it easier to reconstruct the partitions in ascending
9314   // order. In the choice between two optimal partitionings, it picks the one
9315   // which yields more jump tables.
9316 
9317   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9318   SmallVector<unsigned, 8> MinPartitions(N);
9319   // LastElement[i] is the last element of the partition starting at i.
9320   SmallVector<unsigned, 8> LastElement(N);
9321   // PartitionsScore[i] is used to break ties when choosing between two
9322   // partitionings resulting in the same number of partitions.
9323   SmallVector<unsigned, 8> PartitionsScore(N);
9324   // For PartitionsScore, a small number of comparisons is considered as good as
9325   // a jump table and a single comparison is considered better than a jump
9326   // table.
9327   enum PartitionScores : unsigned {
9328     NoTable = 0,
9329     Table = 1,
9330     FewCases = 1,
9331     SingleCase = 2
9332   };
9333 
9334   // Base case: There is only one way to partition Clusters[N-1].
9335   MinPartitions[N - 1] = 1;
9336   LastElement[N - 1] = N - 1;
9337   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9338 
9339   // Note: loop indexes are signed to avoid underflow.
9340   for (int64_t i = N - 2; i >= 0; i--) {
9341     // Find optimal partitioning of Clusters[i..N-1].
9342     // Baseline: Put Clusters[i] into a partition on its own.
9343     MinPartitions[i] = MinPartitions[i + 1] + 1;
9344     LastElement[i] = i;
9345     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9346 
9347     // Search for a solution that results in fewer partitions.
9348     for (int64_t j = N - 1; j > i; j--) {
9349       // Try building a partition from Clusters[i..j].
9350       uint64_t Range = getJumpTableRange(Clusters, i, j);
9351       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9352       assert(NumCases < UINT64_MAX / 100);
9353       assert(Range >= NumCases);
9354       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9355         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9356         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9357         int64_t NumEntries = j - i + 1;
9358 
9359         if (NumEntries == 1)
9360           Score += PartitionScores::SingleCase;
9361         else if (NumEntries <= SmallNumberOfEntries)
9362           Score += PartitionScores::FewCases;
9363         else if (NumEntries >= MinJumpTableEntries)
9364           Score += PartitionScores::Table;
9365 
9366         // If this leads to fewer partitions, or to the same number of
9367         // partitions with better score, it is a better partitioning.
9368         if (NumPartitions < MinPartitions[i] ||
9369             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9370           MinPartitions[i] = NumPartitions;
9371           LastElement[i] = j;
9372           PartitionsScore[i] = Score;
9373         }
9374       }
9375     }
9376   }
9377 
9378   // Iterate over the partitions, replacing some with jump tables in-place.
9379   unsigned DstIndex = 0;
9380   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9381     Last = LastElement[First];
9382     assert(Last >= First);
9383     assert(DstIndex <= First);
9384     unsigned NumClusters = Last - First + 1;
9385 
9386     CaseCluster JTCluster;
9387     if (NumClusters >= MinJumpTableEntries &&
9388         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9389       Clusters[DstIndex++] = JTCluster;
9390     } else {
9391       for (unsigned I = First; I <= Last; ++I)
9392         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9393     }
9394   }
9395   Clusters.resize(DstIndex);
9396 }
9397 
9398 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9399                                         unsigned First, unsigned Last,
9400                                         const SwitchInst *SI,
9401                                         CaseCluster &BTCluster) {
9402   assert(First <= Last);
9403   if (First == Last)
9404     return false;
9405 
9406   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9407   unsigned NumCmps = 0;
9408   for (int64_t I = First; I <= Last; ++I) {
9409     assert(Clusters[I].Kind == CC_Range);
9410     Dests.set(Clusters[I].MBB->getNumber());
9411     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9412   }
9413   unsigned NumDests = Dests.count();
9414 
9415   APInt Low = Clusters[First].Low->getValue();
9416   APInt High = Clusters[Last].High->getValue();
9417   assert(Low.slt(High));
9418 
9419   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9420   const DataLayout &DL = DAG.getDataLayout();
9421   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9422     return false;
9423 
9424   APInt LowBound;
9425   APInt CmpRange;
9426 
9427   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9428   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9429          "Case range must fit in bit mask!");
9430 
9431   // Check if the clusters cover a contiguous range such that no value in the
9432   // range will jump to the default statement.
9433   bool ContiguousRange = true;
9434   for (int64_t I = First + 1; I <= Last; ++I) {
9435     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9436       ContiguousRange = false;
9437       break;
9438     }
9439   }
9440 
9441   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9442     // Optimize the case where all the case values fit in a word without having
9443     // to subtract minValue. In this case, we can optimize away the subtraction.
9444     LowBound = APInt::getNullValue(Low.getBitWidth());
9445     CmpRange = High;
9446     ContiguousRange = false;
9447   } else {
9448     LowBound = Low;
9449     CmpRange = High - Low;
9450   }
9451 
9452   CaseBitsVector CBV;
9453   auto TotalProb = BranchProbability::getZero();
9454   for (unsigned i = First; i <= Last; ++i) {
9455     // Find the CaseBits for this destination.
9456     unsigned j;
9457     for (j = 0; j < CBV.size(); ++j)
9458       if (CBV[j].BB == Clusters[i].MBB)
9459         break;
9460     if (j == CBV.size())
9461       CBV.push_back(
9462           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9463     CaseBits *CB = &CBV[j];
9464 
9465     // Update Mask, Bits and ExtraProb.
9466     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9467     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9468     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9469     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9470     CB->Bits += Hi - Lo + 1;
9471     CB->ExtraProb += Clusters[i].Prob;
9472     TotalProb += Clusters[i].Prob;
9473   }
9474 
9475   BitTestInfo BTI;
9476   std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
9477     // Sort by probability first, number of bits second, bit mask third.
9478     if (a.ExtraProb != b.ExtraProb)
9479       return a.ExtraProb > b.ExtraProb;
9480     if (a.Bits != b.Bits)
9481       return a.Bits > b.Bits;
9482     return a.Mask < b.Mask;
9483   });
9484 
9485   for (auto &CB : CBV) {
9486     MachineBasicBlock *BitTestBB =
9487         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9488     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9489   }
9490   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9491                             SI->getCondition(), -1U, MVT::Other, false,
9492                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9493                             TotalProb);
9494 
9495   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9496                                     BitTestCases.size() - 1, TotalProb);
9497   return true;
9498 }
9499 
9500 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9501                                               const SwitchInst *SI) {
9502 // Partition Clusters into as few subsets as possible, where each subset has a
9503 // range that fits in a machine word and has <= 3 unique destinations.
9504 
9505 #ifndef NDEBUG
9506   // Clusters must be sorted and contain Range or JumpTable clusters.
9507   assert(!Clusters.empty());
9508   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9509   for (const CaseCluster &C : Clusters)
9510     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9511   for (unsigned i = 1; i < Clusters.size(); ++i)
9512     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9513 #endif
9514 
9515   // The algorithm below is not suitable for -O0.
9516   if (TM.getOptLevel() == CodeGenOpt::None)
9517     return;
9518 
9519   // If target does not have legal shift left, do not emit bit tests at all.
9520   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9521   const DataLayout &DL = DAG.getDataLayout();
9522 
9523   EVT PTy = TLI.getPointerTy(DL);
9524   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9525     return;
9526 
9527   int BitWidth = PTy.getSizeInBits();
9528   const int64_t N = Clusters.size();
9529 
9530   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9531   SmallVector<unsigned, 8> MinPartitions(N);
9532   // LastElement[i] is the last element of the partition starting at i.
9533   SmallVector<unsigned, 8> LastElement(N);
9534 
9535   // FIXME: This might not be the best algorithm for finding bit test clusters.
9536 
9537   // Base case: There is only one way to partition Clusters[N-1].
9538   MinPartitions[N - 1] = 1;
9539   LastElement[N - 1] = N - 1;
9540 
9541   // Note: loop indexes are signed to avoid underflow.
9542   for (int64_t i = N - 2; i >= 0; --i) {
9543     // Find optimal partitioning of Clusters[i..N-1].
9544     // Baseline: Put Clusters[i] into a partition on its own.
9545     MinPartitions[i] = MinPartitions[i + 1] + 1;
9546     LastElement[i] = i;
9547 
9548     // Search for a solution that results in fewer partitions.
9549     // Note: the search is limited by BitWidth, reducing time complexity.
9550     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9551       // Try building a partition from Clusters[i..j].
9552 
9553       // Check the range.
9554       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9555                                Clusters[j].High->getValue(), DL))
9556         continue;
9557 
9558       // Check nbr of destinations and cluster types.
9559       // FIXME: This works, but doesn't seem very efficient.
9560       bool RangesOnly = true;
9561       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9562       for (int64_t k = i; k <= j; k++) {
9563         if (Clusters[k].Kind != CC_Range) {
9564           RangesOnly = false;
9565           break;
9566         }
9567         Dests.set(Clusters[k].MBB->getNumber());
9568       }
9569       if (!RangesOnly || Dests.count() > 3)
9570         break;
9571 
9572       // Check if it's a better partition.
9573       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9574       if (NumPartitions < MinPartitions[i]) {
9575         // Found a better partition.
9576         MinPartitions[i] = NumPartitions;
9577         LastElement[i] = j;
9578       }
9579     }
9580   }
9581 
9582   // Iterate over the partitions, replacing with bit-test clusters in-place.
9583   unsigned DstIndex = 0;
9584   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9585     Last = LastElement[First];
9586     assert(First <= Last);
9587     assert(DstIndex <= First);
9588 
9589     CaseCluster BitTestCluster;
9590     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9591       Clusters[DstIndex++] = BitTestCluster;
9592     } else {
9593       size_t NumClusters = Last - First + 1;
9594       std::memmove(&Clusters[DstIndex], &Clusters[First],
9595                    sizeof(Clusters[0]) * NumClusters);
9596       DstIndex += NumClusters;
9597     }
9598   }
9599   Clusters.resize(DstIndex);
9600 }
9601 
9602 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9603                                         MachineBasicBlock *SwitchMBB,
9604                                         MachineBasicBlock *DefaultMBB) {
9605   MachineFunction *CurMF = FuncInfo.MF;
9606   MachineBasicBlock *NextMBB = nullptr;
9607   MachineFunction::iterator BBI(W.MBB);
9608   if (++BBI != FuncInfo.MF->end())
9609     NextMBB = &*BBI;
9610 
9611   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9612 
9613   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9614 
9615   if (Size == 2 && W.MBB == SwitchMBB) {
9616     // If any two of the cases has the same destination, and if one value
9617     // is the same as the other, but has one bit unset that the other has set,
9618     // use bit manipulation to do two compares at once.  For example:
9619     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9620     // TODO: This could be extended to merge any 2 cases in switches with 3
9621     // cases.
9622     // TODO: Handle cases where W.CaseBB != SwitchBB.
9623     CaseCluster &Small = *W.FirstCluster;
9624     CaseCluster &Big = *W.LastCluster;
9625 
9626     if (Small.Low == Small.High && Big.Low == Big.High &&
9627         Small.MBB == Big.MBB) {
9628       const APInt &SmallValue = Small.Low->getValue();
9629       const APInt &BigValue = Big.Low->getValue();
9630 
9631       // Check that there is only one bit different.
9632       APInt CommonBit = BigValue ^ SmallValue;
9633       if (CommonBit.isPowerOf2()) {
9634         SDValue CondLHS = getValue(Cond);
9635         EVT VT = CondLHS.getValueType();
9636         SDLoc DL = getCurSDLoc();
9637 
9638         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9639                                  DAG.getConstant(CommonBit, DL, VT));
9640         SDValue Cond = DAG.getSetCC(
9641             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9642             ISD::SETEQ);
9643 
9644         // Update successor info.
9645         // Both Small and Big will jump to Small.BB, so we sum up the
9646         // probabilities.
9647         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9648         if (BPI)
9649           addSuccessorWithProb(
9650               SwitchMBB, DefaultMBB,
9651               // The default destination is the first successor in IR.
9652               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9653         else
9654           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9655 
9656         // Insert the true branch.
9657         SDValue BrCond =
9658             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9659                         DAG.getBasicBlock(Small.MBB));
9660         // Insert the false branch.
9661         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9662                              DAG.getBasicBlock(DefaultMBB));
9663 
9664         DAG.setRoot(BrCond);
9665         return;
9666       }
9667     }
9668   }
9669 
9670   if (TM.getOptLevel() != CodeGenOpt::None) {
9671     // Here, we order cases by probability so the most likely case will be
9672     // checked first. However, two clusters can have the same probability in
9673     // which case their relative ordering is non-deterministic. So we use Low
9674     // as a tie-breaker as clusters are guaranteed to never overlap.
9675     std::sort(W.FirstCluster, W.LastCluster + 1,
9676               [](const CaseCluster &a, const CaseCluster &b) {
9677       return a.Prob != b.Prob ?
9678              a.Prob > b.Prob :
9679              a.Low->getValue().slt(b.Low->getValue());
9680     });
9681 
9682     // Rearrange the case blocks so that the last one falls through if possible
9683     // without without changing the order of probabilities.
9684     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9685       --I;
9686       if (I->Prob > W.LastCluster->Prob)
9687         break;
9688       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9689         std::swap(*I, *W.LastCluster);
9690         break;
9691       }
9692     }
9693   }
9694 
9695   // Compute total probability.
9696   BranchProbability DefaultProb = W.DefaultProb;
9697   BranchProbability UnhandledProbs = DefaultProb;
9698   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9699     UnhandledProbs += I->Prob;
9700 
9701   MachineBasicBlock *CurMBB = W.MBB;
9702   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9703     MachineBasicBlock *Fallthrough;
9704     if (I == W.LastCluster) {
9705       // For the last cluster, fall through to the default destination.
9706       Fallthrough = DefaultMBB;
9707     } else {
9708       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9709       CurMF->insert(BBI, Fallthrough);
9710       // Put Cond in a virtual register to make it available from the new blocks.
9711       ExportFromCurrentBlock(Cond);
9712     }
9713     UnhandledProbs -= I->Prob;
9714 
9715     switch (I->Kind) {
9716       case CC_JumpTable: {
9717         // FIXME: Optimize away range check based on pivot comparisons.
9718         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9719         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9720 
9721         // The jump block hasn't been inserted yet; insert it here.
9722         MachineBasicBlock *JumpMBB = JT->MBB;
9723         CurMF->insert(BBI, JumpMBB);
9724 
9725         auto JumpProb = I->Prob;
9726         auto FallthroughProb = UnhandledProbs;
9727 
9728         // If the default statement is a target of the jump table, we evenly
9729         // distribute the default probability to successors of CurMBB. Also
9730         // update the probability on the edge from JumpMBB to Fallthrough.
9731         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9732                                               SE = JumpMBB->succ_end();
9733              SI != SE; ++SI) {
9734           if (*SI == DefaultMBB) {
9735             JumpProb += DefaultProb / 2;
9736             FallthroughProb -= DefaultProb / 2;
9737             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9738             JumpMBB->normalizeSuccProbs();
9739             break;
9740           }
9741         }
9742 
9743         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
9744         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
9745         CurMBB->normalizeSuccProbs();
9746 
9747         // The jump table header will be inserted in our current block, do the
9748         // range check, and fall through to our fallthrough block.
9749         JTH->HeaderBB = CurMBB;
9750         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
9751 
9752         // If we're in the right place, emit the jump table header right now.
9753         if (CurMBB == SwitchMBB) {
9754           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
9755           JTH->Emitted = true;
9756         }
9757         break;
9758       }
9759       case CC_BitTests: {
9760         // FIXME: Optimize away range check based on pivot comparisons.
9761         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
9762 
9763         // The bit test blocks haven't been inserted yet; insert them here.
9764         for (BitTestCase &BTC : BTB->Cases)
9765           CurMF->insert(BBI, BTC.ThisBB);
9766 
9767         // Fill in fields of the BitTestBlock.
9768         BTB->Parent = CurMBB;
9769         BTB->Default = Fallthrough;
9770 
9771         BTB->DefaultProb = UnhandledProbs;
9772         // If the cases in bit test don't form a contiguous range, we evenly
9773         // distribute the probability on the edge to Fallthrough to two
9774         // successors of CurMBB.
9775         if (!BTB->ContiguousRange) {
9776           BTB->Prob += DefaultProb / 2;
9777           BTB->DefaultProb -= DefaultProb / 2;
9778         }
9779 
9780         // If we're in the right place, emit the bit test header right now.
9781         if (CurMBB == SwitchMBB) {
9782           visitBitTestHeader(*BTB, SwitchMBB);
9783           BTB->Emitted = true;
9784         }
9785         break;
9786       }
9787       case CC_Range: {
9788         const Value *RHS, *LHS, *MHS;
9789         ISD::CondCode CC;
9790         if (I->Low == I->High) {
9791           // Check Cond == I->Low.
9792           CC = ISD::SETEQ;
9793           LHS = Cond;
9794           RHS=I->Low;
9795           MHS = nullptr;
9796         } else {
9797           // Check I->Low <= Cond <= I->High.
9798           CC = ISD::SETLE;
9799           LHS = I->Low;
9800           MHS = Cond;
9801           RHS = I->High;
9802         }
9803 
9804         // The false probability is the sum of all unhandled cases.
9805         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
9806                      getCurSDLoc(), I->Prob, UnhandledProbs);
9807 
9808         if (CurMBB == SwitchMBB)
9809           visitSwitchCase(CB, SwitchMBB);
9810         else
9811           SwitchCases.push_back(CB);
9812 
9813         break;
9814       }
9815     }
9816     CurMBB = Fallthrough;
9817   }
9818 }
9819 
9820 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
9821                                               CaseClusterIt First,
9822                                               CaseClusterIt Last) {
9823   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
9824     if (X.Prob != CC.Prob)
9825       return X.Prob > CC.Prob;
9826 
9827     // Ties are broken by comparing the case value.
9828     return X.Low->getValue().slt(CC.Low->getValue());
9829   });
9830 }
9831 
9832 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
9833                                         const SwitchWorkListItem &W,
9834                                         Value *Cond,
9835                                         MachineBasicBlock *SwitchMBB) {
9836   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
9837          "Clusters not sorted?");
9838 
9839   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
9840 
9841   // Balance the tree based on branch probabilities to create a near-optimal (in
9842   // terms of search time given key frequency) binary search tree. See e.g. Kurt
9843   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
9844   CaseClusterIt LastLeft = W.FirstCluster;
9845   CaseClusterIt FirstRight = W.LastCluster;
9846   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
9847   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
9848 
9849   // Move LastLeft and FirstRight towards each other from opposite directions to
9850   // find a partitioning of the clusters which balances the probability on both
9851   // sides. If LeftProb and RightProb are equal, alternate which side is
9852   // taken to ensure 0-probability nodes are distributed evenly.
9853   unsigned I = 0;
9854   while (LastLeft + 1 < FirstRight) {
9855     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
9856       LeftProb += (++LastLeft)->Prob;
9857     else
9858       RightProb += (--FirstRight)->Prob;
9859     I++;
9860   }
9861 
9862   while (true) {
9863     // Our binary search tree differs from a typical BST in that ours can have up
9864     // to three values in each leaf. The pivot selection above doesn't take that
9865     // into account, which means the tree might require more nodes and be less
9866     // efficient. We compensate for this here.
9867 
9868     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
9869     unsigned NumRight = W.LastCluster - FirstRight + 1;
9870 
9871     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
9872       // If one side has less than 3 clusters, and the other has more than 3,
9873       // consider taking a cluster from the other side.
9874 
9875       if (NumLeft < NumRight) {
9876         // Consider moving the first cluster on the right to the left side.
9877         CaseCluster &CC = *FirstRight;
9878         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9879         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9880         if (LeftSideRank <= RightSideRank) {
9881           // Moving the cluster to the left does not demote it.
9882           ++LastLeft;
9883           ++FirstRight;
9884           continue;
9885         }
9886       } else {
9887         assert(NumRight < NumLeft);
9888         // Consider moving the last element on the left to the right side.
9889         CaseCluster &CC = *LastLeft;
9890         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
9891         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
9892         if (RightSideRank <= LeftSideRank) {
9893           // Moving the cluster to the right does not demot it.
9894           --LastLeft;
9895           --FirstRight;
9896           continue;
9897         }
9898       }
9899     }
9900     break;
9901   }
9902 
9903   assert(LastLeft + 1 == FirstRight);
9904   assert(LastLeft >= W.FirstCluster);
9905   assert(FirstRight <= W.LastCluster);
9906 
9907   // Use the first element on the right as pivot since we will make less-than
9908   // comparisons against it.
9909   CaseClusterIt PivotCluster = FirstRight;
9910   assert(PivotCluster > W.FirstCluster);
9911   assert(PivotCluster <= W.LastCluster);
9912 
9913   CaseClusterIt FirstLeft = W.FirstCluster;
9914   CaseClusterIt LastRight = W.LastCluster;
9915 
9916   const ConstantInt *Pivot = PivotCluster->Low;
9917 
9918   // New blocks will be inserted immediately after the current one.
9919   MachineFunction::iterator BBI(W.MBB);
9920   ++BBI;
9921 
9922   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
9923   // we can branch to its destination directly if it's squeezed exactly in
9924   // between the known lower bound and Pivot - 1.
9925   MachineBasicBlock *LeftMBB;
9926   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
9927       FirstLeft->Low == W.GE &&
9928       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
9929     LeftMBB = FirstLeft->MBB;
9930   } else {
9931     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9932     FuncInfo.MF->insert(BBI, LeftMBB);
9933     WorkList.push_back(
9934         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
9935     // Put Cond in a virtual register to make it available from the new blocks.
9936     ExportFromCurrentBlock(Cond);
9937   }
9938 
9939   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
9940   // single cluster, RHS.Low == Pivot, and we can branch to its destination
9941   // directly if RHS.High equals the current upper bound.
9942   MachineBasicBlock *RightMBB;
9943   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
9944       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
9945     RightMBB = FirstRight->MBB;
9946   } else {
9947     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
9948     FuncInfo.MF->insert(BBI, RightMBB);
9949     WorkList.push_back(
9950         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
9951     // Put Cond in a virtual register to make it available from the new blocks.
9952     ExportFromCurrentBlock(Cond);
9953   }
9954 
9955   // Create the CaseBlock record that will be used to lower the branch.
9956   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
9957                getCurSDLoc(), LeftProb, RightProb);
9958 
9959   if (W.MBB == SwitchMBB)
9960     visitSwitchCase(CB, SwitchMBB);
9961   else
9962     SwitchCases.push_back(CB);
9963 }
9964 
9965 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
9966 // from the swith statement.
9967 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
9968                                             BranchProbability PeeledCaseProb) {
9969   if (PeeledCaseProb == BranchProbability::getOne())
9970     return BranchProbability::getZero();
9971   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
9972 
9973   uint32_t Numerator = CaseProb.getNumerator();
9974   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
9975   return BranchProbability(Numerator, std::max(Numerator, Denominator));
9976 }
9977 
9978 // Try to peel the top probability case if it exceeds the threshold.
9979 // Return current MachineBasicBlock for the switch statement if the peeling
9980 // does not occur.
9981 // If the peeling is performed, return the newly created MachineBasicBlock
9982 // for the peeled switch statement. Also update Clusters to remove the peeled
9983 // case. PeeledCaseProb is the BranchProbability for the peeled case.
9984 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
9985     const SwitchInst &SI, CaseClusterVector &Clusters,
9986     BranchProbability &PeeledCaseProb) {
9987   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
9988   // Don't perform if there is only one cluster or optimizing for size.
9989   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
9990       TM.getOptLevel() == CodeGenOpt::None ||
9991       SwitchMBB->getParent()->getFunction().optForMinSize())
9992     return SwitchMBB;
9993 
9994   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
9995   unsigned PeeledCaseIndex = 0;
9996   bool SwitchPeeled = false;
9997   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
9998     CaseCluster &CC = Clusters[Index];
9999     if (CC.Prob < TopCaseProb)
10000       continue;
10001     TopCaseProb = CC.Prob;
10002     PeeledCaseIndex = Index;
10003     SwitchPeeled = true;
10004   }
10005   if (!SwitchPeeled)
10006     return SwitchMBB;
10007 
10008   DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " << TopCaseProb
10009                << "\n");
10010 
10011   // Record the MBB for the peeled switch statement.
10012   MachineFunction::iterator BBI(SwitchMBB);
10013   ++BBI;
10014   MachineBasicBlock *PeeledSwitchMBB =
10015       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10016   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10017 
10018   ExportFromCurrentBlock(SI.getCondition());
10019   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10020   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10021                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10022   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10023 
10024   Clusters.erase(PeeledCaseIt);
10025   for (CaseCluster &CC : Clusters) {
10026     DEBUG(dbgs() << "Scale the probablity for one cluster, before scaling: "
10027                  << CC.Prob << "\n");
10028     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10029     DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10030   }
10031   PeeledCaseProb = TopCaseProb;
10032   return PeeledSwitchMBB;
10033 }
10034 
10035 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10036   // Extract cases from the switch.
10037   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10038   CaseClusterVector Clusters;
10039   Clusters.reserve(SI.getNumCases());
10040   for (auto I : SI.cases()) {
10041     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10042     const ConstantInt *CaseVal = I.getCaseValue();
10043     BranchProbability Prob =
10044         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10045             : BranchProbability(1, SI.getNumCases() + 1);
10046     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10047   }
10048 
10049   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10050 
10051   // Cluster adjacent cases with the same destination. We do this at all
10052   // optimization levels because it's cheap to do and will make codegen faster
10053   // if there are many clusters.
10054   sortAndRangeify(Clusters);
10055 
10056   if (TM.getOptLevel() != CodeGenOpt::None) {
10057     // Replace an unreachable default with the most popular destination.
10058     // FIXME: Exploit unreachable default more aggressively.
10059     bool UnreachableDefault =
10060         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10061     if (UnreachableDefault && !Clusters.empty()) {
10062       DenseMap<const BasicBlock *, unsigned> Popularity;
10063       unsigned MaxPop = 0;
10064       const BasicBlock *MaxBB = nullptr;
10065       for (auto I : SI.cases()) {
10066         const BasicBlock *BB = I.getCaseSuccessor();
10067         if (++Popularity[BB] > MaxPop) {
10068           MaxPop = Popularity[BB];
10069           MaxBB = BB;
10070         }
10071       }
10072       // Set new default.
10073       assert(MaxPop > 0 && MaxBB);
10074       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10075 
10076       // Remove cases that were pointing to the destination that is now the
10077       // default.
10078       CaseClusterVector New;
10079       New.reserve(Clusters.size());
10080       for (CaseCluster &CC : Clusters) {
10081         if (CC.MBB != DefaultMBB)
10082           New.push_back(CC);
10083       }
10084       Clusters = std::move(New);
10085     }
10086   }
10087 
10088   // The branch probablity of the peeled case.
10089   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10090   MachineBasicBlock *PeeledSwitchMBB =
10091       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10092 
10093   // If there is only the default destination, jump there directly.
10094   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10095   if (Clusters.empty()) {
10096     assert(PeeledSwitchMBB == SwitchMBB);
10097     SwitchMBB->addSuccessor(DefaultMBB);
10098     if (DefaultMBB != NextBlock(SwitchMBB)) {
10099       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10100                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10101     }
10102     return;
10103   }
10104 
10105   findJumpTables(Clusters, &SI, DefaultMBB);
10106   findBitTestClusters(Clusters, &SI);
10107 
10108   DEBUG({
10109     dbgs() << "Case clusters: ";
10110     for (const CaseCluster &C : Clusters) {
10111       if (C.Kind == CC_JumpTable) dbgs() << "JT:";
10112       if (C.Kind == CC_BitTests) dbgs() << "BT:";
10113 
10114       C.Low->getValue().print(dbgs(), true);
10115       if (C.Low != C.High) {
10116         dbgs() << '-';
10117         C.High->getValue().print(dbgs(), true);
10118       }
10119       dbgs() << ' ';
10120     }
10121     dbgs() << '\n';
10122   });
10123 
10124   assert(!Clusters.empty());
10125   SwitchWorkList WorkList;
10126   CaseClusterIt First = Clusters.begin();
10127   CaseClusterIt Last = Clusters.end() - 1;
10128   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10129   // Scale the branchprobability for DefaultMBB if the peel occurs and
10130   // DefaultMBB is not replaced.
10131   if (PeeledCaseProb != BranchProbability::getZero() &&
10132       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10133     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10134   WorkList.push_back(
10135       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10136 
10137   while (!WorkList.empty()) {
10138     SwitchWorkListItem W = WorkList.back();
10139     WorkList.pop_back();
10140     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10141 
10142     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10143         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10144       // For optimized builds, lower large range as a balanced binary tree.
10145       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10146       continue;
10147     }
10148 
10149     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10150   }
10151 }
10152