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