xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 4954c664307d56c5aa7ed400b3bac730bd71ddb9)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Analysis/VectorUtils.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/FunctionLoweringInfo.h"
41 #include "llvm/CodeGen/GCMetadata.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineJumpTableInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/RuntimeLibcalls.h"
54 #include "llvm/CodeGen/SelectionDAG.h"
55 #include "llvm/CodeGen/SelectionDAGNodes.h"
56 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
57 #include "llvm/CodeGen/StackMaps.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/PatternMatch.h"
92 #include "llvm/IR/Statepoint.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/User.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/MC/MCContext.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/Support/AtomicOrdering.h"
99 #include "llvm/Support/BranchProbability.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CodeGen.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/MachineValueType.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include "llvm/Target/TargetIntrinsicInfo.h"
110 #include "llvm/Target/TargetMachine.h"
111 #include "llvm/Target/TargetOptions.h"
112 #include <algorithm>
113 #include <cassert>
114 #include <cstddef>
115 #include <cstdint>
116 #include <cstring>
117 #include <iterator>
118 #include <limits>
119 #include <numeric>
120 #include <tuple>
121 #include <utility>
122 #include <vector>
123 
124 using namespace llvm;
125 using namespace PatternMatch;
126 
127 #define DEBUG_TYPE "isel"
128 
129 /// LimitFloatPrecision - Generate low-precision inline sequences for
130 /// some float libcalls (6, 8 or 12 bits).
131 static unsigned LimitFloatPrecision;
132 
133 static cl::opt<unsigned, true>
134     LimitFPPrecision("limit-float-precision",
135                      cl::desc("Generate low-precision inline sequences "
136                               "for some float libcalls"),
137                      cl::location(LimitFloatPrecision), cl::Hidden,
138                      cl::init(0));
139 
140 static cl::opt<unsigned> SwitchPeelThreshold(
141     "switch-peel-threshold", cl::Hidden, cl::init(66),
142     cl::desc("Set the case probability threshold for peeling the case from a "
143              "switch statement. A value greater than 100 will void this "
144              "optimization"));
145 
146 // Limit the width of DAG chains. This is important in general to prevent
147 // DAG-based analysis from blowing up. For example, alias analysis and
148 // load clustering may not complete in reasonable time. It is difficult to
149 // recognize and avoid this situation within each individual analysis, and
150 // future analyses are likely to have the same behavior. Limiting DAG width is
151 // the safe approach and will be especially important with global DAGs.
152 //
153 // MaxParallelChains default is arbitrarily high to avoid affecting
154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
155 // sequence over this should have been converted to llvm.memcpy by the
156 // frontend. It is easy to induce this behavior with .ll code such as:
157 // %buffer = alloca [4096 x i8]
158 // %data = load [4096 x i8]* %argPtr
159 // store [4096 x i8] %data, [4096 x i8]* %buffer
160 static const unsigned MaxParallelChains = 64;
161 
162 // Return the calling convention if the Value passed requires ABI mangling as it
163 // is a parameter to a function or a return value from a function which is not
164 // an intrinsic.
165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
166   if (auto *R = dyn_cast<ReturnInst>(V))
167     return R->getParent()->getParent()->getCallingConv();
168 
169   if (auto *CI = dyn_cast<CallInst>(V)) {
170     const bool IsInlineAsm = CI->isInlineAsm();
171     const bool IsIndirectFunctionCall =
172         !IsInlineAsm && !CI->getCalledFunction();
173 
174     // It is possible that the call instruction is an inline asm statement or an
175     // indirect function call in which case the return value of
176     // getCalledFunction() would be nullptr.
177     const bool IsInstrinsicCall =
178         !IsInlineAsm && !IsIndirectFunctionCall &&
179         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
180 
181     if (!IsInlineAsm && !IsInstrinsicCall)
182       return CI->getCallingConv();
183   }
184 
185   return None;
186 }
187 
188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
189                                       const SDValue *Parts, unsigned NumParts,
190                                       MVT PartVT, EVT ValueVT, const Value *V,
191                                       Optional<CallingConv::ID> CC);
192 
193 /// getCopyFromParts - Create a value that contains the specified legal parts
194 /// combined into the value they represent.  If the parts combine to a type
195 /// larger than ValueVT then AssertOp can be used to specify whether the extra
196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
197 /// (ISD::AssertSext).
198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
199                                 const SDValue *Parts, unsigned NumParts,
200                                 MVT PartVT, EVT ValueVT, const Value *V,
201                                 Optional<CallingConv::ID> CC = None,
202                                 Optional<ISD::NodeType> AssertOp = None) {
203   if (ValueVT.isVector())
204     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
205                                   CC);
206 
207   assert(NumParts > 0 && "No parts to assemble!");
208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
209   SDValue Val = Parts[0];
210 
211   if (NumParts > 1) {
212     // Assemble the value from multiple parts.
213     if (ValueVT.isInteger()) {
214       unsigned PartBits = PartVT.getSizeInBits();
215       unsigned ValueBits = ValueVT.getSizeInBits();
216 
217       // Assemble the power of 2 part.
218       unsigned RoundParts = NumParts & (NumParts - 1) ?
219         1 << Log2_32(NumParts) : NumParts;
220       unsigned RoundBits = PartBits * RoundParts;
221       EVT RoundVT = RoundBits == ValueBits ?
222         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
223       SDValue Lo, Hi;
224 
225       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
226 
227       if (RoundParts > 2) {
228         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
229                               PartVT, HalfVT, V);
230         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
231                               RoundParts / 2, PartVT, HalfVT, V);
232       } else {
233         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
234         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
235       }
236 
237       if (DAG.getDataLayout().isBigEndian())
238         std::swap(Lo, Hi);
239 
240       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
241 
242       if (RoundParts < NumParts) {
243         // Assemble the trailing non-power-of-2 part.
244         unsigned OddParts = NumParts - RoundParts;
245         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
246         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
247                               OddVT, V, CC);
248 
249         // Combine the round and odd parts.
250         Lo = Val;
251         if (DAG.getDataLayout().isBigEndian())
252           std::swap(Lo, Hi);
253         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
254         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
255         Hi =
256             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
257                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
258                                         TLI.getPointerTy(DAG.getDataLayout())));
259         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
260         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
261       }
262     } else if (PartVT.isFloatingPoint()) {
263       // FP split into multiple FP parts (for ppcf128)
264       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
265              "Unexpected split");
266       SDValue Lo, Hi;
267       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
268       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
269       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
270         std::swap(Lo, Hi);
271       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
272     } else {
273       // FP split into integer parts (soft fp)
274       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
275              !PartVT.isVector() && "Unexpected split");
276       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
277       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
278     }
279   }
280 
281   // There is now one part, held in Val.  Correct it to match ValueVT.
282   // PartEVT is the type of the register class that holds the value.
283   // ValueVT is the type of the inline asm operation.
284   EVT PartEVT = Val.getValueType();
285 
286   if (PartEVT == ValueVT)
287     return Val;
288 
289   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
290       ValueVT.bitsLT(PartEVT)) {
291     // For an FP value in an integer part, we need to truncate to the right
292     // width first.
293     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
294     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
295   }
296 
297   // Handle types that have the same size.
298   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
299     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
300 
301   // Handle types with different sizes.
302   if (PartEVT.isInteger() && ValueVT.isInteger()) {
303     if (ValueVT.bitsLT(PartEVT)) {
304       // For a truncate, see if we have any information to
305       // indicate whether the truncated bits will always be
306       // zero or sign-extension.
307       if (AssertOp.hasValue())
308         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
309                           DAG.getValueType(ValueVT));
310       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
311     }
312     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
313   }
314 
315   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
316     // FP_ROUND's are always exact here.
317     if (ValueVT.bitsLT(Val.getValueType()))
318       return DAG.getNode(
319           ISD::FP_ROUND, DL, ValueVT, Val,
320           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
321 
322     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
323   }
324 
325   llvm_unreachable("Unknown mismatch!");
326 }
327 
328 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
329                                               const Twine &ErrMsg) {
330   const Instruction *I = dyn_cast_or_null<Instruction>(V);
331   if (!V)
332     return Ctx.emitError(ErrMsg);
333 
334   const char *AsmError = ", possible invalid constraint for vector type";
335   if (const CallInst *CI = dyn_cast<CallInst>(I))
336     if (isa<InlineAsm>(CI->getCalledValue()))
337       return Ctx.emitError(I, ErrMsg + AsmError);
338 
339   return Ctx.emitError(I, ErrMsg);
340 }
341 
342 /// getCopyFromPartsVector - Create a value that contains the specified legal
343 /// parts combined into the value they represent.  If the parts combine to a
344 /// type larger than ValueVT then AssertOp can be used to specify whether the
345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
346 /// ValueVT (ISD::AssertSext).
347 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
348                                       const SDValue *Parts, unsigned NumParts,
349                                       MVT PartVT, EVT ValueVT, const Value *V,
350                                       Optional<CallingConv::ID> CallConv) {
351   assert(ValueVT.isVector() && "Not a vector value");
352   assert(NumParts > 0 && "No parts to assemble!");
353   const bool IsABIRegCopy = CallConv.hasValue();
354 
355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
356   SDValue Val = Parts[0];
357 
358   // Handle a multi-element vector.
359   if (NumParts > 1) {
360     EVT IntermediateVT;
361     MVT RegisterVT;
362     unsigned NumIntermediates;
363     unsigned NumRegs;
364 
365     if (IsABIRegCopy) {
366       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
367           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
368           NumIntermediates, RegisterVT);
369     } else {
370       NumRegs =
371           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
372                                      NumIntermediates, RegisterVT);
373     }
374 
375     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
376     NumParts = NumRegs; // Silence a compiler warning.
377     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
378     assert(RegisterVT.getSizeInBits() ==
379            Parts[0].getSimpleValueType().getSizeInBits() &&
380            "Part type sizes don't match!");
381 
382     // Assemble the parts into intermediate operands.
383     SmallVector<SDValue, 8> Ops(NumIntermediates);
384     if (NumIntermediates == NumParts) {
385       // If the register was not expanded, truncate or copy the value,
386       // as appropriate.
387       for (unsigned i = 0; i != NumParts; ++i)
388         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
389                                   PartVT, IntermediateVT, V);
390     } else if (NumParts > 0) {
391       // If the intermediate type was expanded, build the intermediate
392       // operands from the parts.
393       assert(NumParts % NumIntermediates == 0 &&
394              "Must expand into a divisible number of parts!");
395       unsigned Factor = NumParts / NumIntermediates;
396       for (unsigned i = 0; i != NumIntermediates; ++i)
397         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
398                                   PartVT, IntermediateVT, V);
399     }
400 
401     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
402     // intermediate operands.
403     EVT BuiltVectorTy =
404         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
405                          (IntermediateVT.isVector()
406                               ? IntermediateVT.getVectorNumElements() * NumParts
407                               : NumIntermediates));
408     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
409                                                 : ISD::BUILD_VECTOR,
410                       DL, BuiltVectorTy, Ops);
411   }
412 
413   // There is now one part, held in Val.  Correct it to match ValueVT.
414   EVT PartEVT = Val.getValueType();
415 
416   if (PartEVT == ValueVT)
417     return Val;
418 
419   if (PartEVT.isVector()) {
420     // If the element type of the source/dest vectors are the same, but the
421     // parts vector has more elements than the value vector, then we have a
422     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
423     // elements we want.
424     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
425       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
426              "Cannot narrow, it would be a lossy transformation");
427       return DAG.getNode(
428           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
429           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
430     }
431 
432     // Vector/Vector bitcast.
433     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
434       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
437       "Cannot handle this kind of promotion");
438     // Promoted vector extract
439     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
440 
441   }
442 
443   // Trivial bitcast if the types are the same size and the destination
444   // vector type is legal.
445   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
446       TLI.isTypeLegal(ValueVT))
447     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
448 
449   if (ValueVT.getVectorNumElements() != 1) {
450      // Certain ABIs require that vectors are passed as integers. For vectors
451      // are the same size, this is an obvious bitcast.
452      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
453        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
455        // Bitcast Val back the original type and extract the corresponding
456        // vector we want.
457        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
458        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
459                                            ValueVT.getVectorElementType(), Elts);
460        Val = DAG.getBitcast(WiderVecType, Val);
461        return DAG.getNode(
462            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
463            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
464      }
465 
466      diagnosePossiblyInvalidConstraint(
467          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
468      return DAG.getUNDEF(ValueVT);
469   }
470 
471   // Handle cases such as i8 -> <1 x i1>
472   EVT ValueSVT = ValueVT.getVectorElementType();
473   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
474     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
475                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
476 
477   return DAG.getBuildVector(ValueVT, DL, Val);
478 }
479 
480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
481                                  SDValue Val, SDValue *Parts, unsigned NumParts,
482                                  MVT PartVT, const Value *V,
483                                  Optional<CallingConv::ID> CallConv);
484 
485 /// getCopyToParts - Create a series of nodes that contain the specified value
486 /// split into legal parts.  If the parts contain more bits than Val, then, for
487 /// integers, ExtendKind can be used to specify how to generate the extra bits.
488 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
489                            SDValue *Parts, unsigned NumParts, MVT PartVT,
490                            const Value *V,
491                            Optional<CallingConv::ID> CallConv = None,
492                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
493   EVT ValueVT = Val.getValueType();
494 
495   // Handle the vector case separately.
496   if (ValueVT.isVector())
497     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
498                                 CallConv);
499 
500   unsigned PartBits = PartVT.getSizeInBits();
501   unsigned OrigNumParts = NumParts;
502   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
503          "Copying to an illegal type!");
504 
505   if (NumParts == 0)
506     return;
507 
508   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
509   EVT PartEVT = PartVT;
510   if (PartEVT == ValueVT) {
511     assert(NumParts == 1 && "No-op copy with multiple parts!");
512     Parts[0] = Val;
513     return;
514   }
515 
516   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
517     // If the parts cover more bits than the value has, promote the value.
518     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
519       assert(NumParts == 1 && "Do not know what to promote to!");
520       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
521     } else {
522       if (ValueVT.isFloatingPoint()) {
523         // FP values need to be bitcast, then extended if they are being put
524         // into a larger container.
525         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
526         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
527       }
528       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
529              ValueVT.isInteger() &&
530              "Unknown mismatch!");
531       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
532       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
533       if (PartVT == MVT::x86mmx)
534         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
535     }
536   } else if (PartBits == ValueVT.getSizeInBits()) {
537     // Different types of the same size.
538     assert(NumParts == 1 && PartEVT != ValueVT);
539     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
540   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
541     // If the parts cover less bits than value has, truncate the value.
542     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543            ValueVT.isInteger() &&
544            "Unknown mismatch!");
545     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
547     if (PartVT == MVT::x86mmx)
548       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549   }
550 
551   // The value may have changed - recompute ValueVT.
552   ValueVT = Val.getValueType();
553   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
554          "Failed to tile the value with PartVT!");
555 
556   if (NumParts == 1) {
557     if (PartEVT != ValueVT) {
558       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
559                                         "scalar-to-vector conversion failed");
560       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561     }
562 
563     Parts[0] = Val;
564     return;
565   }
566 
567   // Expand the value into multiple parts.
568   if (NumParts & (NumParts - 1)) {
569     // The number of parts is not a power of 2.  Split off and copy the tail.
570     assert(PartVT.isInteger() && ValueVT.isInteger() &&
571            "Do not know what to expand to!");
572     unsigned RoundParts = 1 << Log2_32(NumParts);
573     unsigned RoundBits = RoundParts * PartBits;
574     unsigned OddParts = NumParts - RoundParts;
575     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
576                                  DAG.getIntPtrConstant(RoundBits, DL));
577     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
578                    CallConv);
579 
580     if (DAG.getDataLayout().isBigEndian())
581       // The odd parts were reversed by getCopyToParts - unreverse them.
582       std::reverse(Parts + RoundParts, Parts + NumParts);
583 
584     NumParts = RoundParts;
585     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
586     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
587   }
588 
589   // The number of parts is a power of 2.  Repeatedly bisect the value using
590   // EXTRACT_ELEMENT.
591   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
592                          EVT::getIntegerVT(*DAG.getContext(),
593                                            ValueVT.getSizeInBits()),
594                          Val);
595 
596   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
597     for (unsigned i = 0; i < NumParts; i += StepSize) {
598       unsigned ThisBits = StepSize * PartBits / 2;
599       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
600       SDValue &Part0 = Parts[i];
601       SDValue &Part1 = Parts[i+StepSize/2];
602 
603       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
604                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
605       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
606                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
607 
608       if (ThisBits == PartBits && ThisVT != PartVT) {
609         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
610         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
611       }
612     }
613   }
614 
615   if (DAG.getDataLayout().isBigEndian())
616     std::reverse(Parts, Parts + OrigNumParts);
617 }
618 
619 static SDValue widenVectorToPartType(SelectionDAG &DAG,
620                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
621   if (!PartVT.isVector())
622     return SDValue();
623 
624   EVT ValueVT = Val.getValueType();
625   unsigned PartNumElts = PartVT.getVectorNumElements();
626   unsigned ValueNumElts = ValueVT.getVectorNumElements();
627   if (PartNumElts > ValueNumElts &&
628       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
629     EVT ElementVT = PartVT.getVectorElementType();
630     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
631     // undef elements.
632     SmallVector<SDValue, 16> Ops;
633     DAG.ExtractVectorElements(Val, Ops);
634     SDValue EltUndef = DAG.getUNDEF(ElementVT);
635     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
636       Ops.push_back(EltUndef);
637 
638     // FIXME: Use CONCAT for 2x -> 4x.
639     return DAG.getBuildVector(PartVT, DL, Ops);
640   }
641 
642   return SDValue();
643 }
644 
645 /// getCopyToPartsVector - Create a series of nodes that contain the specified
646 /// value split into legal parts.
647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
648                                  SDValue Val, SDValue *Parts, unsigned NumParts,
649                                  MVT PartVT, const Value *V,
650                                  Optional<CallingConv::ID> CallConv) {
651   EVT ValueVT = Val.getValueType();
652   assert(ValueVT.isVector() && "Not a vector");
653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
654   const bool IsABIRegCopy = CallConv.hasValue();
655 
656   if (NumParts == 1) {
657     EVT PartEVT = PartVT;
658     if (PartEVT == ValueVT) {
659       // Nothing to do.
660     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
661       // Bitconvert vector->vector case.
662       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
663     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
664       Val = Widened;
665     } else if (PartVT.isVector() &&
666                PartEVT.getVectorElementType().bitsGE(
667                  ValueVT.getVectorElementType()) &&
668                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
669 
670       // Promoted vector extract
671       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
672     } else {
673       if (ValueVT.getVectorNumElements() == 1) {
674         Val = DAG.getNode(
675             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
676             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
677       } else {
678         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
679                "lossy conversion of vector to scalar type");
680         EVT IntermediateType =
681             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
682         Val = DAG.getBitcast(IntermediateType, Val);
683         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
684       }
685     }
686 
687     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
688     Parts[0] = Val;
689     return;
690   }
691 
692   // Handle a multi-element vector.
693   EVT IntermediateVT;
694   MVT RegisterVT;
695   unsigned NumIntermediates;
696   unsigned NumRegs;
697   if (IsABIRegCopy) {
698     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
699         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
700         NumIntermediates, RegisterVT);
701   } else {
702     NumRegs =
703         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
704                                    NumIntermediates, RegisterVT);
705   }
706 
707   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
708   NumParts = NumRegs; // Silence a compiler warning.
709   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
710 
711   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
712     IntermediateVT.getVectorNumElements() : 1;
713 
714   // Convert the vector to the appropiate type if necessary.
715   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
716 
717   EVT BuiltVectorTy = EVT::getVectorVT(
718       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
719   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
720   if (ValueVT != BuiltVectorTy) {
721     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
722       Val = Widened;
723 
724     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
725   }
726 
727   // Split the vector into intermediate operands.
728   SmallVector<SDValue, 8> Ops(NumIntermediates);
729   for (unsigned i = 0; i != NumIntermediates; ++i) {
730     if (IntermediateVT.isVector()) {
731       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
732                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
733     } else {
734       Ops[i] = DAG.getNode(
735           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
736           DAG.getConstant(i, DL, IdxVT));
737     }
738   }
739 
740   // Split the intermediate operands into legal parts.
741   if (NumParts == NumIntermediates) {
742     // If the register was not expanded, promote or copy the value,
743     // as appropriate.
744     for (unsigned i = 0; i != NumParts; ++i)
745       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
746   } else if (NumParts > 0) {
747     // If the intermediate type was expanded, split each the value into
748     // legal parts.
749     assert(NumIntermediates != 0 && "division by zero");
750     assert(NumParts % NumIntermediates == 0 &&
751            "Must expand into a divisible number of parts!");
752     unsigned Factor = NumParts / NumIntermediates;
753     for (unsigned i = 0; i != NumIntermediates; ++i)
754       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
755                      CallConv);
756   }
757 }
758 
759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
760                            EVT valuevt, Optional<CallingConv::ID> CC)
761     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
762       RegCount(1, regs.size()), CallConv(CC) {}
763 
764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
765                            const DataLayout &DL, unsigned Reg, Type *Ty,
766                            Optional<CallingConv::ID> CC) {
767   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
768 
769   CallConv = CC;
770 
771   for (EVT ValueVT : ValueVTs) {
772     unsigned NumRegs =
773         isABIMangled()
774             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
775             : TLI.getNumRegisters(Context, ValueVT);
776     MVT RegisterVT =
777         isABIMangled()
778             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
779             : TLI.getRegisterType(Context, ValueVT);
780     for (unsigned i = 0; i != NumRegs; ++i)
781       Regs.push_back(Reg + i);
782     RegVTs.push_back(RegisterVT);
783     RegCount.push_back(NumRegs);
784     Reg += NumRegs;
785   }
786 }
787 
788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
789                                       FunctionLoweringInfo &FuncInfo,
790                                       const SDLoc &dl, SDValue &Chain,
791                                       SDValue *Flag, const Value *V) const {
792   // A Value with type {} or [0 x %t] needs no registers.
793   if (ValueVTs.empty())
794     return SDValue();
795 
796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
797 
798   // Assemble the legal parts into the final values.
799   SmallVector<SDValue, 4> Values(ValueVTs.size());
800   SmallVector<SDValue, 8> Parts;
801   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
802     // Copy the legal parts from the registers.
803     EVT ValueVT = ValueVTs[Value];
804     unsigned NumRegs = RegCount[Value];
805     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
806                                           *DAG.getContext(),
807                                           CallConv.getValue(), RegVTs[Value])
808                                     : RegVTs[Value];
809 
810     Parts.resize(NumRegs);
811     for (unsigned i = 0; i != NumRegs; ++i) {
812       SDValue P;
813       if (!Flag) {
814         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
815       } else {
816         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
817         *Flag = P.getValue(2);
818       }
819 
820       Chain = P.getValue(1);
821       Parts[i] = P;
822 
823       // If the source register was virtual and if we know something about it,
824       // add an assert node.
825       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
826           !RegisterVT.isInteger())
827         continue;
828 
829       const FunctionLoweringInfo::LiveOutInfo *LOI =
830         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
831       if (!LOI)
832         continue;
833 
834       unsigned RegSize = RegisterVT.getScalarSizeInBits();
835       unsigned NumSignBits = LOI->NumSignBits;
836       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
837 
838       if (NumZeroBits == RegSize) {
839         // The current value is a zero.
840         // Explicitly express that as it would be easier for
841         // optimizations to kick in.
842         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
843         continue;
844       }
845 
846       // FIXME: We capture more information than the dag can represent.  For
847       // now, just use the tightest assertzext/assertsext possible.
848       bool isSExt;
849       EVT FromVT(MVT::Other);
850       if (NumZeroBits) {
851         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
852         isSExt = false;
853       } else if (NumSignBits > 1) {
854         FromVT =
855             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
856         isSExt = true;
857       } else {
858         continue;
859       }
860       // Add an assertion node.
861       assert(FromVT != MVT::Other);
862       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
863                              RegisterVT, P, DAG.getValueType(FromVT));
864     }
865 
866     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
867                                      RegisterVT, ValueVT, V, CallConv);
868     Part += NumRegs;
869     Parts.clear();
870   }
871 
872   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
873 }
874 
875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
876                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
877                                  const Value *V,
878                                  ISD::NodeType PreferredExtendType) const {
879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
880   ISD::NodeType ExtendKind = PreferredExtendType;
881 
882   // Get the list of the values's legal parts.
883   unsigned NumRegs = Regs.size();
884   SmallVector<SDValue, 8> Parts(NumRegs);
885   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
886     unsigned NumParts = RegCount[Value];
887 
888     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
889                                           *DAG.getContext(),
890                                           CallConv.getValue(), RegVTs[Value])
891                                     : RegVTs[Value];
892 
893     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
894       ExtendKind = ISD::ZERO_EXTEND;
895 
896     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
897                    NumParts, RegisterVT, V, CallConv, ExtendKind);
898     Part += NumParts;
899   }
900 
901   // Copy the parts into the registers.
902   SmallVector<SDValue, 8> Chains(NumRegs);
903   for (unsigned i = 0; i != NumRegs; ++i) {
904     SDValue Part;
905     if (!Flag) {
906       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
907     } else {
908       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
909       *Flag = Part.getValue(1);
910     }
911 
912     Chains[i] = Part.getValue(0);
913   }
914 
915   if (NumRegs == 1 || Flag)
916     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
917     // flagged to it. That is the CopyToReg nodes and the user are considered
918     // a single scheduling unit. If we create a TokenFactor and return it as
919     // chain, then the TokenFactor is both a predecessor (operand) of the
920     // user as well as a successor (the TF operands are flagged to the user).
921     // c1, f1 = CopyToReg
922     // c2, f2 = CopyToReg
923     // c3     = TokenFactor c1, c2
924     // ...
925     //        = op c3, ..., f2
926     Chain = Chains[NumRegs-1];
927   else
928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
929 }
930 
931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
932                                         unsigned MatchingIdx, const SDLoc &dl,
933                                         SelectionDAG &DAG,
934                                         std::vector<SDValue> &Ops) const {
935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
936 
937   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
938   if (HasMatching)
939     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
940   else if (!Regs.empty() &&
941            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
942     // Put the register class of the virtual registers in the flag word.  That
943     // way, later passes can recompute register class constraints for inline
944     // assembly as well as normal instructions.
945     // Don't do this for tied operands that can use the regclass information
946     // from the def.
947     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
948     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
949     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
950   }
951 
952   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
953   Ops.push_back(Res);
954 
955   if (Code == InlineAsm::Kind_Clobber) {
956     // Clobbers should always have a 1:1 mapping with registers, and may
957     // reference registers that have illegal (e.g. vector) types. Hence, we
958     // shouldn't try to apply any sort of splitting logic to them.
959     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
960            "No 1:1 mapping from clobbers to regs?");
961     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
962     (void)SP;
963     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
964       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
965       assert(
966           (Regs[I] != SP ||
967            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
968           "If we clobbered the stack pointer, MFI should know about it.");
969     }
970     return;
971   }
972 
973   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
974     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
975     MVT RegisterVT = RegVTs[Value];
976     for (unsigned i = 0; i != NumRegs; ++i) {
977       assert(Reg < Regs.size() && "Mismatch in # registers expected");
978       unsigned TheReg = Regs[Reg++];
979       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
980     }
981   }
982 }
983 
984 SmallVector<std::pair<unsigned, unsigned>, 4>
985 RegsForValue::getRegsAndSizes() const {
986   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
987   unsigned I = 0;
988   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
989     unsigned RegCount = std::get<0>(CountAndVT);
990     MVT RegisterVT = std::get<1>(CountAndVT);
991     unsigned RegisterSize = RegisterVT.getSizeInBits();
992     for (unsigned E = I + RegCount; I != E; ++I)
993       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
994   }
995   return OutVec;
996 }
997 
998 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
999                                const TargetLibraryInfo *li) {
1000   AA = aa;
1001   GFI = gfi;
1002   LibInfo = li;
1003   DL = &DAG.getDataLayout();
1004   Context = DAG.getContext();
1005   LPadToCallSiteMap.clear();
1006 }
1007 
1008 void SelectionDAGBuilder::clear() {
1009   NodeMap.clear();
1010   UnusedArgNodeMap.clear();
1011   PendingLoads.clear();
1012   PendingExports.clear();
1013   CurInst = nullptr;
1014   HasTailCall = false;
1015   SDNodeOrder = LowestSDNodeOrder;
1016   StatepointLowering.clear();
1017 }
1018 
1019 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1020   DanglingDebugInfoMap.clear();
1021 }
1022 
1023 SDValue SelectionDAGBuilder::getRoot() {
1024   if (PendingLoads.empty())
1025     return DAG.getRoot();
1026 
1027   if (PendingLoads.size() == 1) {
1028     SDValue Root = PendingLoads[0];
1029     DAG.setRoot(Root);
1030     PendingLoads.clear();
1031     return Root;
1032   }
1033 
1034   // Otherwise, we have to make a token factor node.
1035   SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1036                              PendingLoads);
1037   PendingLoads.clear();
1038   DAG.setRoot(Root);
1039   return Root;
1040 }
1041 
1042 SDValue SelectionDAGBuilder::getControlRoot() {
1043   SDValue Root = DAG.getRoot();
1044 
1045   if (PendingExports.empty())
1046     return Root;
1047 
1048   // Turn all of the CopyToReg chains into one factored node.
1049   if (Root.getOpcode() != ISD::EntryToken) {
1050     unsigned i = 0, e = PendingExports.size();
1051     for (; i != e; ++i) {
1052       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1053       if (PendingExports[i].getNode()->getOperand(0) == Root)
1054         break;  // Don't add the root if we already indirectly depend on it.
1055     }
1056 
1057     if (i == e)
1058       PendingExports.push_back(Root);
1059   }
1060 
1061   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1062                      PendingExports);
1063   PendingExports.clear();
1064   DAG.setRoot(Root);
1065   return Root;
1066 }
1067 
1068 void SelectionDAGBuilder::visit(const Instruction &I) {
1069   // Set up outgoing PHI node register values before emitting the terminator.
1070   if (I.isTerminator()) {
1071     HandlePHINodesInSuccessorBlocks(I.getParent());
1072   }
1073 
1074   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1075   if (!isa<DbgInfoIntrinsic>(I))
1076     ++SDNodeOrder;
1077 
1078   CurInst = &I;
1079 
1080   visit(I.getOpcode(), I);
1081 
1082   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1083     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1084     // maps to this instruction.
1085     // TODO: We could handle all flags (nsw, etc) here.
1086     // TODO: If an IR instruction maps to >1 node, only the final node will have
1087     //       flags set.
1088     if (SDNode *Node = getNodeForIRValue(&I)) {
1089       SDNodeFlags IncomingFlags;
1090       IncomingFlags.copyFMF(*FPMO);
1091       if (!Node->getFlags().isDefined())
1092         Node->setFlags(IncomingFlags);
1093       else
1094         Node->intersectFlagsWith(IncomingFlags);
1095     }
1096   }
1097 
1098   if (!I.isTerminator() && !HasTailCall &&
1099       !isStatepoint(&I)) // statepoints handle their exports internally
1100     CopyToExportRegsIfNeeded(&I);
1101 
1102   CurInst = nullptr;
1103 }
1104 
1105 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1106   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1107 }
1108 
1109 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1110   // Note: this doesn't use InstVisitor, because it has to work with
1111   // ConstantExpr's in addition to instructions.
1112   switch (Opcode) {
1113   default: llvm_unreachable("Unknown instruction type encountered!");
1114     // Build the switch statement using the Instruction.def file.
1115 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1116     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1117 #include "llvm/IR/Instruction.def"
1118   }
1119 }
1120 
1121 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1122                                                 const DIExpression *Expr) {
1123   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1124     const DbgValueInst *DI = DDI.getDI();
1125     DIVariable *DanglingVariable = DI->getVariable();
1126     DIExpression *DanglingExpr = DI->getExpression();
1127     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1128       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1129       return true;
1130     }
1131     return false;
1132   };
1133 
1134   for (auto &DDIMI : DanglingDebugInfoMap) {
1135     DanglingDebugInfoVector &DDIV = DDIMI.second;
1136     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1137   }
1138 }
1139 
1140 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1141 // generate the debug data structures now that we've seen its definition.
1142 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1143                                                    SDValue Val) {
1144   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1145   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1146     return;
1147 
1148   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1149   for (auto &DDI : DDIV) {
1150     const DbgValueInst *DI = DDI.getDI();
1151     assert(DI && "Ill-formed DanglingDebugInfo");
1152     DebugLoc dl = DDI.getdl();
1153     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1154     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1155     DILocalVariable *Variable = DI->getVariable();
1156     DIExpression *Expr = DI->getExpression();
1157     assert(Variable->isValidLocationForIntrinsic(dl) &&
1158            "Expected inlined-at fields to agree");
1159     SDDbgValue *SDV;
1160     if (Val.getNode()) {
1161       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1162         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1163                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1164         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1165         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1166         // inserted after the definition of Val when emitting the instructions
1167         // after ISel. An alternative could be to teach
1168         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1169         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1170                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1171                    << ValSDNodeOrder << "\n");
1172         SDV = getDbgValue(Val, Variable, Expr, dl,
1173                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1174         DAG.AddDbgValue(SDV, Val.getNode(), false);
1175       } else
1176         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1177                           << "in EmitFuncArgumentDbgValue\n");
1178     } else
1179       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1180   }
1181   DDIV.clear();
1182 }
1183 
1184 /// getCopyFromRegs - If there was virtual register allocated for the value V
1185 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1186 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1187   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1188   SDValue Result;
1189 
1190   if (It != FuncInfo.ValueMap.end()) {
1191     unsigned InReg = It->second;
1192 
1193     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1194                      DAG.getDataLayout(), InReg, Ty,
1195                      None); // This is not an ABI copy.
1196     SDValue Chain = DAG.getEntryNode();
1197     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1198                                  V);
1199     resolveDanglingDebugInfo(V, Result);
1200   }
1201 
1202   return Result;
1203 }
1204 
1205 /// getValue - Return an SDValue for the given Value.
1206 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1207   // If we already have an SDValue for this value, use it. It's important
1208   // to do this first, so that we don't create a CopyFromReg if we already
1209   // have a regular SDValue.
1210   SDValue &N = NodeMap[V];
1211   if (N.getNode()) return N;
1212 
1213   // If there's a virtual register allocated and initialized for this
1214   // value, use it.
1215   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1216     return copyFromReg;
1217 
1218   // Otherwise create a new SDValue and remember it.
1219   SDValue Val = getValueImpl(V);
1220   NodeMap[V] = Val;
1221   resolveDanglingDebugInfo(V, Val);
1222   return Val;
1223 }
1224 
1225 // Return true if SDValue exists for the given Value
1226 bool SelectionDAGBuilder::findValue(const Value *V) const {
1227   return (NodeMap.find(V) != NodeMap.end()) ||
1228     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1229 }
1230 
1231 /// getNonRegisterValue - Return an SDValue for the given Value, but
1232 /// don't look in FuncInfo.ValueMap for a virtual register.
1233 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1234   // If we already have an SDValue for this value, use it.
1235   SDValue &N = NodeMap[V];
1236   if (N.getNode()) {
1237     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1238       // Remove the debug location from the node as the node is about to be used
1239       // in a location which may differ from the original debug location.  This
1240       // is relevant to Constant and ConstantFP nodes because they can appear
1241       // as constant expressions inside PHI nodes.
1242       N->setDebugLoc(DebugLoc());
1243     }
1244     return N;
1245   }
1246 
1247   // Otherwise create a new SDValue and remember it.
1248   SDValue Val = getValueImpl(V);
1249   NodeMap[V] = Val;
1250   resolveDanglingDebugInfo(V, Val);
1251   return Val;
1252 }
1253 
1254 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1255 /// Create an SDValue for the given value.
1256 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1257   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1258 
1259   if (const Constant *C = dyn_cast<Constant>(V)) {
1260     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1261 
1262     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1263       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1264 
1265     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1266       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1267 
1268     if (isa<ConstantPointerNull>(C)) {
1269       unsigned AS = V->getType()->getPointerAddressSpace();
1270       return DAG.getConstant(0, getCurSDLoc(),
1271                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1272     }
1273 
1274     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1275       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1276 
1277     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1278       return DAG.getUNDEF(VT);
1279 
1280     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1281       visit(CE->getOpcode(), *CE);
1282       SDValue N1 = NodeMap[V];
1283       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1284       return N1;
1285     }
1286 
1287     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1288       SmallVector<SDValue, 4> Constants;
1289       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1290            OI != OE; ++OI) {
1291         SDNode *Val = getValue(*OI).getNode();
1292         // If the operand is an empty aggregate, there are no values.
1293         if (!Val) continue;
1294         // Add each leaf value from the operand to the Constants list
1295         // to form a flattened list of all the values.
1296         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1297           Constants.push_back(SDValue(Val, i));
1298       }
1299 
1300       return DAG.getMergeValues(Constants, getCurSDLoc());
1301     }
1302 
1303     if (const ConstantDataSequential *CDS =
1304           dyn_cast<ConstantDataSequential>(C)) {
1305       SmallVector<SDValue, 4> Ops;
1306       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1307         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1308         // Add each leaf value from the operand to the Constants list
1309         // to form a flattened list of all the values.
1310         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1311           Ops.push_back(SDValue(Val, i));
1312       }
1313 
1314       if (isa<ArrayType>(CDS->getType()))
1315         return DAG.getMergeValues(Ops, getCurSDLoc());
1316       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1317     }
1318 
1319     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1320       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1321              "Unknown struct or array constant!");
1322 
1323       SmallVector<EVT, 4> ValueVTs;
1324       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1325       unsigned NumElts = ValueVTs.size();
1326       if (NumElts == 0)
1327         return SDValue(); // empty struct
1328       SmallVector<SDValue, 4> Constants(NumElts);
1329       for (unsigned i = 0; i != NumElts; ++i) {
1330         EVT EltVT = ValueVTs[i];
1331         if (isa<UndefValue>(C))
1332           Constants[i] = DAG.getUNDEF(EltVT);
1333         else if (EltVT.isFloatingPoint())
1334           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1335         else
1336           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1337       }
1338 
1339       return DAG.getMergeValues(Constants, getCurSDLoc());
1340     }
1341 
1342     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1343       return DAG.getBlockAddress(BA, VT);
1344 
1345     VectorType *VecTy = cast<VectorType>(V->getType());
1346     unsigned NumElements = VecTy->getNumElements();
1347 
1348     // Now that we know the number and type of the elements, get that number of
1349     // elements into the Ops array based on what kind of constant it is.
1350     SmallVector<SDValue, 16> Ops;
1351     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1352       for (unsigned i = 0; i != NumElements; ++i)
1353         Ops.push_back(getValue(CV->getOperand(i)));
1354     } else {
1355       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1356       EVT EltVT =
1357           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1358 
1359       SDValue Op;
1360       if (EltVT.isFloatingPoint())
1361         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1362       else
1363         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1364       Ops.assign(NumElements, Op);
1365     }
1366 
1367     // Create a BUILD_VECTOR node.
1368     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1369   }
1370 
1371   // If this is a static alloca, generate it as the frameindex instead of
1372   // computation.
1373   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1374     DenseMap<const AllocaInst*, int>::iterator SI =
1375       FuncInfo.StaticAllocaMap.find(AI);
1376     if (SI != FuncInfo.StaticAllocaMap.end())
1377       return DAG.getFrameIndex(SI->second,
1378                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1379   }
1380 
1381   // If this is an instruction which fast-isel has deferred, select it now.
1382   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1383     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1384 
1385     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1386                      Inst->getType(), getABIRegCopyCC(V));
1387     SDValue Chain = DAG.getEntryNode();
1388     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1389   }
1390 
1391   llvm_unreachable("Can't get register for value!");
1392 }
1393 
1394 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1395   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1396   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1397   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1398   bool IsSEH = isAsynchronousEHPersonality(Pers);
1399   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1400   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1401   if (!IsSEH)
1402     CatchPadMBB->setIsEHScopeEntry();
1403   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1404   if (IsMSVCCXX || IsCoreCLR)
1405     CatchPadMBB->setIsEHFuncletEntry();
1406   // Wasm does not need catchpads anymore
1407   if (!IsWasmCXX)
1408     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1409                             getControlRoot()));
1410 }
1411 
1412 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1413   // Update machine-CFG edge.
1414   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1415   FuncInfo.MBB->addSuccessor(TargetMBB);
1416 
1417   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1418   bool IsSEH = isAsynchronousEHPersonality(Pers);
1419   if (IsSEH) {
1420     // If this is not a fall-through branch or optimizations are switched off,
1421     // emit the branch.
1422     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1423         TM.getOptLevel() == CodeGenOpt::None)
1424       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1425                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1426     return;
1427   }
1428 
1429   // Figure out the funclet membership for the catchret's successor.
1430   // This will be used by the FuncletLayout pass to determine how to order the
1431   // BB's.
1432   // A 'catchret' returns to the outer scope's color.
1433   Value *ParentPad = I.getCatchSwitchParentPad();
1434   const BasicBlock *SuccessorColor;
1435   if (isa<ConstantTokenNone>(ParentPad))
1436     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1437   else
1438     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1439   assert(SuccessorColor && "No parent funclet for catchret!");
1440   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1441   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1442 
1443   // Create the terminator node.
1444   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1445                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1446                             DAG.getBasicBlock(SuccessorColorMBB));
1447   DAG.setRoot(Ret);
1448 }
1449 
1450 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1451   // Don't emit any special code for the cleanuppad instruction. It just marks
1452   // the start of an EH scope/funclet.
1453   FuncInfo.MBB->setIsEHScopeEntry();
1454   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1455   if (Pers != EHPersonality::Wasm_CXX) {
1456     FuncInfo.MBB->setIsEHFuncletEntry();
1457     FuncInfo.MBB->setIsCleanupFuncletEntry();
1458   }
1459 }
1460 
1461 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1462 /// many places it could ultimately go. In the IR, we have a single unwind
1463 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1464 /// This function skips over imaginary basic blocks that hold catchswitch
1465 /// instructions, and finds all the "real" machine
1466 /// basic block destinations. As those destinations may not be successors of
1467 /// EHPadBB, here we also calculate the edge probability to those destinations.
1468 /// The passed-in Prob is the edge probability to EHPadBB.
1469 static void findUnwindDestinations(
1470     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1471     BranchProbability Prob,
1472     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1473         &UnwindDests) {
1474   EHPersonality Personality =
1475     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1476   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1477   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1478   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1479   bool IsSEH = isAsynchronousEHPersonality(Personality);
1480 
1481   while (EHPadBB) {
1482     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1483     BasicBlock *NewEHPadBB = nullptr;
1484     if (isa<LandingPadInst>(Pad)) {
1485       // Stop on landingpads. They are not funclets.
1486       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1487       break;
1488     } else if (isa<CleanupPadInst>(Pad)) {
1489       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1490       // personalities.
1491       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1492       UnwindDests.back().first->setIsEHScopeEntry();
1493       if (!IsWasmCXX)
1494         UnwindDests.back().first->setIsEHFuncletEntry();
1495       break;
1496     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1497       // Add the catchpad handlers to the possible destinations.
1498       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1499         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1500         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1501         if (IsMSVCCXX || IsCoreCLR)
1502           UnwindDests.back().first->setIsEHFuncletEntry();
1503         if (!IsSEH)
1504           UnwindDests.back().first->setIsEHScopeEntry();
1505       }
1506       NewEHPadBB = CatchSwitch->getUnwindDest();
1507     } else {
1508       continue;
1509     }
1510 
1511     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1512     if (BPI && NewEHPadBB)
1513       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1514     EHPadBB = NewEHPadBB;
1515   }
1516 }
1517 
1518 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1519   // Update successor info.
1520   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1521   auto UnwindDest = I.getUnwindDest();
1522   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1523   BranchProbability UnwindDestProb =
1524       (BPI && UnwindDest)
1525           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1526           : BranchProbability::getZero();
1527   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1528   for (auto &UnwindDest : UnwindDests) {
1529     UnwindDest.first->setIsEHPad();
1530     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1531   }
1532   FuncInfo.MBB->normalizeSuccProbs();
1533 
1534   // Create the terminator node.
1535   SDValue Ret =
1536       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1537   DAG.setRoot(Ret);
1538 }
1539 
1540 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1541   report_fatal_error("visitCatchSwitch not yet implemented!");
1542 }
1543 
1544 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1545   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1546   auto &DL = DAG.getDataLayout();
1547   SDValue Chain = getControlRoot();
1548   SmallVector<ISD::OutputArg, 8> Outs;
1549   SmallVector<SDValue, 8> OutVals;
1550 
1551   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1552   // lower
1553   //
1554   //   %val = call <ty> @llvm.experimental.deoptimize()
1555   //   ret <ty> %val
1556   //
1557   // differently.
1558   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1559     LowerDeoptimizingReturn();
1560     return;
1561   }
1562 
1563   if (!FuncInfo.CanLowerReturn) {
1564     unsigned DemoteReg = FuncInfo.DemoteRegister;
1565     const Function *F = I.getParent()->getParent();
1566 
1567     // Emit a store of the return value through the virtual register.
1568     // Leave Outs empty so that LowerReturn won't try to load return
1569     // registers the usual way.
1570     SmallVector<EVT, 1> PtrValueVTs;
1571     ComputeValueVTs(TLI, DL,
1572                     F->getReturnType()->getPointerTo(
1573                         DAG.getDataLayout().getAllocaAddrSpace()),
1574                     PtrValueVTs);
1575 
1576     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1577                                         DemoteReg, PtrValueVTs[0]);
1578     SDValue RetOp = getValue(I.getOperand(0));
1579 
1580     SmallVector<EVT, 4> ValueVTs;
1581     SmallVector<uint64_t, 4> Offsets;
1582     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1583     unsigned NumValues = ValueVTs.size();
1584 
1585     SmallVector<SDValue, 4> Chains(NumValues);
1586     for (unsigned i = 0; i != NumValues; ++i) {
1587       // An aggregate return value cannot wrap around the address space, so
1588       // offsets to its parts don't wrap either.
1589       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1590       Chains[i] = DAG.getStore(
1591           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1592           // FIXME: better loc info would be nice.
1593           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1594     }
1595 
1596     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1597                         MVT::Other, Chains);
1598   } else if (I.getNumOperands() != 0) {
1599     SmallVector<EVT, 4> ValueVTs;
1600     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1601     unsigned NumValues = ValueVTs.size();
1602     if (NumValues) {
1603       SDValue RetOp = getValue(I.getOperand(0));
1604 
1605       const Function *F = I.getParent()->getParent();
1606 
1607       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1608       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1609                                           Attribute::SExt))
1610         ExtendKind = ISD::SIGN_EXTEND;
1611       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1612                                                Attribute::ZExt))
1613         ExtendKind = ISD::ZERO_EXTEND;
1614 
1615       LLVMContext &Context = F->getContext();
1616       bool RetInReg = F->getAttributes().hasAttribute(
1617           AttributeList::ReturnIndex, Attribute::InReg);
1618 
1619       for (unsigned j = 0; j != NumValues; ++j) {
1620         EVT VT = ValueVTs[j];
1621 
1622         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1623           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1624 
1625         CallingConv::ID CC = F->getCallingConv();
1626 
1627         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1628         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1629         SmallVector<SDValue, 4> Parts(NumParts);
1630         getCopyToParts(DAG, getCurSDLoc(),
1631                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1632                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1633 
1634         // 'inreg' on function refers to return value
1635         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1636         if (RetInReg)
1637           Flags.setInReg();
1638 
1639         // Propagate extension type if any
1640         if (ExtendKind == ISD::SIGN_EXTEND)
1641           Flags.setSExt();
1642         else if (ExtendKind == ISD::ZERO_EXTEND)
1643           Flags.setZExt();
1644 
1645         for (unsigned i = 0; i < NumParts; ++i) {
1646           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1647                                         VT, /*isfixed=*/true, 0, 0));
1648           OutVals.push_back(Parts[i]);
1649         }
1650       }
1651     }
1652   }
1653 
1654   // Push in swifterror virtual register as the last element of Outs. This makes
1655   // sure swifterror virtual register will be returned in the swifterror
1656   // physical register.
1657   const Function *F = I.getParent()->getParent();
1658   if (TLI.supportSwiftError() &&
1659       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1660     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1661     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1662     Flags.setSwiftError();
1663     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1664                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1665                                   true /*isfixed*/, 1 /*origidx*/,
1666                                   0 /*partOffs*/));
1667     // Create SDNode for the swifterror virtual register.
1668     OutVals.push_back(
1669         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1670                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1671                         EVT(TLI.getPointerTy(DL))));
1672   }
1673 
1674   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1675   CallingConv::ID CallConv =
1676     DAG.getMachineFunction().getFunction().getCallingConv();
1677   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1678       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1679 
1680   // Verify that the target's LowerReturn behaved as expected.
1681   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1682          "LowerReturn didn't return a valid chain!");
1683 
1684   // Update the DAG with the new chain value resulting from return lowering.
1685   DAG.setRoot(Chain);
1686 }
1687 
1688 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1689 /// created for it, emit nodes to copy the value into the virtual
1690 /// registers.
1691 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1692   // Skip empty types
1693   if (V->getType()->isEmptyTy())
1694     return;
1695 
1696   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1697   if (VMI != FuncInfo.ValueMap.end()) {
1698     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1699     CopyValueToVirtualRegister(V, VMI->second);
1700   }
1701 }
1702 
1703 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1704 /// the current basic block, add it to ValueMap now so that we'll get a
1705 /// CopyTo/FromReg.
1706 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1707   // No need to export constants.
1708   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1709 
1710   // Already exported?
1711   if (FuncInfo.isExportedInst(V)) return;
1712 
1713   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1714   CopyValueToVirtualRegister(V, Reg);
1715 }
1716 
1717 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1718                                                      const BasicBlock *FromBB) {
1719   // The operands of the setcc have to be in this block.  We don't know
1720   // how to export them from some other block.
1721   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1722     // Can export from current BB.
1723     if (VI->getParent() == FromBB)
1724       return true;
1725 
1726     // Is already exported, noop.
1727     return FuncInfo.isExportedInst(V);
1728   }
1729 
1730   // If this is an argument, we can export it if the BB is the entry block or
1731   // if it is already exported.
1732   if (isa<Argument>(V)) {
1733     if (FromBB == &FromBB->getParent()->getEntryBlock())
1734       return true;
1735 
1736     // Otherwise, can only export this if it is already exported.
1737     return FuncInfo.isExportedInst(V);
1738   }
1739 
1740   // Otherwise, constants can always be exported.
1741   return true;
1742 }
1743 
1744 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1745 BranchProbability
1746 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1747                                         const MachineBasicBlock *Dst) const {
1748   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1749   const BasicBlock *SrcBB = Src->getBasicBlock();
1750   const BasicBlock *DstBB = Dst->getBasicBlock();
1751   if (!BPI) {
1752     // If BPI is not available, set the default probability as 1 / N, where N is
1753     // the number of successors.
1754     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1755     return BranchProbability(1, SuccSize);
1756   }
1757   return BPI->getEdgeProbability(SrcBB, DstBB);
1758 }
1759 
1760 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1761                                                MachineBasicBlock *Dst,
1762                                                BranchProbability Prob) {
1763   if (!FuncInfo.BPI)
1764     Src->addSuccessorWithoutProb(Dst);
1765   else {
1766     if (Prob.isUnknown())
1767       Prob = getEdgeProbability(Src, Dst);
1768     Src->addSuccessor(Dst, Prob);
1769   }
1770 }
1771 
1772 static bool InBlock(const Value *V, const BasicBlock *BB) {
1773   if (const Instruction *I = dyn_cast<Instruction>(V))
1774     return I->getParent() == BB;
1775   return true;
1776 }
1777 
1778 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1779 /// This function emits a branch and is used at the leaves of an OR or an
1780 /// AND operator tree.
1781 void
1782 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1783                                                   MachineBasicBlock *TBB,
1784                                                   MachineBasicBlock *FBB,
1785                                                   MachineBasicBlock *CurBB,
1786                                                   MachineBasicBlock *SwitchBB,
1787                                                   BranchProbability TProb,
1788                                                   BranchProbability FProb,
1789                                                   bool InvertCond) {
1790   const BasicBlock *BB = CurBB->getBasicBlock();
1791 
1792   // If the leaf of the tree is a comparison, merge the condition into
1793   // the caseblock.
1794   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1795     // The operands of the cmp have to be in this block.  We don't know
1796     // how to export them from some other block.  If this is the first block
1797     // of the sequence, no exporting is needed.
1798     if (CurBB == SwitchBB ||
1799         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1800          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1801       ISD::CondCode Condition;
1802       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1803         ICmpInst::Predicate Pred =
1804             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1805         Condition = getICmpCondCode(Pred);
1806       } else {
1807         const FCmpInst *FC = cast<FCmpInst>(Cond);
1808         FCmpInst::Predicate Pred =
1809             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1810         Condition = getFCmpCondCode(Pred);
1811         if (TM.Options.NoNaNsFPMath)
1812           Condition = getFCmpCodeWithoutNaN(Condition);
1813       }
1814 
1815       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1816                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1817       SwitchCases.push_back(CB);
1818       return;
1819     }
1820   }
1821 
1822   // Create a CaseBlock record representing this branch.
1823   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1824   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1825                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1826   SwitchCases.push_back(CB);
1827 }
1828 
1829 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1830                                                MachineBasicBlock *TBB,
1831                                                MachineBasicBlock *FBB,
1832                                                MachineBasicBlock *CurBB,
1833                                                MachineBasicBlock *SwitchBB,
1834                                                Instruction::BinaryOps Opc,
1835                                                BranchProbability TProb,
1836                                                BranchProbability FProb,
1837                                                bool InvertCond) {
1838   // Skip over not part of the tree and remember to invert op and operands at
1839   // next level.
1840   Value *NotCond;
1841   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
1842       InBlock(NotCond, CurBB->getBasicBlock())) {
1843     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1844                          !InvertCond);
1845     return;
1846   }
1847 
1848   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1849   // Compute the effective opcode for Cond, taking into account whether it needs
1850   // to be inverted, e.g.
1851   //   and (not (or A, B)), C
1852   // gets lowered as
1853   //   and (and (not A, not B), C)
1854   unsigned BOpc = 0;
1855   if (BOp) {
1856     BOpc = BOp->getOpcode();
1857     if (InvertCond) {
1858       if (BOpc == Instruction::And)
1859         BOpc = Instruction::Or;
1860       else if (BOpc == Instruction::Or)
1861         BOpc = Instruction::And;
1862     }
1863   }
1864 
1865   // If this node is not part of the or/and tree, emit it as a branch.
1866   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1867       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1868       BOp->getParent() != CurBB->getBasicBlock() ||
1869       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1870       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1871     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1872                                  TProb, FProb, InvertCond);
1873     return;
1874   }
1875 
1876   //  Create TmpBB after CurBB.
1877   MachineFunction::iterator BBI(CurBB);
1878   MachineFunction &MF = DAG.getMachineFunction();
1879   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1880   CurBB->getParent()->insert(++BBI, TmpBB);
1881 
1882   if (Opc == Instruction::Or) {
1883     // Codegen X | Y as:
1884     // BB1:
1885     //   jmp_if_X TBB
1886     //   jmp TmpBB
1887     // TmpBB:
1888     //   jmp_if_Y TBB
1889     //   jmp FBB
1890     //
1891 
1892     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1893     // The requirement is that
1894     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1895     //     = TrueProb for original BB.
1896     // Assuming the original probabilities are A and B, one choice is to set
1897     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1898     // A/(1+B) and 2B/(1+B). This choice assumes that
1899     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1900     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1901     // TmpBB, but the math is more complicated.
1902 
1903     auto NewTrueProb = TProb / 2;
1904     auto NewFalseProb = TProb / 2 + FProb;
1905     // Emit the LHS condition.
1906     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1907                          NewTrueProb, NewFalseProb, InvertCond);
1908 
1909     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1910     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1911     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1912     // Emit the RHS condition into TmpBB.
1913     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1914                          Probs[0], Probs[1], InvertCond);
1915   } else {
1916     assert(Opc == Instruction::And && "Unknown merge op!");
1917     // Codegen X & Y as:
1918     // BB1:
1919     //   jmp_if_X TmpBB
1920     //   jmp FBB
1921     // TmpBB:
1922     //   jmp_if_Y TBB
1923     //   jmp FBB
1924     //
1925     //  This requires creation of TmpBB after CurBB.
1926 
1927     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1928     // The requirement is that
1929     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1930     //     = FalseProb for original BB.
1931     // Assuming the original probabilities are A and B, one choice is to set
1932     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1933     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1934     // TrueProb for BB1 * FalseProb for TmpBB.
1935 
1936     auto NewTrueProb = TProb + FProb / 2;
1937     auto NewFalseProb = FProb / 2;
1938     // Emit the LHS condition.
1939     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1940                          NewTrueProb, NewFalseProb, InvertCond);
1941 
1942     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1943     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1944     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1945     // Emit the RHS condition into TmpBB.
1946     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1947                          Probs[0], Probs[1], InvertCond);
1948   }
1949 }
1950 
1951 /// If the set of cases should be emitted as a series of branches, return true.
1952 /// If we should emit this as a bunch of and/or'd together conditions, return
1953 /// false.
1954 bool
1955 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1956   if (Cases.size() != 2) return true;
1957 
1958   // If this is two comparisons of the same values or'd or and'd together, they
1959   // will get folded into a single comparison, so don't emit two blocks.
1960   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1961        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1962       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1963        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1964     return false;
1965   }
1966 
1967   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1968   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1969   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1970       Cases[0].CC == Cases[1].CC &&
1971       isa<Constant>(Cases[0].CmpRHS) &&
1972       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1973     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1974       return false;
1975     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1976       return false;
1977   }
1978 
1979   return true;
1980 }
1981 
1982 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1983   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1984 
1985   // Update machine-CFG edges.
1986   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1987 
1988   if (I.isUnconditional()) {
1989     // Update machine-CFG edges.
1990     BrMBB->addSuccessor(Succ0MBB);
1991 
1992     // If this is not a fall-through branch or optimizations are switched off,
1993     // emit the branch.
1994     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1995       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1996                               MVT::Other, getControlRoot(),
1997                               DAG.getBasicBlock(Succ0MBB)));
1998 
1999     return;
2000   }
2001 
2002   // If this condition is one of the special cases we handle, do special stuff
2003   // now.
2004   const Value *CondVal = I.getCondition();
2005   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2006 
2007   // If this is a series of conditions that are or'd or and'd together, emit
2008   // this as a sequence of branches instead of setcc's with and/or operations.
2009   // As long as jumps are not expensive, this should improve performance.
2010   // For example, instead of something like:
2011   //     cmp A, B
2012   //     C = seteq
2013   //     cmp D, E
2014   //     F = setle
2015   //     or C, F
2016   //     jnz foo
2017   // Emit:
2018   //     cmp A, B
2019   //     je foo
2020   //     cmp D, E
2021   //     jle foo
2022   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2023     Instruction::BinaryOps Opcode = BOp->getOpcode();
2024     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2025         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2026         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2027       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2028                            Opcode,
2029                            getEdgeProbability(BrMBB, Succ0MBB),
2030                            getEdgeProbability(BrMBB, Succ1MBB),
2031                            /*InvertCond=*/false);
2032       // If the compares in later blocks need to use values not currently
2033       // exported from this block, export them now.  This block should always
2034       // be the first entry.
2035       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2036 
2037       // Allow some cases to be rejected.
2038       if (ShouldEmitAsBranches(SwitchCases)) {
2039         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2040           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2041           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2042         }
2043 
2044         // Emit the branch for this block.
2045         visitSwitchCase(SwitchCases[0], BrMBB);
2046         SwitchCases.erase(SwitchCases.begin());
2047         return;
2048       }
2049 
2050       // Okay, we decided not to do this, remove any inserted MBB's and clear
2051       // SwitchCases.
2052       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2053         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2054 
2055       SwitchCases.clear();
2056     }
2057   }
2058 
2059   // Create a CaseBlock record representing this branch.
2060   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2061                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2062 
2063   // Use visitSwitchCase to actually insert the fast branch sequence for this
2064   // cond branch.
2065   visitSwitchCase(CB, BrMBB);
2066 }
2067 
2068 /// visitSwitchCase - Emits the necessary code to represent a single node in
2069 /// the binary search tree resulting from lowering a switch instruction.
2070 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2071                                           MachineBasicBlock *SwitchBB) {
2072   SDValue Cond;
2073   SDValue CondLHS = getValue(CB.CmpLHS);
2074   SDLoc dl = CB.DL;
2075 
2076   // Build the setcc now.
2077   if (!CB.CmpMHS) {
2078     // Fold "(X == true)" to X and "(X == false)" to !X to
2079     // handle common cases produced by branch lowering.
2080     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2081         CB.CC == ISD::SETEQ)
2082       Cond = CondLHS;
2083     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2084              CB.CC == ISD::SETEQ) {
2085       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2086       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2087     } else
2088       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2089   } else {
2090     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2091 
2092     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2093     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2094 
2095     SDValue CmpOp = getValue(CB.CmpMHS);
2096     EVT VT = CmpOp.getValueType();
2097 
2098     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2099       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2100                           ISD::SETLE);
2101     } else {
2102       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2103                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2104       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2105                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2106     }
2107   }
2108 
2109   // Update successor info
2110   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2111   // TrueBB and FalseBB are always different unless the incoming IR is
2112   // degenerate. This only happens when running llc on weird IR.
2113   if (CB.TrueBB != CB.FalseBB)
2114     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2115   SwitchBB->normalizeSuccProbs();
2116 
2117   // If the lhs block is the next block, invert the condition so that we can
2118   // fall through to the lhs instead of the rhs block.
2119   if (CB.TrueBB == NextBlock(SwitchBB)) {
2120     std::swap(CB.TrueBB, CB.FalseBB);
2121     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2122     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2123   }
2124 
2125   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2126                                MVT::Other, getControlRoot(), Cond,
2127                                DAG.getBasicBlock(CB.TrueBB));
2128 
2129   // Insert the false branch. Do this even if it's a fall through branch,
2130   // this makes it easier to do DAG optimizations which require inverting
2131   // the branch condition.
2132   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2133                        DAG.getBasicBlock(CB.FalseBB));
2134 
2135   DAG.setRoot(BrCond);
2136 }
2137 
2138 /// visitJumpTable - Emit JumpTable node in the current MBB
2139 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2140   // Emit the code for the jump table
2141   assert(JT.Reg != -1U && "Should lower JT Header first!");
2142   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2143   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2144                                      JT.Reg, PTy);
2145   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2146   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2147                                     MVT::Other, Index.getValue(1),
2148                                     Table, Index);
2149   DAG.setRoot(BrJumpTable);
2150 }
2151 
2152 /// visitJumpTableHeader - This function emits necessary code to produce index
2153 /// in the JumpTable from switch case.
2154 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2155                                                JumpTableHeader &JTH,
2156                                                MachineBasicBlock *SwitchBB) {
2157   SDLoc dl = getCurSDLoc();
2158 
2159   // Subtract the lowest switch case value from the value being switched on and
2160   // conditional branch to default mbb if the result is greater than the
2161   // difference between smallest and largest cases.
2162   SDValue SwitchOp = getValue(JTH.SValue);
2163   EVT VT = SwitchOp.getValueType();
2164   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2165                             DAG.getConstant(JTH.First, dl, VT));
2166 
2167   // The SDNode we just created, which holds the value being switched on minus
2168   // the smallest case value, needs to be copied to a virtual register so it
2169   // can be used as an index into the jump table in a subsequent basic block.
2170   // This value may be smaller or larger than the target's pointer type, and
2171   // therefore require extension or truncating.
2172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2173   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2174 
2175   unsigned JumpTableReg =
2176       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2177   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2178                                     JumpTableReg, SwitchOp);
2179   JT.Reg = JumpTableReg;
2180 
2181   // Emit the range check for the jump table, and branch to the default block
2182   // for the switch statement if the value being switched on exceeds the largest
2183   // case in the switch.
2184   SDValue CMP = DAG.getSetCC(
2185       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2186                                  Sub.getValueType()),
2187       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2188 
2189   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2190                                MVT::Other, CopyTo, CMP,
2191                                DAG.getBasicBlock(JT.Default));
2192 
2193   // Avoid emitting unnecessary branches to the next block.
2194   if (JT.MBB != NextBlock(SwitchBB))
2195     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2196                          DAG.getBasicBlock(JT.MBB));
2197 
2198   DAG.setRoot(BrCond);
2199 }
2200 
2201 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2202 /// variable if there exists one.
2203 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2204                                  SDValue &Chain) {
2205   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2206   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2209   MachineSDNode *Node =
2210       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2211   if (Global) {
2212     MachinePointerInfo MPInfo(Global);
2213     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2214                  MachineMemOperand::MODereferenceable;
2215     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2216         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2217     DAG.setNodeMemRefs(Node, {MemRef});
2218   }
2219   return SDValue(Node, 0);
2220 }
2221 
2222 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2223 /// tail spliced into a stack protector check success bb.
2224 ///
2225 /// For a high level explanation of how this fits into the stack protector
2226 /// generation see the comment on the declaration of class
2227 /// StackProtectorDescriptor.
2228 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2229                                                   MachineBasicBlock *ParentBB) {
2230 
2231   // First create the loads to the guard/stack slot for the comparison.
2232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2233   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2234 
2235   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2236   int FI = MFI.getStackProtectorIndex();
2237 
2238   SDValue Guard;
2239   SDLoc dl = getCurSDLoc();
2240   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2241   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2242   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2243 
2244   // Generate code to load the content of the guard slot.
2245   SDValue GuardVal = DAG.getLoad(
2246       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2247       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2248       MachineMemOperand::MOVolatile);
2249 
2250   if (TLI.useStackGuardXorFP())
2251     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2252 
2253   // Retrieve guard check function, nullptr if instrumentation is inlined.
2254   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2255     // The target provides a guard check function to validate the guard value.
2256     // Generate a call to that function with the content of the guard slot as
2257     // argument.
2258     auto *Fn = cast<Function>(GuardCheck);
2259     FunctionType *FnTy = Fn->getFunctionType();
2260     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2261 
2262     TargetLowering::ArgListTy Args;
2263     TargetLowering::ArgListEntry Entry;
2264     Entry.Node = GuardVal;
2265     Entry.Ty = FnTy->getParamType(0);
2266     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2267       Entry.IsInReg = true;
2268     Args.push_back(Entry);
2269 
2270     TargetLowering::CallLoweringInfo CLI(DAG);
2271     CLI.setDebugLoc(getCurSDLoc())
2272       .setChain(DAG.getEntryNode())
2273       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2274                  getValue(GuardCheck), std::move(Args));
2275 
2276     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2277     DAG.setRoot(Result.second);
2278     return;
2279   }
2280 
2281   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2282   // Otherwise, emit a volatile load to retrieve the stack guard value.
2283   SDValue Chain = DAG.getEntryNode();
2284   if (TLI.useLoadStackGuardNode()) {
2285     Guard = getLoadStackGuard(DAG, dl, Chain);
2286   } else {
2287     const Value *IRGuard = TLI.getSDagStackGuard(M);
2288     SDValue GuardPtr = getValue(IRGuard);
2289 
2290     Guard =
2291         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2292                     Align, MachineMemOperand::MOVolatile);
2293   }
2294 
2295   // Perform the comparison via a subtract/getsetcc.
2296   EVT VT = Guard.getValueType();
2297   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2298 
2299   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2300                                                         *DAG.getContext(),
2301                                                         Sub.getValueType()),
2302                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2303 
2304   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2305   // branch to failure MBB.
2306   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2307                                MVT::Other, GuardVal.getOperand(0),
2308                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2309   // Otherwise branch to success MBB.
2310   SDValue Br = DAG.getNode(ISD::BR, dl,
2311                            MVT::Other, BrCond,
2312                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2313 
2314   DAG.setRoot(Br);
2315 }
2316 
2317 /// Codegen the failure basic block for a stack protector check.
2318 ///
2319 /// A failure stack protector machine basic block consists simply of a call to
2320 /// __stack_chk_fail().
2321 ///
2322 /// For a high level explanation of how this fits into the stack protector
2323 /// generation see the comment on the declaration of class
2324 /// StackProtectorDescriptor.
2325 void
2326 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2327   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2328   SDValue Chain =
2329       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2330                       None, false, getCurSDLoc(), false, false).second;
2331   DAG.setRoot(Chain);
2332 }
2333 
2334 /// visitBitTestHeader - This function emits necessary code to produce value
2335 /// suitable for "bit tests"
2336 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2337                                              MachineBasicBlock *SwitchBB) {
2338   SDLoc dl = getCurSDLoc();
2339 
2340   // Subtract the minimum value
2341   SDValue SwitchOp = getValue(B.SValue);
2342   EVT VT = SwitchOp.getValueType();
2343   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2344                             DAG.getConstant(B.First, dl, VT));
2345 
2346   // Check range
2347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2348   SDValue RangeCmp = DAG.getSetCC(
2349       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2350                                  Sub.getValueType()),
2351       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2352 
2353   // Determine the type of the test operands.
2354   bool UsePtrType = false;
2355   if (!TLI.isTypeLegal(VT))
2356     UsePtrType = true;
2357   else {
2358     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2359       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2360         // Switch table case range are encoded into series of masks.
2361         // Just use pointer type, it's guaranteed to fit.
2362         UsePtrType = true;
2363         break;
2364       }
2365   }
2366   if (UsePtrType) {
2367     VT = TLI.getPointerTy(DAG.getDataLayout());
2368     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2369   }
2370 
2371   B.RegVT = VT.getSimpleVT();
2372   B.Reg = FuncInfo.CreateReg(B.RegVT);
2373   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2374 
2375   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2376 
2377   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2378   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2379   SwitchBB->normalizeSuccProbs();
2380 
2381   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2382                                 MVT::Other, CopyTo, RangeCmp,
2383                                 DAG.getBasicBlock(B.Default));
2384 
2385   // Avoid emitting unnecessary branches to the next block.
2386   if (MBB != NextBlock(SwitchBB))
2387     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2388                           DAG.getBasicBlock(MBB));
2389 
2390   DAG.setRoot(BrRange);
2391 }
2392 
2393 /// visitBitTestCase - this function produces one "bit test"
2394 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2395                                            MachineBasicBlock* NextMBB,
2396                                            BranchProbability BranchProbToNext,
2397                                            unsigned Reg,
2398                                            BitTestCase &B,
2399                                            MachineBasicBlock *SwitchBB) {
2400   SDLoc dl = getCurSDLoc();
2401   MVT VT = BB.RegVT;
2402   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2403   SDValue Cmp;
2404   unsigned PopCount = countPopulation(B.Mask);
2405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2406   if (PopCount == 1) {
2407     // Testing for a single bit; just compare the shift count with what it
2408     // would need to be to shift a 1 bit in that position.
2409     Cmp = DAG.getSetCC(
2410         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2411         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2412         ISD::SETEQ);
2413   } else if (PopCount == BB.Range) {
2414     // There is only one zero bit in the range, test for it directly.
2415     Cmp = DAG.getSetCC(
2416         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2417         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2418         ISD::SETNE);
2419   } else {
2420     // Make desired shift
2421     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2422                                     DAG.getConstant(1, dl, VT), ShiftOp);
2423 
2424     // Emit bit tests and jumps
2425     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2426                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2427     Cmp = DAG.getSetCC(
2428         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2429         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2430   }
2431 
2432   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2433   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2434   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2435   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2436   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2437   // one as they are relative probabilities (and thus work more like weights),
2438   // and hence we need to normalize them to let the sum of them become one.
2439   SwitchBB->normalizeSuccProbs();
2440 
2441   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2442                               MVT::Other, getControlRoot(),
2443                               Cmp, DAG.getBasicBlock(B.TargetBB));
2444 
2445   // Avoid emitting unnecessary branches to the next block.
2446   if (NextMBB != NextBlock(SwitchBB))
2447     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2448                         DAG.getBasicBlock(NextMBB));
2449 
2450   DAG.setRoot(BrAnd);
2451 }
2452 
2453 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2454   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2455 
2456   // Retrieve successors. Look through artificial IR level blocks like
2457   // catchswitch for successors.
2458   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2459   const BasicBlock *EHPadBB = I.getSuccessor(1);
2460 
2461   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2462   // have to do anything here to lower funclet bundles.
2463   assert(!I.hasOperandBundlesOtherThan(
2464              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2465          "Cannot lower invokes with arbitrary operand bundles yet!");
2466 
2467   const Value *Callee(I.getCalledValue());
2468   const Function *Fn = dyn_cast<Function>(Callee);
2469   if (isa<InlineAsm>(Callee))
2470     visitInlineAsm(&I);
2471   else if (Fn && Fn->isIntrinsic()) {
2472     switch (Fn->getIntrinsicID()) {
2473     default:
2474       llvm_unreachable("Cannot invoke this intrinsic");
2475     case Intrinsic::donothing:
2476       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2477       break;
2478     case Intrinsic::experimental_patchpoint_void:
2479     case Intrinsic::experimental_patchpoint_i64:
2480       visitPatchpoint(&I, EHPadBB);
2481       break;
2482     case Intrinsic::experimental_gc_statepoint:
2483       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2484       break;
2485     }
2486   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2487     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2488     // Eventually we will support lowering the @llvm.experimental.deoptimize
2489     // intrinsic, and right now there are no plans to support other intrinsics
2490     // with deopt state.
2491     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2492   } else {
2493     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2494   }
2495 
2496   // If the value of the invoke is used outside of its defining block, make it
2497   // available as a virtual register.
2498   // We already took care of the exported value for the statepoint instruction
2499   // during call to the LowerStatepoint.
2500   if (!isStatepoint(I)) {
2501     CopyToExportRegsIfNeeded(&I);
2502   }
2503 
2504   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2505   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2506   BranchProbability EHPadBBProb =
2507       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2508           : BranchProbability::getZero();
2509   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2510 
2511   // Update successor info.
2512   addSuccessorWithProb(InvokeMBB, Return);
2513   for (auto &UnwindDest : UnwindDests) {
2514     UnwindDest.first->setIsEHPad();
2515     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2516   }
2517   InvokeMBB->normalizeSuccProbs();
2518 
2519   // Drop into normal successor.
2520   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2521                           MVT::Other, getControlRoot(),
2522                           DAG.getBasicBlock(Return)));
2523 }
2524 
2525 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2526   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2527 }
2528 
2529 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2530   assert(FuncInfo.MBB->isEHPad() &&
2531          "Call to landingpad not in landing pad!");
2532 
2533   // If there aren't registers to copy the values into (e.g., during SjLj
2534   // exceptions), then don't bother to create these DAG nodes.
2535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2536   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2537   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2538       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2539     return;
2540 
2541   // If landingpad's return type is token type, we don't create DAG nodes
2542   // for its exception pointer and selector value. The extraction of exception
2543   // pointer or selector value from token type landingpads is not currently
2544   // supported.
2545   if (LP.getType()->isTokenTy())
2546     return;
2547 
2548   SmallVector<EVT, 2> ValueVTs;
2549   SDLoc dl = getCurSDLoc();
2550   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2551   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2552 
2553   // Get the two live-in registers as SDValues. The physregs have already been
2554   // copied into virtual registers.
2555   SDValue Ops[2];
2556   if (FuncInfo.ExceptionPointerVirtReg) {
2557     Ops[0] = DAG.getZExtOrTrunc(
2558         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2559                            FuncInfo.ExceptionPointerVirtReg,
2560                            TLI.getPointerTy(DAG.getDataLayout())),
2561         dl, ValueVTs[0]);
2562   } else {
2563     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2564   }
2565   Ops[1] = DAG.getZExtOrTrunc(
2566       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2567                          FuncInfo.ExceptionSelectorVirtReg,
2568                          TLI.getPointerTy(DAG.getDataLayout())),
2569       dl, ValueVTs[1]);
2570 
2571   // Merge into one.
2572   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2573                             DAG.getVTList(ValueVTs), Ops);
2574   setValue(&LP, Res);
2575 }
2576 
2577 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2578 #ifndef NDEBUG
2579   for (const CaseCluster &CC : Clusters)
2580     assert(CC.Low == CC.High && "Input clusters must be single-case");
2581 #endif
2582 
2583   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2584     return a.Low->getValue().slt(b.Low->getValue());
2585   });
2586 
2587   // Merge adjacent clusters with the same destination.
2588   const unsigned N = Clusters.size();
2589   unsigned DstIndex = 0;
2590   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2591     CaseCluster &CC = Clusters[SrcIndex];
2592     const ConstantInt *CaseVal = CC.Low;
2593     MachineBasicBlock *Succ = CC.MBB;
2594 
2595     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2596         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2597       // If this case has the same successor and is a neighbour, merge it into
2598       // the previous cluster.
2599       Clusters[DstIndex - 1].High = CaseVal;
2600       Clusters[DstIndex - 1].Prob += CC.Prob;
2601     } else {
2602       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2603                    sizeof(Clusters[SrcIndex]));
2604     }
2605   }
2606   Clusters.resize(DstIndex);
2607 }
2608 
2609 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2610                                            MachineBasicBlock *Last) {
2611   // Update JTCases.
2612   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2613     if (JTCases[i].first.HeaderBB == First)
2614       JTCases[i].first.HeaderBB = Last;
2615 
2616   // Update BitTestCases.
2617   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2618     if (BitTestCases[i].Parent == First)
2619       BitTestCases[i].Parent = Last;
2620 }
2621 
2622 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2623   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2624 
2625   // Update machine-CFG edges with unique successors.
2626   SmallSet<BasicBlock*, 32> Done;
2627   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2628     BasicBlock *BB = I.getSuccessor(i);
2629     bool Inserted = Done.insert(BB).second;
2630     if (!Inserted)
2631         continue;
2632 
2633     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2634     addSuccessorWithProb(IndirectBrMBB, Succ);
2635   }
2636   IndirectBrMBB->normalizeSuccProbs();
2637 
2638   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2639                           MVT::Other, getControlRoot(),
2640                           getValue(I.getAddress())));
2641 }
2642 
2643 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2644   if (!DAG.getTarget().Options.TrapUnreachable)
2645     return;
2646 
2647   // We may be able to ignore unreachable behind a noreturn call.
2648   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2649     const BasicBlock &BB = *I.getParent();
2650     if (&I != &BB.front()) {
2651       BasicBlock::const_iterator PredI =
2652         std::prev(BasicBlock::const_iterator(&I));
2653       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2654         if (Call->doesNotReturn())
2655           return;
2656       }
2657     }
2658   }
2659 
2660   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2661 }
2662 
2663 void SelectionDAGBuilder::visitFSub(const User &I) {
2664   // -0.0 - X --> fneg
2665   Type *Ty = I.getType();
2666   if (isa<Constant>(I.getOperand(0)) &&
2667       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2668     SDValue Op2 = getValue(I.getOperand(1));
2669     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2670                              Op2.getValueType(), Op2));
2671     return;
2672   }
2673 
2674   visitBinary(I, ISD::FSUB);
2675 }
2676 
2677 /// Checks if the given instruction performs a vector reduction, in which case
2678 /// we have the freedom to alter the elements in the result as long as the
2679 /// reduction of them stays unchanged.
2680 static bool isVectorReductionOp(const User *I) {
2681   const Instruction *Inst = dyn_cast<Instruction>(I);
2682   if (!Inst || !Inst->getType()->isVectorTy())
2683     return false;
2684 
2685   auto OpCode = Inst->getOpcode();
2686   switch (OpCode) {
2687   case Instruction::Add:
2688   case Instruction::Mul:
2689   case Instruction::And:
2690   case Instruction::Or:
2691   case Instruction::Xor:
2692     break;
2693   case Instruction::FAdd:
2694   case Instruction::FMul:
2695     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2696       if (FPOp->getFastMathFlags().isFast())
2697         break;
2698     LLVM_FALLTHROUGH;
2699   default:
2700     return false;
2701   }
2702 
2703   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2704   // Ensure the reduction size is a power of 2.
2705   if (!isPowerOf2_32(ElemNum))
2706     return false;
2707 
2708   unsigned ElemNumToReduce = ElemNum;
2709 
2710   // Do DFS search on the def-use chain from the given instruction. We only
2711   // allow four kinds of operations during the search until we reach the
2712   // instruction that extracts the first element from the vector:
2713   //
2714   //   1. The reduction operation of the same opcode as the given instruction.
2715   //
2716   //   2. PHI node.
2717   //
2718   //   3. ShuffleVector instruction together with a reduction operation that
2719   //      does a partial reduction.
2720   //
2721   //   4. ExtractElement that extracts the first element from the vector, and we
2722   //      stop searching the def-use chain here.
2723   //
2724   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2725   // from 1-3 to the stack to continue the DFS. The given instruction is not
2726   // a reduction operation if we meet any other instructions other than those
2727   // listed above.
2728 
2729   SmallVector<const User *, 16> UsersToVisit{Inst};
2730   SmallPtrSet<const User *, 16> Visited;
2731   bool ReduxExtracted = false;
2732 
2733   while (!UsersToVisit.empty()) {
2734     auto User = UsersToVisit.back();
2735     UsersToVisit.pop_back();
2736     if (!Visited.insert(User).second)
2737       continue;
2738 
2739     for (const auto &U : User->users()) {
2740       auto Inst = dyn_cast<Instruction>(U);
2741       if (!Inst)
2742         return false;
2743 
2744       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2745         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2746           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2747             return false;
2748         UsersToVisit.push_back(U);
2749       } else if (const ShuffleVectorInst *ShufInst =
2750                      dyn_cast<ShuffleVectorInst>(U)) {
2751         // Detect the following pattern: A ShuffleVector instruction together
2752         // with a reduction that do partial reduction on the first and second
2753         // ElemNumToReduce / 2 elements, and store the result in
2754         // ElemNumToReduce / 2 elements in another vector.
2755 
2756         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2757         if (ResultElements < ElemNum)
2758           return false;
2759 
2760         if (ElemNumToReduce == 1)
2761           return false;
2762         if (!isa<UndefValue>(U->getOperand(1)))
2763           return false;
2764         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2765           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2766             return false;
2767         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2768           if (ShufInst->getMaskValue(i) != -1)
2769             return false;
2770 
2771         // There is only one user of this ShuffleVector instruction, which
2772         // must be a reduction operation.
2773         if (!U->hasOneUse())
2774           return false;
2775 
2776         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2777         if (!U2 || U2->getOpcode() != OpCode)
2778           return false;
2779 
2780         // Check operands of the reduction operation.
2781         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2782             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2783           UsersToVisit.push_back(U2);
2784           ElemNumToReduce /= 2;
2785         } else
2786           return false;
2787       } else if (isa<ExtractElementInst>(U)) {
2788         // At this moment we should have reduced all elements in the vector.
2789         if (ElemNumToReduce != 1)
2790           return false;
2791 
2792         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2793         if (!Val || !Val->isZero())
2794           return false;
2795 
2796         ReduxExtracted = true;
2797       } else
2798         return false;
2799     }
2800   }
2801   return ReduxExtracted;
2802 }
2803 
2804 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
2805   SDNodeFlags Flags;
2806 
2807   SDValue Op = getValue(I.getOperand(0));
2808   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
2809                                     Op, Flags);
2810   setValue(&I, UnNodeValue);
2811 }
2812 
2813 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2814   SDNodeFlags Flags;
2815   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2816     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2817     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2818   }
2819   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2820     Flags.setExact(ExactOp->isExact());
2821   }
2822   if (isVectorReductionOp(&I)) {
2823     Flags.setVectorReduction(true);
2824     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2825   }
2826 
2827   SDValue Op1 = getValue(I.getOperand(0));
2828   SDValue Op2 = getValue(I.getOperand(1));
2829   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2830                                      Op1, Op2, Flags);
2831   setValue(&I, BinNodeValue);
2832 }
2833 
2834 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2835   SDValue Op1 = getValue(I.getOperand(0));
2836   SDValue Op2 = getValue(I.getOperand(1));
2837 
2838   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2839       Op1.getValueType(), DAG.getDataLayout());
2840 
2841   // Coerce the shift amount to the right type if we can.
2842   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2843     unsigned ShiftSize = ShiftTy.getSizeInBits();
2844     unsigned Op2Size = Op2.getValueSizeInBits();
2845     SDLoc DL = getCurSDLoc();
2846 
2847     // If the operand is smaller than the shift count type, promote it.
2848     if (ShiftSize > Op2Size)
2849       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2850 
2851     // If the operand is larger than the shift count type but the shift
2852     // count type has enough bits to represent any shift value, truncate
2853     // it now. This is a common case and it exposes the truncate to
2854     // optimization early.
2855     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2856       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2857     // Otherwise we'll need to temporarily settle for some other convenient
2858     // type.  Type legalization will make adjustments once the shiftee is split.
2859     else
2860       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2861   }
2862 
2863   bool nuw = false;
2864   bool nsw = false;
2865   bool exact = false;
2866 
2867   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2868 
2869     if (const OverflowingBinaryOperator *OFBinOp =
2870             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2871       nuw = OFBinOp->hasNoUnsignedWrap();
2872       nsw = OFBinOp->hasNoSignedWrap();
2873     }
2874     if (const PossiblyExactOperator *ExactOp =
2875             dyn_cast<const PossiblyExactOperator>(&I))
2876       exact = ExactOp->isExact();
2877   }
2878   SDNodeFlags Flags;
2879   Flags.setExact(exact);
2880   Flags.setNoSignedWrap(nsw);
2881   Flags.setNoUnsignedWrap(nuw);
2882   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2883                             Flags);
2884   setValue(&I, Res);
2885 }
2886 
2887 void SelectionDAGBuilder::visitSDiv(const User &I) {
2888   SDValue Op1 = getValue(I.getOperand(0));
2889   SDValue Op2 = getValue(I.getOperand(1));
2890 
2891   SDNodeFlags Flags;
2892   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2893                  cast<PossiblyExactOperator>(&I)->isExact());
2894   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2895                            Op2, Flags));
2896 }
2897 
2898 void SelectionDAGBuilder::visitICmp(const User &I) {
2899   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2900   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2901     predicate = IC->getPredicate();
2902   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2903     predicate = ICmpInst::Predicate(IC->getPredicate());
2904   SDValue Op1 = getValue(I.getOperand(0));
2905   SDValue Op2 = getValue(I.getOperand(1));
2906   ISD::CondCode Opcode = getICmpCondCode(predicate);
2907 
2908   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2909                                                         I.getType());
2910   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2911 }
2912 
2913 void SelectionDAGBuilder::visitFCmp(const User &I) {
2914   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2915   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2916     predicate = FC->getPredicate();
2917   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2918     predicate = FCmpInst::Predicate(FC->getPredicate());
2919   SDValue Op1 = getValue(I.getOperand(0));
2920   SDValue Op2 = getValue(I.getOperand(1));
2921 
2922   ISD::CondCode Condition = getFCmpCondCode(predicate);
2923   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2924   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2925     Condition = getFCmpCodeWithoutNaN(Condition);
2926 
2927   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2928                                                         I.getType());
2929   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2930 }
2931 
2932 // Check if the condition of the select has one use or two users that are both
2933 // selects with the same condition.
2934 static bool hasOnlySelectUsers(const Value *Cond) {
2935   return llvm::all_of(Cond->users(), [](const Value *V) {
2936     return isa<SelectInst>(V);
2937   });
2938 }
2939 
2940 void SelectionDAGBuilder::visitSelect(const User &I) {
2941   SmallVector<EVT, 4> ValueVTs;
2942   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2943                   ValueVTs);
2944   unsigned NumValues = ValueVTs.size();
2945   if (NumValues == 0) return;
2946 
2947   SmallVector<SDValue, 4> Values(NumValues);
2948   SDValue Cond     = getValue(I.getOperand(0));
2949   SDValue LHSVal   = getValue(I.getOperand(1));
2950   SDValue RHSVal   = getValue(I.getOperand(2));
2951   auto BaseOps = {Cond};
2952   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2953     ISD::VSELECT : ISD::SELECT;
2954 
2955   // Min/max matching is only viable if all output VTs are the same.
2956   if (is_splat(ValueVTs)) {
2957     EVT VT = ValueVTs[0];
2958     LLVMContext &Ctx = *DAG.getContext();
2959     auto &TLI = DAG.getTargetLoweringInfo();
2960 
2961     // We care about the legality of the operation after it has been type
2962     // legalized.
2963     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2964            VT != TLI.getTypeToTransformTo(Ctx, VT))
2965       VT = TLI.getTypeToTransformTo(Ctx, VT);
2966 
2967     // If the vselect is legal, assume we want to leave this as a vector setcc +
2968     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2969     // min/max is legal on the scalar type.
2970     bool UseScalarMinMax = VT.isVector() &&
2971       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2972 
2973     Value *LHS, *RHS;
2974     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2975     ISD::NodeType Opc = ISD::DELETED_NODE;
2976     switch (SPR.Flavor) {
2977     case SPF_UMAX:    Opc = ISD::UMAX; break;
2978     case SPF_UMIN:    Opc = ISD::UMIN; break;
2979     case SPF_SMAX:    Opc = ISD::SMAX; break;
2980     case SPF_SMIN:    Opc = ISD::SMIN; break;
2981     case SPF_FMINNUM:
2982       switch (SPR.NaNBehavior) {
2983       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2984       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
2985       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2986       case SPNB_RETURNS_ANY: {
2987         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2988           Opc = ISD::FMINNUM;
2989         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
2990           Opc = ISD::FMINIMUM;
2991         else if (UseScalarMinMax)
2992           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2993             ISD::FMINNUM : ISD::FMINIMUM;
2994         break;
2995       }
2996       }
2997       break;
2998     case SPF_FMAXNUM:
2999       switch (SPR.NaNBehavior) {
3000       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3001       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3002       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3003       case SPNB_RETURNS_ANY:
3004 
3005         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3006           Opc = ISD::FMAXNUM;
3007         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3008           Opc = ISD::FMAXIMUM;
3009         else if (UseScalarMinMax)
3010           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3011             ISD::FMAXNUM : ISD::FMAXIMUM;
3012         break;
3013       }
3014       break;
3015     default: break;
3016     }
3017 
3018     if (Opc != ISD::DELETED_NODE &&
3019         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3020          (UseScalarMinMax &&
3021           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3022         // If the underlying comparison instruction is used by any other
3023         // instruction, the consumed instructions won't be destroyed, so it is
3024         // not profitable to convert to a min/max.
3025         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3026       OpCode = Opc;
3027       LHSVal = getValue(LHS);
3028       RHSVal = getValue(RHS);
3029       BaseOps = {};
3030     }
3031   }
3032 
3033   for (unsigned i = 0; i != NumValues; ++i) {
3034     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3035     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3036     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3037     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3038                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3039                             Ops);
3040   }
3041 
3042   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3043                            DAG.getVTList(ValueVTs), Values));
3044 }
3045 
3046 void SelectionDAGBuilder::visitTrunc(const User &I) {
3047   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3048   SDValue N = getValue(I.getOperand(0));
3049   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3050                                                         I.getType());
3051   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3052 }
3053 
3054 void SelectionDAGBuilder::visitZExt(const User &I) {
3055   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3056   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3057   SDValue N = getValue(I.getOperand(0));
3058   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3059                                                         I.getType());
3060   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3061 }
3062 
3063 void SelectionDAGBuilder::visitSExt(const User &I) {
3064   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3065   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3066   SDValue N = getValue(I.getOperand(0));
3067   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3068                                                         I.getType());
3069   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3070 }
3071 
3072 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3073   // FPTrunc is never a no-op cast, no need to check
3074   SDValue N = getValue(I.getOperand(0));
3075   SDLoc dl = getCurSDLoc();
3076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3077   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3078   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3079                            DAG.getTargetConstant(
3080                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3081 }
3082 
3083 void SelectionDAGBuilder::visitFPExt(const User &I) {
3084   // FPExt is never a no-op cast, no need to check
3085   SDValue N = getValue(I.getOperand(0));
3086   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3087                                                         I.getType());
3088   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3089 }
3090 
3091 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3092   // FPToUI is never a no-op cast, no need to check
3093   SDValue N = getValue(I.getOperand(0));
3094   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3095                                                         I.getType());
3096   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3097 }
3098 
3099 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3100   // FPToSI is never a no-op cast, no need to check
3101   SDValue N = getValue(I.getOperand(0));
3102   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3103                                                         I.getType());
3104   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3105 }
3106 
3107 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3108   // UIToFP is never a no-op cast, no need to check
3109   SDValue N = getValue(I.getOperand(0));
3110   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3111                                                         I.getType());
3112   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3113 }
3114 
3115 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3116   // SIToFP is never a no-op cast, no need to check
3117   SDValue N = getValue(I.getOperand(0));
3118   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3119                                                         I.getType());
3120   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3121 }
3122 
3123 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3124   // What to do depends on the size of the integer and the size of the pointer.
3125   // We can either truncate, zero extend, or no-op, accordingly.
3126   SDValue N = getValue(I.getOperand(0));
3127   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3128                                                         I.getType());
3129   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3130 }
3131 
3132 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3133   // What to do depends on the size of the integer and the size of the pointer.
3134   // We can either truncate, zero extend, or no-op, accordingly.
3135   SDValue N = getValue(I.getOperand(0));
3136   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3137                                                         I.getType());
3138   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3139 }
3140 
3141 void SelectionDAGBuilder::visitBitCast(const User &I) {
3142   SDValue N = getValue(I.getOperand(0));
3143   SDLoc dl = getCurSDLoc();
3144   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3145                                                         I.getType());
3146 
3147   // BitCast assures us that source and destination are the same size so this is
3148   // either a BITCAST or a no-op.
3149   if (DestVT != N.getValueType())
3150     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3151                              DestVT, N)); // convert types.
3152   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3153   // might fold any kind of constant expression to an integer constant and that
3154   // is not what we are looking for. Only recognize a bitcast of a genuine
3155   // constant integer as an opaque constant.
3156   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3157     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3158                                  /*isOpaque*/true));
3159   else
3160     setValue(&I, N);            // noop cast.
3161 }
3162 
3163 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3164   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3165   const Value *SV = I.getOperand(0);
3166   SDValue N = getValue(SV);
3167   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3168 
3169   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3170   unsigned DestAS = I.getType()->getPointerAddressSpace();
3171 
3172   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3173     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3174 
3175   setValue(&I, N);
3176 }
3177 
3178 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3180   SDValue InVec = getValue(I.getOperand(0));
3181   SDValue InVal = getValue(I.getOperand(1));
3182   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3183                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3184   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3185                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3186                            InVec, InVal, InIdx));
3187 }
3188 
3189 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3190   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3191   SDValue InVec = getValue(I.getOperand(0));
3192   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3193                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3194   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3195                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3196                            InVec, InIdx));
3197 }
3198 
3199 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3200   SDValue Src1 = getValue(I.getOperand(0));
3201   SDValue Src2 = getValue(I.getOperand(1));
3202   SDLoc DL = getCurSDLoc();
3203 
3204   SmallVector<int, 8> Mask;
3205   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3206   unsigned MaskNumElts = Mask.size();
3207 
3208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3209   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3210   EVT SrcVT = Src1.getValueType();
3211   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3212 
3213   if (SrcNumElts == MaskNumElts) {
3214     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3215     return;
3216   }
3217 
3218   // Normalize the shuffle vector since mask and vector length don't match.
3219   if (SrcNumElts < MaskNumElts) {
3220     // Mask is longer than the source vectors. We can use concatenate vector to
3221     // make the mask and vectors lengths match.
3222 
3223     if (MaskNumElts % SrcNumElts == 0) {
3224       // Mask length is a multiple of the source vector length.
3225       // Check if the shuffle is some kind of concatenation of the input
3226       // vectors.
3227       unsigned NumConcat = MaskNumElts / SrcNumElts;
3228       bool IsConcat = true;
3229       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3230       for (unsigned i = 0; i != MaskNumElts; ++i) {
3231         int Idx = Mask[i];
3232         if (Idx < 0)
3233           continue;
3234         // Ensure the indices in each SrcVT sized piece are sequential and that
3235         // the same source is used for the whole piece.
3236         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3237             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3238              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3239           IsConcat = false;
3240           break;
3241         }
3242         // Remember which source this index came from.
3243         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3244       }
3245 
3246       // The shuffle is concatenating multiple vectors together. Just emit
3247       // a CONCAT_VECTORS operation.
3248       if (IsConcat) {
3249         SmallVector<SDValue, 8> ConcatOps;
3250         for (auto Src : ConcatSrcs) {
3251           if (Src < 0)
3252             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3253           else if (Src == 0)
3254             ConcatOps.push_back(Src1);
3255           else
3256             ConcatOps.push_back(Src2);
3257         }
3258         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3259         return;
3260       }
3261     }
3262 
3263     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3264     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3265     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3266                                     PaddedMaskNumElts);
3267 
3268     // Pad both vectors with undefs to make them the same length as the mask.
3269     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3270 
3271     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3272     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3273     MOps1[0] = Src1;
3274     MOps2[0] = Src2;
3275 
3276     Src1 = Src1.isUndef()
3277                ? DAG.getUNDEF(PaddedVT)
3278                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3279     Src2 = Src2.isUndef()
3280                ? DAG.getUNDEF(PaddedVT)
3281                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3282 
3283     // Readjust mask for new input vector length.
3284     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3285     for (unsigned i = 0; i != MaskNumElts; ++i) {
3286       int Idx = Mask[i];
3287       if (Idx >= (int)SrcNumElts)
3288         Idx -= SrcNumElts - PaddedMaskNumElts;
3289       MappedOps[i] = Idx;
3290     }
3291 
3292     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3293 
3294     // If the concatenated vector was padded, extract a subvector with the
3295     // correct number of elements.
3296     if (MaskNumElts != PaddedMaskNumElts)
3297       Result = DAG.getNode(
3298           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3299           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3300 
3301     setValue(&I, Result);
3302     return;
3303   }
3304 
3305   if (SrcNumElts > MaskNumElts) {
3306     // Analyze the access pattern of the vector to see if we can extract
3307     // two subvectors and do the shuffle.
3308     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3309     bool CanExtract = true;
3310     for (int Idx : Mask) {
3311       unsigned Input = 0;
3312       if (Idx < 0)
3313         continue;
3314 
3315       if (Idx >= (int)SrcNumElts) {
3316         Input = 1;
3317         Idx -= SrcNumElts;
3318       }
3319 
3320       // If all the indices come from the same MaskNumElts sized portion of
3321       // the sources we can use extract. Also make sure the extract wouldn't
3322       // extract past the end of the source.
3323       int NewStartIdx = alignDown(Idx, MaskNumElts);
3324       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3325           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3326         CanExtract = false;
3327       // Make sure we always update StartIdx as we use it to track if all
3328       // elements are undef.
3329       StartIdx[Input] = NewStartIdx;
3330     }
3331 
3332     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3333       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3334       return;
3335     }
3336     if (CanExtract) {
3337       // Extract appropriate subvector and generate a vector shuffle
3338       for (unsigned Input = 0; Input < 2; ++Input) {
3339         SDValue &Src = Input == 0 ? Src1 : Src2;
3340         if (StartIdx[Input] < 0)
3341           Src = DAG.getUNDEF(VT);
3342         else {
3343           Src = DAG.getNode(
3344               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3345               DAG.getConstant(StartIdx[Input], DL,
3346                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3347         }
3348       }
3349 
3350       // Calculate new mask.
3351       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3352       for (int &Idx : MappedOps) {
3353         if (Idx >= (int)SrcNumElts)
3354           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3355         else if (Idx >= 0)
3356           Idx -= StartIdx[0];
3357       }
3358 
3359       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3360       return;
3361     }
3362   }
3363 
3364   // We can't use either concat vectors or extract subvectors so fall back to
3365   // replacing the shuffle with extract and build vector.
3366   // to insert and build vector.
3367   EVT EltVT = VT.getVectorElementType();
3368   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3369   SmallVector<SDValue,8> Ops;
3370   for (int Idx : Mask) {
3371     SDValue Res;
3372 
3373     if (Idx < 0) {
3374       Res = DAG.getUNDEF(EltVT);
3375     } else {
3376       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3377       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3378 
3379       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3380                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3381     }
3382 
3383     Ops.push_back(Res);
3384   }
3385 
3386   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3387 }
3388 
3389 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3390   ArrayRef<unsigned> Indices;
3391   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3392     Indices = IV->getIndices();
3393   else
3394     Indices = cast<ConstantExpr>(&I)->getIndices();
3395 
3396   const Value *Op0 = I.getOperand(0);
3397   const Value *Op1 = I.getOperand(1);
3398   Type *AggTy = I.getType();
3399   Type *ValTy = Op1->getType();
3400   bool IntoUndef = isa<UndefValue>(Op0);
3401   bool FromUndef = isa<UndefValue>(Op1);
3402 
3403   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3404 
3405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3406   SmallVector<EVT, 4> AggValueVTs;
3407   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3408   SmallVector<EVT, 4> ValValueVTs;
3409   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3410 
3411   unsigned NumAggValues = AggValueVTs.size();
3412   unsigned NumValValues = ValValueVTs.size();
3413   SmallVector<SDValue, 4> Values(NumAggValues);
3414 
3415   // Ignore an insertvalue that produces an empty object
3416   if (!NumAggValues) {
3417     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3418     return;
3419   }
3420 
3421   SDValue Agg = getValue(Op0);
3422   unsigned i = 0;
3423   // Copy the beginning value(s) from the original aggregate.
3424   for (; i != LinearIndex; ++i)
3425     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3426                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3427   // Copy values from the inserted value(s).
3428   if (NumValValues) {
3429     SDValue Val = getValue(Op1);
3430     for (; i != LinearIndex + NumValValues; ++i)
3431       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3432                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3433   }
3434   // Copy remaining value(s) from the original aggregate.
3435   for (; i != NumAggValues; ++i)
3436     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3437                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3438 
3439   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3440                            DAG.getVTList(AggValueVTs), Values));
3441 }
3442 
3443 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3444   ArrayRef<unsigned> Indices;
3445   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3446     Indices = EV->getIndices();
3447   else
3448     Indices = cast<ConstantExpr>(&I)->getIndices();
3449 
3450   const Value *Op0 = I.getOperand(0);
3451   Type *AggTy = Op0->getType();
3452   Type *ValTy = I.getType();
3453   bool OutOfUndef = isa<UndefValue>(Op0);
3454 
3455   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3456 
3457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3458   SmallVector<EVT, 4> ValValueVTs;
3459   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3460 
3461   unsigned NumValValues = ValValueVTs.size();
3462 
3463   // Ignore a extractvalue that produces an empty object
3464   if (!NumValValues) {
3465     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3466     return;
3467   }
3468 
3469   SmallVector<SDValue, 4> Values(NumValValues);
3470 
3471   SDValue Agg = getValue(Op0);
3472   // Copy out the selected value(s).
3473   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3474     Values[i - LinearIndex] =
3475       OutOfUndef ?
3476         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3477         SDValue(Agg.getNode(), Agg.getResNo() + i);
3478 
3479   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3480                            DAG.getVTList(ValValueVTs), Values));
3481 }
3482 
3483 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3484   Value *Op0 = I.getOperand(0);
3485   // Note that the pointer operand may be a vector of pointers. Take the scalar
3486   // element which holds a pointer.
3487   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3488   SDValue N = getValue(Op0);
3489   SDLoc dl = getCurSDLoc();
3490 
3491   // Normalize Vector GEP - all scalar operands should be converted to the
3492   // splat vector.
3493   unsigned VectorWidth = I.getType()->isVectorTy() ?
3494     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3495 
3496   if (VectorWidth && !N.getValueType().isVector()) {
3497     LLVMContext &Context = *DAG.getContext();
3498     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3499     N = DAG.getSplatBuildVector(VT, dl, N);
3500   }
3501 
3502   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3503        GTI != E; ++GTI) {
3504     const Value *Idx = GTI.getOperand();
3505     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3506       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3507       if (Field) {
3508         // N = N + Offset
3509         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3510 
3511         // In an inbounds GEP with an offset that is nonnegative even when
3512         // interpreted as signed, assume there is no unsigned overflow.
3513         SDNodeFlags Flags;
3514         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3515           Flags.setNoUnsignedWrap(true);
3516 
3517         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3518                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3519       }
3520     } else {
3521       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3522       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3523       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3524 
3525       // If this is a scalar constant or a splat vector of constants,
3526       // handle it quickly.
3527       const auto *CI = dyn_cast<ConstantInt>(Idx);
3528       if (!CI && isa<ConstantDataVector>(Idx) &&
3529           cast<ConstantDataVector>(Idx)->getSplatValue())
3530         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3531 
3532       if (CI) {
3533         if (CI->isZero())
3534           continue;
3535         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3536         LLVMContext &Context = *DAG.getContext();
3537         SDValue OffsVal = VectorWidth ?
3538           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3539           DAG.getConstant(Offs, dl, IdxTy);
3540 
3541         // In an inbouds GEP with an offset that is nonnegative even when
3542         // interpreted as signed, assume there is no unsigned overflow.
3543         SDNodeFlags Flags;
3544         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3545           Flags.setNoUnsignedWrap(true);
3546 
3547         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3548         continue;
3549       }
3550 
3551       // N = N + Idx * ElementSize;
3552       SDValue IdxN = getValue(Idx);
3553 
3554       if (!IdxN.getValueType().isVector() && VectorWidth) {
3555         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3556         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3557       }
3558 
3559       // If the index is smaller or larger than intptr_t, truncate or extend
3560       // it.
3561       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3562 
3563       // If this is a multiply by a power of two, turn it into a shl
3564       // immediately.  This is a very common case.
3565       if (ElementSize != 1) {
3566         if (ElementSize.isPowerOf2()) {
3567           unsigned Amt = ElementSize.logBase2();
3568           IdxN = DAG.getNode(ISD::SHL, dl,
3569                              N.getValueType(), IdxN,
3570                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3571         } else {
3572           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3573           IdxN = DAG.getNode(ISD::MUL, dl,
3574                              N.getValueType(), IdxN, Scale);
3575         }
3576       }
3577 
3578       N = DAG.getNode(ISD::ADD, dl,
3579                       N.getValueType(), N, IdxN);
3580     }
3581   }
3582 
3583   setValue(&I, N);
3584 }
3585 
3586 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3587   // If this is a fixed sized alloca in the entry block of the function,
3588   // allocate it statically on the stack.
3589   if (FuncInfo.StaticAllocaMap.count(&I))
3590     return;   // getValue will auto-populate this.
3591 
3592   SDLoc dl = getCurSDLoc();
3593   Type *Ty = I.getAllocatedType();
3594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3595   auto &DL = DAG.getDataLayout();
3596   uint64_t TySize = DL.getTypeAllocSize(Ty);
3597   unsigned Align =
3598       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3599 
3600   SDValue AllocSize = getValue(I.getArraySize());
3601 
3602   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3603   if (AllocSize.getValueType() != IntPtr)
3604     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3605 
3606   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3607                           AllocSize,
3608                           DAG.getConstant(TySize, dl, IntPtr));
3609 
3610   // Handle alignment.  If the requested alignment is less than or equal to
3611   // the stack alignment, ignore it.  If the size is greater than or equal to
3612   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3613   unsigned StackAlign =
3614       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3615   if (Align <= StackAlign)
3616     Align = 0;
3617 
3618   // Round the size of the allocation up to the stack alignment size
3619   // by add SA-1 to the size. This doesn't overflow because we're computing
3620   // an address inside an alloca.
3621   SDNodeFlags Flags;
3622   Flags.setNoUnsignedWrap(true);
3623   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3624                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3625 
3626   // Mask out the low bits for alignment purposes.
3627   AllocSize =
3628       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3629                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3630 
3631   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3632   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3633   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3634   setValue(&I, DSA);
3635   DAG.setRoot(DSA.getValue(1));
3636 
3637   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3638 }
3639 
3640 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3641   if (I.isAtomic())
3642     return visitAtomicLoad(I);
3643 
3644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3645   const Value *SV = I.getOperand(0);
3646   if (TLI.supportSwiftError()) {
3647     // Swifterror values can come from either a function parameter with
3648     // swifterror attribute or an alloca with swifterror attribute.
3649     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3650       if (Arg->hasSwiftErrorAttr())
3651         return visitLoadFromSwiftError(I);
3652     }
3653 
3654     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3655       if (Alloca->isSwiftError())
3656         return visitLoadFromSwiftError(I);
3657     }
3658   }
3659 
3660   SDValue Ptr = getValue(SV);
3661 
3662   Type *Ty = I.getType();
3663 
3664   bool isVolatile = I.isVolatile();
3665   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3666   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3667   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3668   unsigned Alignment = I.getAlignment();
3669 
3670   AAMDNodes AAInfo;
3671   I.getAAMetadata(AAInfo);
3672   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3673 
3674   SmallVector<EVT, 4> ValueVTs;
3675   SmallVector<uint64_t, 4> Offsets;
3676   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3677   unsigned NumValues = ValueVTs.size();
3678   if (NumValues == 0)
3679     return;
3680 
3681   SDValue Root;
3682   bool ConstantMemory = false;
3683   if (isVolatile || NumValues > MaxParallelChains)
3684     // Serialize volatile loads with other side effects.
3685     Root = getRoot();
3686   else if (AA && AA->pointsToConstantMemory(MemoryLocation(
3687                SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3688     // Do not serialize (non-volatile) loads of constant memory with anything.
3689     Root = DAG.getEntryNode();
3690     ConstantMemory = true;
3691   } else {
3692     // Do not serialize non-volatile loads against each other.
3693     Root = DAG.getRoot();
3694   }
3695 
3696   SDLoc dl = getCurSDLoc();
3697 
3698   if (isVolatile)
3699     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3700 
3701   // An aggregate load cannot wrap around the address space, so offsets to its
3702   // parts don't wrap either.
3703   SDNodeFlags Flags;
3704   Flags.setNoUnsignedWrap(true);
3705 
3706   SmallVector<SDValue, 4> Values(NumValues);
3707   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3708   EVT PtrVT = Ptr.getValueType();
3709   unsigned ChainI = 0;
3710   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3711     // Serializing loads here may result in excessive register pressure, and
3712     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3713     // could recover a bit by hoisting nodes upward in the chain by recognizing
3714     // they are side-effect free or do not alias. The optimizer should really
3715     // avoid this case by converting large object/array copies to llvm.memcpy
3716     // (MaxParallelChains should always remain as failsafe).
3717     if (ChainI == MaxParallelChains) {
3718       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3719       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3720                                   makeArrayRef(Chains.data(), ChainI));
3721       Root = Chain;
3722       ChainI = 0;
3723     }
3724     SDValue A = DAG.getNode(ISD::ADD, dl,
3725                             PtrVT, Ptr,
3726                             DAG.getConstant(Offsets[i], dl, PtrVT),
3727                             Flags);
3728     auto MMOFlags = MachineMemOperand::MONone;
3729     if (isVolatile)
3730       MMOFlags |= MachineMemOperand::MOVolatile;
3731     if (isNonTemporal)
3732       MMOFlags |= MachineMemOperand::MONonTemporal;
3733     if (isInvariant)
3734       MMOFlags |= MachineMemOperand::MOInvariant;
3735     if (isDereferenceable)
3736       MMOFlags |= MachineMemOperand::MODereferenceable;
3737     MMOFlags |= TLI.getMMOFlags(I);
3738 
3739     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3740                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3741                             MMOFlags, AAInfo, Ranges);
3742 
3743     Values[i] = L;
3744     Chains[ChainI] = L.getValue(1);
3745   }
3746 
3747   if (!ConstantMemory) {
3748     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3749                                 makeArrayRef(Chains.data(), ChainI));
3750     if (isVolatile)
3751       DAG.setRoot(Chain);
3752     else
3753       PendingLoads.push_back(Chain);
3754   }
3755 
3756   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3757                            DAG.getVTList(ValueVTs), Values));
3758 }
3759 
3760 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3761   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3762          "call visitStoreToSwiftError when backend supports swifterror");
3763 
3764   SmallVector<EVT, 4> ValueVTs;
3765   SmallVector<uint64_t, 4> Offsets;
3766   const Value *SrcV = I.getOperand(0);
3767   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3768                   SrcV->getType(), ValueVTs, &Offsets);
3769   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3770          "expect a single EVT for swifterror");
3771 
3772   SDValue Src = getValue(SrcV);
3773   // Create a virtual register, then update the virtual register.
3774   unsigned VReg; bool CreatedVReg;
3775   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3776   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3777   // Chain can be getRoot or getControlRoot.
3778   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3779                                       SDValue(Src.getNode(), Src.getResNo()));
3780   DAG.setRoot(CopyNode);
3781   if (CreatedVReg)
3782     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3783 }
3784 
3785 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3786   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3787          "call visitLoadFromSwiftError when backend supports swifterror");
3788 
3789   assert(!I.isVolatile() &&
3790          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3791          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3792          "Support volatile, non temporal, invariant for load_from_swift_error");
3793 
3794   const Value *SV = I.getOperand(0);
3795   Type *Ty = I.getType();
3796   AAMDNodes AAInfo;
3797   I.getAAMetadata(AAInfo);
3798   assert((!AA || !AA->pointsToConstantMemory(MemoryLocation(
3799              SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) &&
3800          "load_from_swift_error should not be constant memory");
3801 
3802   SmallVector<EVT, 4> ValueVTs;
3803   SmallVector<uint64_t, 4> Offsets;
3804   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3805                   ValueVTs, &Offsets);
3806   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3807          "expect a single EVT for swifterror");
3808 
3809   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3810   SDValue L = DAG.getCopyFromReg(
3811       getRoot(), getCurSDLoc(),
3812       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3813       ValueVTs[0]);
3814 
3815   setValue(&I, L);
3816 }
3817 
3818 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3819   if (I.isAtomic())
3820     return visitAtomicStore(I);
3821 
3822   const Value *SrcV = I.getOperand(0);
3823   const Value *PtrV = I.getOperand(1);
3824 
3825   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3826   if (TLI.supportSwiftError()) {
3827     // Swifterror values can come from either a function parameter with
3828     // swifterror attribute or an alloca with swifterror attribute.
3829     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3830       if (Arg->hasSwiftErrorAttr())
3831         return visitStoreToSwiftError(I);
3832     }
3833 
3834     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3835       if (Alloca->isSwiftError())
3836         return visitStoreToSwiftError(I);
3837     }
3838   }
3839 
3840   SmallVector<EVT, 4> ValueVTs;
3841   SmallVector<uint64_t, 4> Offsets;
3842   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3843                   SrcV->getType(), ValueVTs, &Offsets);
3844   unsigned NumValues = ValueVTs.size();
3845   if (NumValues == 0)
3846     return;
3847 
3848   // Get the lowered operands. Note that we do this after
3849   // checking if NumResults is zero, because with zero results
3850   // the operands won't have values in the map.
3851   SDValue Src = getValue(SrcV);
3852   SDValue Ptr = getValue(PtrV);
3853 
3854   SDValue Root = getRoot();
3855   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3856   SDLoc dl = getCurSDLoc();
3857   EVT PtrVT = Ptr.getValueType();
3858   unsigned Alignment = I.getAlignment();
3859   AAMDNodes AAInfo;
3860   I.getAAMetadata(AAInfo);
3861 
3862   auto MMOFlags = MachineMemOperand::MONone;
3863   if (I.isVolatile())
3864     MMOFlags |= MachineMemOperand::MOVolatile;
3865   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3866     MMOFlags |= MachineMemOperand::MONonTemporal;
3867   MMOFlags |= TLI.getMMOFlags(I);
3868 
3869   // An aggregate load cannot wrap around the address space, so offsets to its
3870   // parts don't wrap either.
3871   SDNodeFlags Flags;
3872   Flags.setNoUnsignedWrap(true);
3873 
3874   unsigned ChainI = 0;
3875   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3876     // See visitLoad comments.
3877     if (ChainI == MaxParallelChains) {
3878       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3879                                   makeArrayRef(Chains.data(), ChainI));
3880       Root = Chain;
3881       ChainI = 0;
3882     }
3883     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3884                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3885     SDValue St = DAG.getStore(
3886         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3887         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3888     Chains[ChainI] = St;
3889   }
3890 
3891   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3892                                   makeArrayRef(Chains.data(), ChainI));
3893   DAG.setRoot(StoreNode);
3894 }
3895 
3896 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3897                                            bool IsCompressing) {
3898   SDLoc sdl = getCurSDLoc();
3899 
3900   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3901                            unsigned& Alignment) {
3902     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3903     Src0 = I.getArgOperand(0);
3904     Ptr = I.getArgOperand(1);
3905     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3906     Mask = I.getArgOperand(3);
3907   };
3908   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3909                            unsigned& Alignment) {
3910     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3911     Src0 = I.getArgOperand(0);
3912     Ptr = I.getArgOperand(1);
3913     Mask = I.getArgOperand(2);
3914     Alignment = 0;
3915   };
3916 
3917   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3918   unsigned Alignment;
3919   if (IsCompressing)
3920     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3921   else
3922     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3923 
3924   SDValue Ptr = getValue(PtrOperand);
3925   SDValue Src0 = getValue(Src0Operand);
3926   SDValue Mask = getValue(MaskOperand);
3927 
3928   EVT VT = Src0.getValueType();
3929   if (!Alignment)
3930     Alignment = DAG.getEVTAlignment(VT);
3931 
3932   AAMDNodes AAInfo;
3933   I.getAAMetadata(AAInfo);
3934 
3935   MachineMemOperand *MMO =
3936     DAG.getMachineFunction().
3937     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3938                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3939                           Alignment, AAInfo);
3940   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3941                                          MMO, false /* Truncating */,
3942                                          IsCompressing);
3943   DAG.setRoot(StoreNode);
3944   setValue(&I, StoreNode);
3945 }
3946 
3947 // Get a uniform base for the Gather/Scatter intrinsic.
3948 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3949 // We try to represent it as a base pointer + vector of indices.
3950 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3951 // The first operand of the GEP may be a single pointer or a vector of pointers
3952 // Example:
3953 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3954 //  or
3955 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3956 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3957 //
3958 // When the first GEP operand is a single pointer - it is the uniform base we
3959 // are looking for. If first operand of the GEP is a splat vector - we
3960 // extract the splat value and use it as a uniform base.
3961 // In all other cases the function returns 'false'.
3962 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3963                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3964   SelectionDAG& DAG = SDB->DAG;
3965   LLVMContext &Context = *DAG.getContext();
3966 
3967   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3968   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3969   if (!GEP)
3970     return false;
3971 
3972   const Value *GEPPtr = GEP->getPointerOperand();
3973   if (!GEPPtr->getType()->isVectorTy())
3974     Ptr = GEPPtr;
3975   else if (!(Ptr = getSplatValue(GEPPtr)))
3976     return false;
3977 
3978   unsigned FinalIndex = GEP->getNumOperands() - 1;
3979   Value *IndexVal = GEP->getOperand(FinalIndex);
3980 
3981   // Ensure all the other indices are 0.
3982   for (unsigned i = 1; i < FinalIndex; ++i) {
3983     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3984     if (!C || !C->isZero())
3985       return false;
3986   }
3987 
3988   // The operands of the GEP may be defined in another basic block.
3989   // In this case we'll not find nodes for the operands.
3990   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3991     return false;
3992 
3993   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3994   const DataLayout &DL = DAG.getDataLayout();
3995   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
3996                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
3997   Base = SDB->getValue(Ptr);
3998   Index = SDB->getValue(IndexVal);
3999 
4000   if (!Index.getValueType().isVector()) {
4001     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4002     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4003     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4004   }
4005   return true;
4006 }
4007 
4008 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4009   SDLoc sdl = getCurSDLoc();
4010 
4011   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4012   const Value *Ptr = I.getArgOperand(1);
4013   SDValue Src0 = getValue(I.getArgOperand(0));
4014   SDValue Mask = getValue(I.getArgOperand(3));
4015   EVT VT = Src0.getValueType();
4016   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4017   if (!Alignment)
4018     Alignment = DAG.getEVTAlignment(VT);
4019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4020 
4021   AAMDNodes AAInfo;
4022   I.getAAMetadata(AAInfo);
4023 
4024   SDValue Base;
4025   SDValue Index;
4026   SDValue Scale;
4027   const Value *BasePtr = Ptr;
4028   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4029 
4030   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4031   MachineMemOperand *MMO = DAG.getMachineFunction().
4032     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4033                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4034                          Alignment, AAInfo);
4035   if (!UniformBase) {
4036     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4037     Index = getValue(Ptr);
4038     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4039   }
4040   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4041   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4042                                          Ops, MMO);
4043   DAG.setRoot(Scatter);
4044   setValue(&I, Scatter);
4045 }
4046 
4047 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4048   SDLoc sdl = getCurSDLoc();
4049 
4050   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4051                            unsigned& Alignment) {
4052     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4053     Ptr = I.getArgOperand(0);
4054     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4055     Mask = I.getArgOperand(2);
4056     Src0 = I.getArgOperand(3);
4057   };
4058   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4059                            unsigned& Alignment) {
4060     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4061     Ptr = I.getArgOperand(0);
4062     Alignment = 0;
4063     Mask = I.getArgOperand(1);
4064     Src0 = I.getArgOperand(2);
4065   };
4066 
4067   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4068   unsigned Alignment;
4069   if (IsExpanding)
4070     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4071   else
4072     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4073 
4074   SDValue Ptr = getValue(PtrOperand);
4075   SDValue Src0 = getValue(Src0Operand);
4076   SDValue Mask = getValue(MaskOperand);
4077 
4078   EVT VT = Src0.getValueType();
4079   if (!Alignment)
4080     Alignment = DAG.getEVTAlignment(VT);
4081 
4082   AAMDNodes AAInfo;
4083   I.getAAMetadata(AAInfo);
4084   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4085 
4086   // Do not serialize masked loads of constant memory with anything.
4087   bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation(
4088       PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo));
4089   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4090 
4091   MachineMemOperand *MMO =
4092     DAG.getMachineFunction().
4093     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4094                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4095                           Alignment, AAInfo, Ranges);
4096 
4097   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4098                                    ISD::NON_EXTLOAD, IsExpanding);
4099   if (AddToChain)
4100     PendingLoads.push_back(Load.getValue(1));
4101   setValue(&I, Load);
4102 }
4103 
4104 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4105   SDLoc sdl = getCurSDLoc();
4106 
4107   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4108   const Value *Ptr = I.getArgOperand(0);
4109   SDValue Src0 = getValue(I.getArgOperand(3));
4110   SDValue Mask = getValue(I.getArgOperand(2));
4111 
4112   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4113   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4114   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4115   if (!Alignment)
4116     Alignment = DAG.getEVTAlignment(VT);
4117 
4118   AAMDNodes AAInfo;
4119   I.getAAMetadata(AAInfo);
4120   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4121 
4122   SDValue Root = DAG.getRoot();
4123   SDValue Base;
4124   SDValue Index;
4125   SDValue Scale;
4126   const Value *BasePtr = Ptr;
4127   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4128   bool ConstantMemory = false;
4129   if (UniformBase &&
4130       AA && AA->pointsToConstantMemory(MemoryLocation(
4131           BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
4132           AAInfo))) {
4133     // Do not serialize (non-volatile) loads of constant memory with anything.
4134     Root = DAG.getEntryNode();
4135     ConstantMemory = true;
4136   }
4137 
4138   MachineMemOperand *MMO =
4139     DAG.getMachineFunction().
4140     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4141                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4142                          Alignment, AAInfo, Ranges);
4143 
4144   if (!UniformBase) {
4145     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4146     Index = getValue(Ptr);
4147     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4148   }
4149   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4150   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4151                                        Ops, MMO);
4152 
4153   SDValue OutChain = Gather.getValue(1);
4154   if (!ConstantMemory)
4155     PendingLoads.push_back(OutChain);
4156   setValue(&I, Gather);
4157 }
4158 
4159 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4160   SDLoc dl = getCurSDLoc();
4161   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4162   AtomicOrdering FailureOrder = I.getFailureOrdering();
4163   SyncScope::ID SSID = I.getSyncScopeID();
4164 
4165   SDValue InChain = getRoot();
4166 
4167   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4168   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4169   SDValue L = DAG.getAtomicCmpSwap(
4170       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4171       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4172       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4173       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4174 
4175   SDValue OutChain = L.getValue(2);
4176 
4177   setValue(&I, L);
4178   DAG.setRoot(OutChain);
4179 }
4180 
4181 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4182   SDLoc dl = getCurSDLoc();
4183   ISD::NodeType NT;
4184   switch (I.getOperation()) {
4185   default: llvm_unreachable("Unknown atomicrmw operation");
4186   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4187   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4188   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4189   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4190   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4191   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4192   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4193   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4194   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4195   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4196   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4197   }
4198   AtomicOrdering Order = I.getOrdering();
4199   SyncScope::ID SSID = I.getSyncScopeID();
4200 
4201   SDValue InChain = getRoot();
4202 
4203   SDValue L =
4204     DAG.getAtomic(NT, dl,
4205                   getValue(I.getValOperand()).getSimpleValueType(),
4206                   InChain,
4207                   getValue(I.getPointerOperand()),
4208                   getValue(I.getValOperand()),
4209                   I.getPointerOperand(),
4210                   /* Alignment=*/ 0, Order, SSID);
4211 
4212   SDValue OutChain = L.getValue(1);
4213 
4214   setValue(&I, L);
4215   DAG.setRoot(OutChain);
4216 }
4217 
4218 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4219   SDLoc dl = getCurSDLoc();
4220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4221   SDValue Ops[3];
4222   Ops[0] = getRoot();
4223   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4224                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4225   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4226                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4227   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4228 }
4229 
4230 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4231   SDLoc dl = getCurSDLoc();
4232   AtomicOrdering Order = I.getOrdering();
4233   SyncScope::ID SSID = I.getSyncScopeID();
4234 
4235   SDValue InChain = getRoot();
4236 
4237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4238   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4239 
4240   if (!TLI.supportsUnalignedAtomics() &&
4241       I.getAlignment() < VT.getStoreSize())
4242     report_fatal_error("Cannot generate unaligned atomic load");
4243 
4244   MachineMemOperand *MMO =
4245       DAG.getMachineFunction().
4246       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4247                            MachineMemOperand::MOVolatile |
4248                            MachineMemOperand::MOLoad,
4249                            VT.getStoreSize(),
4250                            I.getAlignment() ? I.getAlignment() :
4251                                               DAG.getEVTAlignment(VT),
4252                            AAMDNodes(), nullptr, SSID, Order);
4253 
4254   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4255   SDValue L =
4256       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4257                     getValue(I.getPointerOperand()), MMO);
4258 
4259   SDValue OutChain = L.getValue(1);
4260 
4261   setValue(&I, L);
4262   DAG.setRoot(OutChain);
4263 }
4264 
4265 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4266   SDLoc dl = getCurSDLoc();
4267 
4268   AtomicOrdering Order = I.getOrdering();
4269   SyncScope::ID SSID = I.getSyncScopeID();
4270 
4271   SDValue InChain = getRoot();
4272 
4273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4274   EVT VT =
4275       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4276 
4277   if (I.getAlignment() < VT.getStoreSize())
4278     report_fatal_error("Cannot generate unaligned atomic store");
4279 
4280   SDValue OutChain =
4281     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4282                   InChain,
4283                   getValue(I.getPointerOperand()),
4284                   getValue(I.getValueOperand()),
4285                   I.getPointerOperand(), I.getAlignment(),
4286                   Order, SSID);
4287 
4288   DAG.setRoot(OutChain);
4289 }
4290 
4291 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4292 /// node.
4293 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4294                                                unsigned Intrinsic) {
4295   // Ignore the callsite's attributes. A specific call site may be marked with
4296   // readnone, but the lowering code will expect the chain based on the
4297   // definition.
4298   const Function *F = I.getCalledFunction();
4299   bool HasChain = !F->doesNotAccessMemory();
4300   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4301 
4302   // Build the operand list.
4303   SmallVector<SDValue, 8> Ops;
4304   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4305     if (OnlyLoad) {
4306       // We don't need to serialize loads against other loads.
4307       Ops.push_back(DAG.getRoot());
4308     } else {
4309       Ops.push_back(getRoot());
4310     }
4311   }
4312 
4313   // Info is set by getTgtMemInstrinsic
4314   TargetLowering::IntrinsicInfo Info;
4315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4316   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4317                                                DAG.getMachineFunction(),
4318                                                Intrinsic);
4319 
4320   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4321   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4322       Info.opc == ISD::INTRINSIC_W_CHAIN)
4323     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4324                                         TLI.getPointerTy(DAG.getDataLayout())));
4325 
4326   // Add all operands of the call to the operand list.
4327   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4328     SDValue Op = getValue(I.getArgOperand(i));
4329     Ops.push_back(Op);
4330   }
4331 
4332   SmallVector<EVT, 4> ValueVTs;
4333   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4334 
4335   if (HasChain)
4336     ValueVTs.push_back(MVT::Other);
4337 
4338   SDVTList VTs = DAG.getVTList(ValueVTs);
4339 
4340   // Create the node.
4341   SDValue Result;
4342   if (IsTgtIntrinsic) {
4343     // This is target intrinsic that touches memory
4344     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4345       Ops, Info.memVT,
4346       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4347       Info.flags, Info.size);
4348   } else if (!HasChain) {
4349     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4350   } else if (!I.getType()->isVoidTy()) {
4351     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4352   } else {
4353     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4354   }
4355 
4356   if (HasChain) {
4357     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4358     if (OnlyLoad)
4359       PendingLoads.push_back(Chain);
4360     else
4361       DAG.setRoot(Chain);
4362   }
4363 
4364   if (!I.getType()->isVoidTy()) {
4365     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4366       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4367       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4368     } else
4369       Result = lowerRangeToAssertZExt(DAG, I, Result);
4370 
4371     setValue(&I, Result);
4372   }
4373 }
4374 
4375 /// GetSignificand - Get the significand and build it into a floating-point
4376 /// number with exponent of 1:
4377 ///
4378 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4379 ///
4380 /// where Op is the hexadecimal representation of floating point value.
4381 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4382   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4383                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4384   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4385                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4386   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4387 }
4388 
4389 /// GetExponent - Get the exponent:
4390 ///
4391 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4392 ///
4393 /// where Op is the hexadecimal representation of floating point value.
4394 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4395                            const TargetLowering &TLI, const SDLoc &dl) {
4396   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4397                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4398   SDValue t1 = DAG.getNode(
4399       ISD::SRL, dl, MVT::i32, t0,
4400       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4401   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4402                            DAG.getConstant(127, dl, MVT::i32));
4403   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4404 }
4405 
4406 /// getF32Constant - Get 32-bit floating point constant.
4407 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4408                               const SDLoc &dl) {
4409   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4410                            MVT::f32);
4411 }
4412 
4413 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4414                                        SelectionDAG &DAG) {
4415   // TODO: What fast-math-flags should be set on the floating-point nodes?
4416 
4417   //   IntegerPartOfX = ((int32_t)(t0);
4418   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4419 
4420   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4421   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4422   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4423 
4424   //   IntegerPartOfX <<= 23;
4425   IntegerPartOfX = DAG.getNode(
4426       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4427       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4428                                   DAG.getDataLayout())));
4429 
4430   SDValue TwoToFractionalPartOfX;
4431   if (LimitFloatPrecision <= 6) {
4432     // For floating-point precision of 6:
4433     //
4434     //   TwoToFractionalPartOfX =
4435     //     0.997535578f +
4436     //       (0.735607626f + 0.252464424f * x) * x;
4437     //
4438     // error 0.0144103317, which is 6 bits
4439     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4440                              getF32Constant(DAG, 0x3e814304, dl));
4441     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4442                              getF32Constant(DAG, 0x3f3c50c8, dl));
4443     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4444     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4445                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4446   } else if (LimitFloatPrecision <= 12) {
4447     // For floating-point precision of 12:
4448     //
4449     //   TwoToFractionalPartOfX =
4450     //     0.999892986f +
4451     //       (0.696457318f +
4452     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4453     //
4454     // error 0.000107046256, which is 13 to 14 bits
4455     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4456                              getF32Constant(DAG, 0x3da235e3, dl));
4457     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4458                              getF32Constant(DAG, 0x3e65b8f3, dl));
4459     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4460     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4461                              getF32Constant(DAG, 0x3f324b07, dl));
4462     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4463     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4464                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4465   } else { // LimitFloatPrecision <= 18
4466     // For floating-point precision of 18:
4467     //
4468     //   TwoToFractionalPartOfX =
4469     //     0.999999982f +
4470     //       (0.693148872f +
4471     //         (0.240227044f +
4472     //           (0.554906021e-1f +
4473     //             (0.961591928e-2f +
4474     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4475     // error 2.47208000*10^(-7), which is better than 18 bits
4476     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4477                              getF32Constant(DAG, 0x3924b03e, dl));
4478     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4479                              getF32Constant(DAG, 0x3ab24b87, dl));
4480     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4481     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4482                              getF32Constant(DAG, 0x3c1d8c17, dl));
4483     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4484     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4485                              getF32Constant(DAG, 0x3d634a1d, dl));
4486     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4487     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4488                              getF32Constant(DAG, 0x3e75fe14, dl));
4489     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4490     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4491                               getF32Constant(DAG, 0x3f317234, dl));
4492     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4493     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4494                                          getF32Constant(DAG, 0x3f800000, dl));
4495   }
4496 
4497   // Add the exponent into the result in integer domain.
4498   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4499   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4500                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4501 }
4502 
4503 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4504 /// limited-precision mode.
4505 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4506                          const TargetLowering &TLI) {
4507   if (Op.getValueType() == MVT::f32 &&
4508       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4509 
4510     // Put the exponent in the right bit position for later addition to the
4511     // final result:
4512     //
4513     //   #define LOG2OFe 1.4426950f
4514     //   t0 = Op * LOG2OFe
4515 
4516     // TODO: What fast-math-flags should be set here?
4517     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4518                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4519     return getLimitedPrecisionExp2(t0, dl, DAG);
4520   }
4521 
4522   // No special expansion.
4523   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4524 }
4525 
4526 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4527 /// limited-precision mode.
4528 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4529                          const TargetLowering &TLI) {
4530   // TODO: What fast-math-flags should be set on the floating-point nodes?
4531 
4532   if (Op.getValueType() == MVT::f32 &&
4533       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4534     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4535 
4536     // Scale the exponent by log(2) [0.69314718f].
4537     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4538     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4539                                         getF32Constant(DAG, 0x3f317218, 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     SDValue LogOfMantissa;
4546     if (LimitFloatPrecision <= 6) {
4547       // For floating-point precision of 6:
4548       //
4549       //   LogofMantissa =
4550       //     -1.1609546f +
4551       //       (1.4034025f - 0.23903021f * x) * x;
4552       //
4553       // error 0.0034276066, which is better than 8 bits
4554       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4555                                getF32Constant(DAG, 0xbe74c456, dl));
4556       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4557                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4558       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4559       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4560                                   getF32Constant(DAG, 0x3f949a29, dl));
4561     } else if (LimitFloatPrecision <= 12) {
4562       // For floating-point precision of 12:
4563       //
4564       //   LogOfMantissa =
4565       //     -1.7417939f +
4566       //       (2.8212026f +
4567       //         (-1.4699568f +
4568       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4569       //
4570       // error 0.000061011436, which is 14 bits
4571       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4572                                getF32Constant(DAG, 0xbd67b6d6, dl));
4573       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4574                                getF32Constant(DAG, 0x3ee4f4b8, 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, 0x3fbc278b, 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, 0x40348e95, dl));
4581       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4582       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4583                                   getF32Constant(DAG, 0x3fdef31a, dl));
4584     } else { // LimitFloatPrecision <= 18
4585       // For floating-point precision of 18:
4586       //
4587       //   LogOfMantissa =
4588       //     -2.1072184f +
4589       //       (4.2372794f +
4590       //         (-3.7029485f +
4591       //           (2.2781945f +
4592       //             (-0.87823314f +
4593       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4594       //
4595       // error 0.0000023660568, which is better than 18 bits
4596       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4597                                getF32Constant(DAG, 0xbc91e5ac, dl));
4598       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4599                                getF32Constant(DAG, 0x3e4350aa, dl));
4600       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4601       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4602                                getF32Constant(DAG, 0x3f60d3e3, dl));
4603       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4604       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4605                                getF32Constant(DAG, 0x4011cdf0, dl));
4606       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4607       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4608                                getF32Constant(DAG, 0x406cfd1c, dl));
4609       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4610       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4611                                getF32Constant(DAG, 0x408797cb, dl));
4612       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4613       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4614                                   getF32Constant(DAG, 0x4006dcab, dl));
4615     }
4616 
4617     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4618   }
4619 
4620   // No special expansion.
4621   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4622 }
4623 
4624 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4625 /// limited-precision mode.
4626 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4627                           const TargetLowering &TLI) {
4628   // TODO: What fast-math-flags should be set on the floating-point nodes?
4629 
4630   if (Op.getValueType() == MVT::f32 &&
4631       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4632     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4633 
4634     // Get the exponent.
4635     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4636 
4637     // Get the significand and build it into a floating-point number with
4638     // exponent of 1.
4639     SDValue X = GetSignificand(DAG, Op1, dl);
4640 
4641     // Different possible minimax approximations of significand in
4642     // floating-point for various degrees of accuracy over [1,2].
4643     SDValue Log2ofMantissa;
4644     if (LimitFloatPrecision <= 6) {
4645       // For floating-point precision of 6:
4646       //
4647       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4648       //
4649       // error 0.0049451742, which is more than 7 bits
4650       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4651                                getF32Constant(DAG, 0xbeb08fe0, dl));
4652       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4653                                getF32Constant(DAG, 0x40019463, dl));
4654       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4655       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4656                                    getF32Constant(DAG, 0x3fd6633d, dl));
4657     } else if (LimitFloatPrecision <= 12) {
4658       // For floating-point precision of 12:
4659       //
4660       //   Log2ofMantissa =
4661       //     -2.51285454f +
4662       //       (4.07009056f +
4663       //         (-2.12067489f +
4664       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4665       //
4666       // error 0.0000876136000, which is better than 13 bits
4667       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4668                                getF32Constant(DAG, 0xbda7262e, dl));
4669       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4670                                getF32Constant(DAG, 0x3f25280b, dl));
4671       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4672       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4673                                getF32Constant(DAG, 0x4007b923, dl));
4674       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4675       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4676                                getF32Constant(DAG, 0x40823e2f, dl));
4677       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4678       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4679                                    getF32Constant(DAG, 0x4020d29c, dl));
4680     } else { // LimitFloatPrecision <= 18
4681       // For floating-point precision of 18:
4682       //
4683       //   Log2ofMantissa =
4684       //     -3.0400495f +
4685       //       (6.1129976f +
4686       //         (-5.3420409f +
4687       //           (3.2865683f +
4688       //             (-1.2669343f +
4689       //               (0.27515199f -
4690       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4691       //
4692       // error 0.0000018516, which is better than 18 bits
4693       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4694                                getF32Constant(DAG, 0xbcd2769e, dl));
4695       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4696                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4697       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4698       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4699                                getF32Constant(DAG, 0x3fa22ae7, dl));
4700       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4701       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4702                                getF32Constant(DAG, 0x40525723, dl));
4703       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4704       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4705                                getF32Constant(DAG, 0x40aaf200, dl));
4706       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4707       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4708                                getF32Constant(DAG, 0x40c39dad, dl));
4709       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4710       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4711                                    getF32Constant(DAG, 0x4042902c, dl));
4712     }
4713 
4714     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4715   }
4716 
4717   // No special expansion.
4718   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4719 }
4720 
4721 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4722 /// limited-precision mode.
4723 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4724                            const TargetLowering &TLI) {
4725   // TODO: What fast-math-flags should be set on the floating-point nodes?
4726 
4727   if (Op.getValueType() == MVT::f32 &&
4728       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4729     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4730 
4731     // Scale the exponent by log10(2) [0.30102999f].
4732     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4733     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4734                                         getF32Constant(DAG, 0x3e9a209a, dl));
4735 
4736     // Get the significand and build it into a floating-point number with
4737     // exponent of 1.
4738     SDValue X = GetSignificand(DAG, Op1, dl);
4739 
4740     SDValue Log10ofMantissa;
4741     if (LimitFloatPrecision <= 6) {
4742       // For floating-point precision of 6:
4743       //
4744       //   Log10ofMantissa =
4745       //     -0.50419619f +
4746       //       (0.60948995f - 0.10380950f * x) * x;
4747       //
4748       // error 0.0014886165, which is 6 bits
4749       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4750                                getF32Constant(DAG, 0xbdd49a13, dl));
4751       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4752                                getF32Constant(DAG, 0x3f1c0789, dl));
4753       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4754       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4755                                     getF32Constant(DAG, 0x3f011300, dl));
4756     } else if (LimitFloatPrecision <= 12) {
4757       // For floating-point precision of 12:
4758       //
4759       //   Log10ofMantissa =
4760       //     -0.64831180f +
4761       //       (0.91751397f +
4762       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4763       //
4764       // error 0.00019228036, which is better than 12 bits
4765       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4766                                getF32Constant(DAG, 0x3d431f31, dl));
4767       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4768                                getF32Constant(DAG, 0x3ea21fb2, dl));
4769       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4770       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4771                                getF32Constant(DAG, 0x3f6ae232, dl));
4772       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4773       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4774                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4775     } else { // LimitFloatPrecision <= 18
4776       // For floating-point precision of 18:
4777       //
4778       //   Log10ofMantissa =
4779       //     -0.84299375f +
4780       //       (1.5327582f +
4781       //         (-1.0688956f +
4782       //           (0.49102474f +
4783       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4784       //
4785       // error 0.0000037995730, which is better than 18 bits
4786       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4787                                getF32Constant(DAG, 0x3c5d51ce, dl));
4788       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4789                                getF32Constant(DAG, 0x3e00685a, dl));
4790       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4791       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4792                                getF32Constant(DAG, 0x3efb6798, dl));
4793       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4794       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4795                                getF32Constant(DAG, 0x3f88d192, dl));
4796       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4797       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4798                                getF32Constant(DAG, 0x3fc4316c, dl));
4799       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4800       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4801                                     getF32Constant(DAG, 0x3f57ce70, dl));
4802     }
4803 
4804     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4805   }
4806 
4807   // No special expansion.
4808   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4809 }
4810 
4811 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4812 /// limited-precision mode.
4813 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4814                           const TargetLowering &TLI) {
4815   if (Op.getValueType() == MVT::f32 &&
4816       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4817     return getLimitedPrecisionExp2(Op, dl, DAG);
4818 
4819   // No special expansion.
4820   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4821 }
4822 
4823 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4824 /// limited-precision mode with x == 10.0f.
4825 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4826                          SelectionDAG &DAG, const TargetLowering &TLI) {
4827   bool IsExp10 = false;
4828   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4829       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4830     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4831       APFloat Ten(10.0f);
4832       IsExp10 = LHSC->isExactlyValue(Ten);
4833     }
4834   }
4835 
4836   // TODO: What fast-math-flags should be set on the FMUL node?
4837   if (IsExp10) {
4838     // Put the exponent in the right bit position for later addition to the
4839     // final result:
4840     //
4841     //   #define LOG2OF10 3.3219281f
4842     //   t0 = Op * LOG2OF10;
4843     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4844                              getF32Constant(DAG, 0x40549a78, dl));
4845     return getLimitedPrecisionExp2(t0, dl, DAG);
4846   }
4847 
4848   // No special expansion.
4849   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4850 }
4851 
4852 /// ExpandPowI - Expand a llvm.powi intrinsic.
4853 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4854                           SelectionDAG &DAG) {
4855   // If RHS is a constant, we can expand this out to a multiplication tree,
4856   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4857   // optimizing for size, we only want to do this if the expansion would produce
4858   // a small number of multiplies, otherwise we do the full expansion.
4859   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4860     // Get the exponent as a positive value.
4861     unsigned Val = RHSC->getSExtValue();
4862     if ((int)Val < 0) Val = -Val;
4863 
4864     // powi(x, 0) -> 1.0
4865     if (Val == 0)
4866       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4867 
4868     const Function &F = DAG.getMachineFunction().getFunction();
4869     if (!F.optForSize() ||
4870         // If optimizing for size, don't insert too many multiplies.
4871         // This inserts up to 5 multiplies.
4872         countPopulation(Val) + Log2_32(Val) < 7) {
4873       // We use the simple binary decomposition method to generate the multiply
4874       // sequence.  There are more optimal ways to do this (for example,
4875       // powi(x,15) generates one more multiply than it should), but this has
4876       // the benefit of being both really simple and much better than a libcall.
4877       SDValue Res;  // Logically starts equal to 1.0
4878       SDValue CurSquare = LHS;
4879       // TODO: Intrinsics should have fast-math-flags that propagate to these
4880       // nodes.
4881       while (Val) {
4882         if (Val & 1) {
4883           if (Res.getNode())
4884             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4885           else
4886             Res = CurSquare;  // 1.0*CurSquare.
4887         }
4888 
4889         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4890                                 CurSquare, CurSquare);
4891         Val >>= 1;
4892       }
4893 
4894       // If the original was negative, invert the result, producing 1/(x*x*x).
4895       if (RHSC->getSExtValue() < 0)
4896         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4897                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4898       return Res;
4899     }
4900   }
4901 
4902   // Otherwise, expand to a libcall.
4903   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4904 }
4905 
4906 // getUnderlyingArgReg - Find underlying register used for a truncated or
4907 // bitcasted argument.
4908 static unsigned getUnderlyingArgReg(const SDValue &N) {
4909   switch (N.getOpcode()) {
4910   case ISD::CopyFromReg:
4911     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4912   case ISD::BITCAST:
4913   case ISD::AssertZext:
4914   case ISD::AssertSext:
4915   case ISD::TRUNCATE:
4916     return getUnderlyingArgReg(N.getOperand(0));
4917   default:
4918     return 0;
4919   }
4920 }
4921 
4922 /// If the DbgValueInst is a dbg_value of a function argument, create the
4923 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4924 /// instruction selection, they will be inserted to the entry BB.
4925 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4926     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4927     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4928   const Argument *Arg = dyn_cast<Argument>(V);
4929   if (!Arg)
4930     return false;
4931 
4932   MachineFunction &MF = DAG.getMachineFunction();
4933   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4934 
4935   bool IsIndirect = false;
4936   Optional<MachineOperand> Op;
4937   // Some arguments' frame index is recorded during argument lowering.
4938   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4939   if (FI != std::numeric_limits<int>::max())
4940     Op = MachineOperand::CreateFI(FI);
4941 
4942   if (!Op && N.getNode()) {
4943     unsigned Reg = getUnderlyingArgReg(N);
4944     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4945       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4946       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4947       if (PR)
4948         Reg = PR;
4949     }
4950     if (Reg) {
4951       Op = MachineOperand::CreateReg(Reg, false);
4952       IsIndirect = IsDbgDeclare;
4953     }
4954   }
4955 
4956   if (!Op && N.getNode())
4957     // Check if frame index is available.
4958     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4959       if (FrameIndexSDNode *FINode =
4960           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4961         Op = MachineOperand::CreateFI(FINode->getIndex());
4962 
4963   if (!Op) {
4964     // Check if ValueMap has reg number.
4965     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4966     if (VMI != FuncInfo.ValueMap.end()) {
4967       const auto &TLI = DAG.getTargetLoweringInfo();
4968       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4969                        V->getType(), getABIRegCopyCC(V));
4970       if (RFV.occupiesMultipleRegs()) {
4971         unsigned Offset = 0;
4972         for (auto RegAndSize : RFV.getRegsAndSizes()) {
4973           Op = MachineOperand::CreateReg(RegAndSize.first, false);
4974           auto FragmentExpr = DIExpression::createFragmentExpression(
4975               Expr, Offset, RegAndSize.second);
4976           if (!FragmentExpr)
4977             continue;
4978           FuncInfo.ArgDbgValues.push_back(
4979               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4980                       Op->getReg(), Variable, *FragmentExpr));
4981           Offset += RegAndSize.second;
4982         }
4983         return true;
4984       }
4985       Op = MachineOperand::CreateReg(VMI->second, false);
4986       IsIndirect = IsDbgDeclare;
4987     }
4988   }
4989 
4990   if (!Op)
4991     return false;
4992 
4993   assert(Variable->isValidLocationForIntrinsic(DL) &&
4994          "Expected inlined-at fields to agree");
4995   IsIndirect = (Op->isReg()) ? IsIndirect : true;
4996   FuncInfo.ArgDbgValues.push_back(
4997       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4998               *Op, Variable, Expr));
4999 
5000   return true;
5001 }
5002 
5003 /// Return the appropriate SDDbgValue based on N.
5004 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5005                                              DILocalVariable *Variable,
5006                                              DIExpression *Expr,
5007                                              const DebugLoc &dl,
5008                                              unsigned DbgSDNodeOrder) {
5009   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5010     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5011     // stack slot locations.
5012     //
5013     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5014     // debug values here after optimization:
5015     //
5016     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5017     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5018     //
5019     // Both describe the direct values of their associated variables.
5020     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5021                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5022   }
5023   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5024                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5025 }
5026 
5027 // VisualStudio defines setjmp as _setjmp
5028 #if defined(_MSC_VER) && defined(setjmp) && \
5029                          !defined(setjmp_undefined_for_msvc)
5030 #  pragma push_macro("setjmp")
5031 #  undef setjmp
5032 #  define setjmp_undefined_for_msvc
5033 #endif
5034 
5035 /// Lower the call to the specified intrinsic function. If we want to emit this
5036 /// as a call to a named external function, return the name. Otherwise, lower it
5037 /// and return null.
5038 const char *
5039 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5041   SDLoc sdl = getCurSDLoc();
5042   DebugLoc dl = getCurDebugLoc();
5043   SDValue Res;
5044 
5045   switch (Intrinsic) {
5046   default:
5047     // By default, turn this into a target intrinsic node.
5048     visitTargetIntrinsic(I, Intrinsic);
5049     return nullptr;
5050   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5051   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5052   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5053   case Intrinsic::returnaddress:
5054     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5055                              TLI.getPointerTy(DAG.getDataLayout()),
5056                              getValue(I.getArgOperand(0))));
5057     return nullptr;
5058   case Intrinsic::addressofreturnaddress:
5059     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5060                              TLI.getPointerTy(DAG.getDataLayout())));
5061     return nullptr;
5062   case Intrinsic::sponentry:
5063     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5064                              TLI.getPointerTy(DAG.getDataLayout())));
5065     return nullptr;
5066   case Intrinsic::frameaddress:
5067     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5068                              TLI.getPointerTy(DAG.getDataLayout()),
5069                              getValue(I.getArgOperand(0))));
5070     return nullptr;
5071   case Intrinsic::read_register: {
5072     Value *Reg = I.getArgOperand(0);
5073     SDValue Chain = getRoot();
5074     SDValue RegName =
5075         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5076     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5077     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5078       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5079     setValue(&I, Res);
5080     DAG.setRoot(Res.getValue(1));
5081     return nullptr;
5082   }
5083   case Intrinsic::write_register: {
5084     Value *Reg = I.getArgOperand(0);
5085     Value *RegValue = I.getArgOperand(1);
5086     SDValue Chain = getRoot();
5087     SDValue RegName =
5088         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5089     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5090                             RegName, getValue(RegValue)));
5091     return nullptr;
5092   }
5093   case Intrinsic::setjmp:
5094     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5095   case Intrinsic::longjmp:
5096     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5097   case Intrinsic::memcpy: {
5098     const auto &MCI = cast<MemCpyInst>(I);
5099     SDValue Op1 = getValue(I.getArgOperand(0));
5100     SDValue Op2 = getValue(I.getArgOperand(1));
5101     SDValue Op3 = getValue(I.getArgOperand(2));
5102     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5103     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5104     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5105     unsigned Align = MinAlign(DstAlign, SrcAlign);
5106     bool isVol = MCI.isVolatile();
5107     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5108     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5109     // node.
5110     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5111                                false, isTC,
5112                                MachinePointerInfo(I.getArgOperand(0)),
5113                                MachinePointerInfo(I.getArgOperand(1)));
5114     updateDAGForMaybeTailCall(MC);
5115     return nullptr;
5116   }
5117   case Intrinsic::memset: {
5118     const auto &MSI = cast<MemSetInst>(I);
5119     SDValue Op1 = getValue(I.getArgOperand(0));
5120     SDValue Op2 = getValue(I.getArgOperand(1));
5121     SDValue Op3 = getValue(I.getArgOperand(2));
5122     // @llvm.memset defines 0 and 1 to both mean no alignment.
5123     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5124     bool isVol = MSI.isVolatile();
5125     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5126     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5127                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5128     updateDAGForMaybeTailCall(MS);
5129     return nullptr;
5130   }
5131   case Intrinsic::memmove: {
5132     const auto &MMI = cast<MemMoveInst>(I);
5133     SDValue Op1 = getValue(I.getArgOperand(0));
5134     SDValue Op2 = getValue(I.getArgOperand(1));
5135     SDValue Op3 = getValue(I.getArgOperand(2));
5136     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5137     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5138     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5139     unsigned Align = MinAlign(DstAlign, SrcAlign);
5140     bool isVol = MMI.isVolatile();
5141     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5142     // FIXME: Support passing different dest/src alignments to the memmove DAG
5143     // node.
5144     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5145                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5146                                 MachinePointerInfo(I.getArgOperand(1)));
5147     updateDAGForMaybeTailCall(MM);
5148     return nullptr;
5149   }
5150   case Intrinsic::memcpy_element_unordered_atomic: {
5151     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5152     SDValue Dst = getValue(MI.getRawDest());
5153     SDValue Src = getValue(MI.getRawSource());
5154     SDValue Length = getValue(MI.getLength());
5155 
5156     unsigned DstAlign = MI.getDestAlignment();
5157     unsigned SrcAlign = MI.getSourceAlignment();
5158     Type *LengthTy = MI.getLength()->getType();
5159     unsigned ElemSz = MI.getElementSizeInBytes();
5160     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5161     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5162                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5163                                      MachinePointerInfo(MI.getRawDest()),
5164                                      MachinePointerInfo(MI.getRawSource()));
5165     updateDAGForMaybeTailCall(MC);
5166     return nullptr;
5167   }
5168   case Intrinsic::memmove_element_unordered_atomic: {
5169     auto &MI = cast<AtomicMemMoveInst>(I);
5170     SDValue Dst = getValue(MI.getRawDest());
5171     SDValue Src = getValue(MI.getRawSource());
5172     SDValue Length = getValue(MI.getLength());
5173 
5174     unsigned DstAlign = MI.getDestAlignment();
5175     unsigned SrcAlign = MI.getSourceAlignment();
5176     Type *LengthTy = MI.getLength()->getType();
5177     unsigned ElemSz = MI.getElementSizeInBytes();
5178     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5179     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5180                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5181                                       MachinePointerInfo(MI.getRawDest()),
5182                                       MachinePointerInfo(MI.getRawSource()));
5183     updateDAGForMaybeTailCall(MC);
5184     return nullptr;
5185   }
5186   case Intrinsic::memset_element_unordered_atomic: {
5187     auto &MI = cast<AtomicMemSetInst>(I);
5188     SDValue Dst = getValue(MI.getRawDest());
5189     SDValue Val = getValue(MI.getValue());
5190     SDValue Length = getValue(MI.getLength());
5191 
5192     unsigned DstAlign = MI.getDestAlignment();
5193     Type *LengthTy = MI.getLength()->getType();
5194     unsigned ElemSz = MI.getElementSizeInBytes();
5195     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5196     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5197                                      LengthTy, ElemSz, isTC,
5198                                      MachinePointerInfo(MI.getRawDest()));
5199     updateDAGForMaybeTailCall(MC);
5200     return nullptr;
5201   }
5202   case Intrinsic::dbg_addr:
5203   case Intrinsic::dbg_declare: {
5204     const auto &DI = cast<DbgVariableIntrinsic>(I);
5205     DILocalVariable *Variable = DI.getVariable();
5206     DIExpression *Expression = DI.getExpression();
5207     dropDanglingDebugInfo(Variable, Expression);
5208     assert(Variable && "Missing variable");
5209 
5210     // Check if address has undef value.
5211     const Value *Address = DI.getVariableLocation();
5212     if (!Address || isa<UndefValue>(Address) ||
5213         (Address->use_empty() && !isa<Argument>(Address))) {
5214       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5215       return nullptr;
5216     }
5217 
5218     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5219 
5220     // Check if this variable can be described by a frame index, typically
5221     // either as a static alloca or a byval parameter.
5222     int FI = std::numeric_limits<int>::max();
5223     if (const auto *AI =
5224             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5225       if (AI->isStaticAlloca()) {
5226         auto I = FuncInfo.StaticAllocaMap.find(AI);
5227         if (I != FuncInfo.StaticAllocaMap.end())
5228           FI = I->second;
5229       }
5230     } else if (const auto *Arg = dyn_cast<Argument>(
5231                    Address->stripInBoundsConstantOffsets())) {
5232       FI = FuncInfo.getArgumentFrameIndex(Arg);
5233     }
5234 
5235     // llvm.dbg.addr is control dependent and always generates indirect
5236     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5237     // the MachineFunction variable table.
5238     if (FI != std::numeric_limits<int>::max()) {
5239       if (Intrinsic == Intrinsic::dbg_addr) {
5240         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5241             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5242         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5243       }
5244       return nullptr;
5245     }
5246 
5247     SDValue &N = NodeMap[Address];
5248     if (!N.getNode() && isa<Argument>(Address))
5249       // Check unused arguments map.
5250       N = UnusedArgNodeMap[Address];
5251     SDDbgValue *SDV;
5252     if (N.getNode()) {
5253       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5254         Address = BCI->getOperand(0);
5255       // Parameters are handled specially.
5256       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5257       if (isParameter && FINode) {
5258         // Byval parameter. We have a frame index at this point.
5259         SDV =
5260             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5261                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5262       } else if (isa<Argument>(Address)) {
5263         // Address is an argument, so try to emit its dbg value using
5264         // virtual register info from the FuncInfo.ValueMap.
5265         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5266         return nullptr;
5267       } else {
5268         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5269                               true, dl, SDNodeOrder);
5270       }
5271       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5272     } else {
5273       // If Address is an argument then try to emit its dbg value using
5274       // virtual register info from the FuncInfo.ValueMap.
5275       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5276                                     N)) {
5277         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5278       }
5279     }
5280     return nullptr;
5281   }
5282   case Intrinsic::dbg_label: {
5283     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5284     DILabel *Label = DI.getLabel();
5285     assert(Label && "Missing label");
5286 
5287     SDDbgLabel *SDV;
5288     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5289     DAG.AddDbgLabel(SDV);
5290     return nullptr;
5291   }
5292   case Intrinsic::dbg_value: {
5293     const DbgValueInst &DI = cast<DbgValueInst>(I);
5294     assert(DI.getVariable() && "Missing variable");
5295 
5296     DILocalVariable *Variable = DI.getVariable();
5297     DIExpression *Expression = DI.getExpression();
5298     dropDanglingDebugInfo(Variable, Expression);
5299     const Value *V = DI.getValue();
5300     if (!V)
5301       return nullptr;
5302 
5303     SDDbgValue *SDV;
5304     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
5305       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5306       DAG.AddDbgValue(SDV, nullptr, false);
5307       return nullptr;
5308     }
5309 
5310     // Do not use getValue() in here; we don't want to generate code at
5311     // this point if it hasn't been done yet.
5312     SDValue N = NodeMap[V];
5313     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5314       N = UnusedArgNodeMap[V];
5315     if (N.getNode()) {
5316       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5317         return nullptr;
5318       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5319       DAG.AddDbgValue(SDV, N.getNode(), false);
5320       return nullptr;
5321     }
5322 
5323     // PHI nodes have already been selected, so we should know which VReg that
5324     // is assigns to already.
5325     if (isa<PHINode>(V)) {
5326       auto VMI = FuncInfo.ValueMap.find(V);
5327       if (VMI != FuncInfo.ValueMap.end()) {
5328         unsigned Reg = VMI->second;
5329         // The PHI node may be split up into several MI PHI nodes (in
5330         // FunctionLoweringInfo::set).
5331         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5332                          V->getType(), None);
5333         if (RFV.occupiesMultipleRegs()) {
5334           unsigned Offset = 0;
5335           unsigned BitsToDescribe = 0;
5336           if (auto VarSize = Variable->getSizeInBits())
5337             BitsToDescribe = *VarSize;
5338           if (auto Fragment = Expression->getFragmentInfo())
5339             BitsToDescribe = Fragment->SizeInBits;
5340           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5341             unsigned RegisterSize = RegAndSize.second;
5342             // Bail out if all bits are described already.
5343             if (Offset >= BitsToDescribe)
5344               break;
5345             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5346                 ? BitsToDescribe - Offset
5347                 : RegisterSize;
5348             auto FragmentExpr = DIExpression::createFragmentExpression(
5349                 Expression, Offset, FragmentSize);
5350             if (!FragmentExpr)
5351                 continue;
5352             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5353                                       false, dl, SDNodeOrder);
5354             DAG.AddDbgValue(SDV, nullptr, false);
5355             Offset += RegisterSize;
5356           }
5357         } else {
5358           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5359                                     SDNodeOrder);
5360           DAG.AddDbgValue(SDV, nullptr, false);
5361         }
5362         return nullptr;
5363       }
5364     }
5365 
5366     // TODO: When we get here we will either drop the dbg.value completely, or
5367     // we try to move it forward by letting it dangle for awhile. So we should
5368     // probably add an extra DbgValue to the DAG here, with a reference to
5369     // "noreg", to indicate that we have lost the debug location for the
5370     // variable.
5371 
5372     if (!V->use_empty() ) {
5373       // Do not call getValue(V) yet, as we don't want to generate code.
5374       // Remember it for later.
5375       DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5376       return nullptr;
5377     }
5378 
5379     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5380     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5381     return nullptr;
5382   }
5383 
5384   case Intrinsic::eh_typeid_for: {
5385     // Find the type id for the given typeinfo.
5386     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5387     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5388     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5389     setValue(&I, Res);
5390     return nullptr;
5391   }
5392 
5393   case Intrinsic::eh_return_i32:
5394   case Intrinsic::eh_return_i64:
5395     DAG.getMachineFunction().setCallsEHReturn(true);
5396     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5397                             MVT::Other,
5398                             getControlRoot(),
5399                             getValue(I.getArgOperand(0)),
5400                             getValue(I.getArgOperand(1))));
5401     return nullptr;
5402   case Intrinsic::eh_unwind_init:
5403     DAG.getMachineFunction().setCallsUnwindInit(true);
5404     return nullptr;
5405   case Intrinsic::eh_dwarf_cfa:
5406     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5407                              TLI.getPointerTy(DAG.getDataLayout()),
5408                              getValue(I.getArgOperand(0))));
5409     return nullptr;
5410   case Intrinsic::eh_sjlj_callsite: {
5411     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5412     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5413     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5414     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5415 
5416     MMI.setCurrentCallSite(CI->getZExtValue());
5417     return nullptr;
5418   }
5419   case Intrinsic::eh_sjlj_functioncontext: {
5420     // Get and store the index of the function context.
5421     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5422     AllocaInst *FnCtx =
5423       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5424     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5425     MFI.setFunctionContextIndex(FI);
5426     return nullptr;
5427   }
5428   case Intrinsic::eh_sjlj_setjmp: {
5429     SDValue Ops[2];
5430     Ops[0] = getRoot();
5431     Ops[1] = getValue(I.getArgOperand(0));
5432     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5433                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5434     setValue(&I, Op.getValue(0));
5435     DAG.setRoot(Op.getValue(1));
5436     return nullptr;
5437   }
5438   case Intrinsic::eh_sjlj_longjmp:
5439     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5440                             getRoot(), getValue(I.getArgOperand(0))));
5441     return nullptr;
5442   case Intrinsic::eh_sjlj_setup_dispatch:
5443     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5444                             getRoot()));
5445     return nullptr;
5446   case Intrinsic::masked_gather:
5447     visitMaskedGather(I);
5448     return nullptr;
5449   case Intrinsic::masked_load:
5450     visitMaskedLoad(I);
5451     return nullptr;
5452   case Intrinsic::masked_scatter:
5453     visitMaskedScatter(I);
5454     return nullptr;
5455   case Intrinsic::masked_store:
5456     visitMaskedStore(I);
5457     return nullptr;
5458   case Intrinsic::masked_expandload:
5459     visitMaskedLoad(I, true /* IsExpanding */);
5460     return nullptr;
5461   case Intrinsic::masked_compressstore:
5462     visitMaskedStore(I, true /* IsCompressing */);
5463     return nullptr;
5464   case Intrinsic::x86_mmx_pslli_w:
5465   case Intrinsic::x86_mmx_pslli_d:
5466   case Intrinsic::x86_mmx_pslli_q:
5467   case Intrinsic::x86_mmx_psrli_w:
5468   case Intrinsic::x86_mmx_psrli_d:
5469   case Intrinsic::x86_mmx_psrli_q:
5470   case Intrinsic::x86_mmx_psrai_w:
5471   case Intrinsic::x86_mmx_psrai_d: {
5472     SDValue ShAmt = getValue(I.getArgOperand(1));
5473     if (isa<ConstantSDNode>(ShAmt)) {
5474       visitTargetIntrinsic(I, Intrinsic);
5475       return nullptr;
5476     }
5477     unsigned NewIntrinsic = 0;
5478     EVT ShAmtVT = MVT::v2i32;
5479     switch (Intrinsic) {
5480     case Intrinsic::x86_mmx_pslli_w:
5481       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5482       break;
5483     case Intrinsic::x86_mmx_pslli_d:
5484       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5485       break;
5486     case Intrinsic::x86_mmx_pslli_q:
5487       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5488       break;
5489     case Intrinsic::x86_mmx_psrli_w:
5490       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5491       break;
5492     case Intrinsic::x86_mmx_psrli_d:
5493       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5494       break;
5495     case Intrinsic::x86_mmx_psrli_q:
5496       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5497       break;
5498     case Intrinsic::x86_mmx_psrai_w:
5499       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5500       break;
5501     case Intrinsic::x86_mmx_psrai_d:
5502       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5503       break;
5504     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5505     }
5506 
5507     // The vector shift intrinsics with scalars uses 32b shift amounts but
5508     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5509     // to be zero.
5510     // We must do this early because v2i32 is not a legal type.
5511     SDValue ShOps[2];
5512     ShOps[0] = ShAmt;
5513     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5514     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5515     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5516     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5517     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5518                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5519                        getValue(I.getArgOperand(0)), ShAmt);
5520     setValue(&I, Res);
5521     return nullptr;
5522   }
5523   case Intrinsic::powi:
5524     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5525                             getValue(I.getArgOperand(1)), DAG));
5526     return nullptr;
5527   case Intrinsic::log:
5528     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5529     return nullptr;
5530   case Intrinsic::log2:
5531     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5532     return nullptr;
5533   case Intrinsic::log10:
5534     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5535     return nullptr;
5536   case Intrinsic::exp:
5537     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5538     return nullptr;
5539   case Intrinsic::exp2:
5540     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5541     return nullptr;
5542   case Intrinsic::pow:
5543     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5544                            getValue(I.getArgOperand(1)), DAG, TLI));
5545     return nullptr;
5546   case Intrinsic::sqrt:
5547   case Intrinsic::fabs:
5548   case Intrinsic::sin:
5549   case Intrinsic::cos:
5550   case Intrinsic::floor:
5551   case Intrinsic::ceil:
5552   case Intrinsic::trunc:
5553   case Intrinsic::rint:
5554   case Intrinsic::nearbyint:
5555   case Intrinsic::round:
5556   case Intrinsic::canonicalize: {
5557     unsigned Opcode;
5558     switch (Intrinsic) {
5559     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5560     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5561     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5562     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5563     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5564     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5565     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5566     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5567     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5568     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5569     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5570     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5571     }
5572 
5573     setValue(&I, DAG.getNode(Opcode, sdl,
5574                              getValue(I.getArgOperand(0)).getValueType(),
5575                              getValue(I.getArgOperand(0))));
5576     return nullptr;
5577   }
5578   case Intrinsic::minnum: {
5579     auto VT = getValue(I.getArgOperand(0)).getValueType();
5580     unsigned Opc =
5581         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5582             ? ISD::FMINIMUM
5583             : ISD::FMINNUM;
5584     setValue(&I, DAG.getNode(Opc, sdl, VT,
5585                              getValue(I.getArgOperand(0)),
5586                              getValue(I.getArgOperand(1))));
5587     return nullptr;
5588   }
5589   case Intrinsic::maxnum: {
5590     auto VT = getValue(I.getArgOperand(0)).getValueType();
5591     unsigned Opc =
5592         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5593             ? ISD::FMAXIMUM
5594             : ISD::FMAXNUM;
5595     setValue(&I, DAG.getNode(Opc, sdl, VT,
5596                              getValue(I.getArgOperand(0)),
5597                              getValue(I.getArgOperand(1))));
5598     return nullptr;
5599   }
5600   case Intrinsic::minimum:
5601     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5602                              getValue(I.getArgOperand(0)).getValueType(),
5603                              getValue(I.getArgOperand(0)),
5604                              getValue(I.getArgOperand(1))));
5605     return nullptr;
5606   case Intrinsic::maximum:
5607     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5608                              getValue(I.getArgOperand(0)).getValueType(),
5609                              getValue(I.getArgOperand(0)),
5610                              getValue(I.getArgOperand(1))));
5611     return nullptr;
5612   case Intrinsic::copysign:
5613     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5614                              getValue(I.getArgOperand(0)).getValueType(),
5615                              getValue(I.getArgOperand(0)),
5616                              getValue(I.getArgOperand(1))));
5617     return nullptr;
5618   case Intrinsic::fma:
5619     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5620                              getValue(I.getArgOperand(0)).getValueType(),
5621                              getValue(I.getArgOperand(0)),
5622                              getValue(I.getArgOperand(1)),
5623                              getValue(I.getArgOperand(2))));
5624     return nullptr;
5625   case Intrinsic::experimental_constrained_fadd:
5626   case Intrinsic::experimental_constrained_fsub:
5627   case Intrinsic::experimental_constrained_fmul:
5628   case Intrinsic::experimental_constrained_fdiv:
5629   case Intrinsic::experimental_constrained_frem:
5630   case Intrinsic::experimental_constrained_fma:
5631   case Intrinsic::experimental_constrained_sqrt:
5632   case Intrinsic::experimental_constrained_pow:
5633   case Intrinsic::experimental_constrained_powi:
5634   case Intrinsic::experimental_constrained_sin:
5635   case Intrinsic::experimental_constrained_cos:
5636   case Intrinsic::experimental_constrained_exp:
5637   case Intrinsic::experimental_constrained_exp2:
5638   case Intrinsic::experimental_constrained_log:
5639   case Intrinsic::experimental_constrained_log10:
5640   case Intrinsic::experimental_constrained_log2:
5641   case Intrinsic::experimental_constrained_rint:
5642   case Intrinsic::experimental_constrained_nearbyint:
5643   case Intrinsic::experimental_constrained_maxnum:
5644   case Intrinsic::experimental_constrained_minnum:
5645   case Intrinsic::experimental_constrained_ceil:
5646   case Intrinsic::experimental_constrained_floor:
5647   case Intrinsic::experimental_constrained_round:
5648   case Intrinsic::experimental_constrained_trunc:
5649     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5650     return nullptr;
5651   case Intrinsic::fmuladd: {
5652     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5653     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5654         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5655       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5656                                getValue(I.getArgOperand(0)).getValueType(),
5657                                getValue(I.getArgOperand(0)),
5658                                getValue(I.getArgOperand(1)),
5659                                getValue(I.getArgOperand(2))));
5660     } else {
5661       // TODO: Intrinsic calls should have fast-math-flags.
5662       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5663                                 getValue(I.getArgOperand(0)).getValueType(),
5664                                 getValue(I.getArgOperand(0)),
5665                                 getValue(I.getArgOperand(1)));
5666       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5667                                 getValue(I.getArgOperand(0)).getValueType(),
5668                                 Mul,
5669                                 getValue(I.getArgOperand(2)));
5670       setValue(&I, Add);
5671     }
5672     return nullptr;
5673   }
5674   case Intrinsic::convert_to_fp16:
5675     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5676                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5677                                          getValue(I.getArgOperand(0)),
5678                                          DAG.getTargetConstant(0, sdl,
5679                                                                MVT::i32))));
5680     return nullptr;
5681   case Intrinsic::convert_from_fp16:
5682     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5683                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5684                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5685                                          getValue(I.getArgOperand(0)))));
5686     return nullptr;
5687   case Intrinsic::pcmarker: {
5688     SDValue Tmp = getValue(I.getArgOperand(0));
5689     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5690     return nullptr;
5691   }
5692   case Intrinsic::readcyclecounter: {
5693     SDValue Op = getRoot();
5694     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5695                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5696     setValue(&I, Res);
5697     DAG.setRoot(Res.getValue(1));
5698     return nullptr;
5699   }
5700   case Intrinsic::bitreverse:
5701     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5702                              getValue(I.getArgOperand(0)).getValueType(),
5703                              getValue(I.getArgOperand(0))));
5704     return nullptr;
5705   case Intrinsic::bswap:
5706     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5707                              getValue(I.getArgOperand(0)).getValueType(),
5708                              getValue(I.getArgOperand(0))));
5709     return nullptr;
5710   case Intrinsic::cttz: {
5711     SDValue Arg = getValue(I.getArgOperand(0));
5712     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5713     EVT Ty = Arg.getValueType();
5714     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5715                              sdl, Ty, Arg));
5716     return nullptr;
5717   }
5718   case Intrinsic::ctlz: {
5719     SDValue Arg = getValue(I.getArgOperand(0));
5720     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5721     EVT Ty = Arg.getValueType();
5722     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5723                              sdl, Ty, Arg));
5724     return nullptr;
5725   }
5726   case Intrinsic::ctpop: {
5727     SDValue Arg = getValue(I.getArgOperand(0));
5728     EVT Ty = Arg.getValueType();
5729     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5730     return nullptr;
5731   }
5732   case Intrinsic::fshl:
5733   case Intrinsic::fshr: {
5734     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5735     SDValue X = getValue(I.getArgOperand(0));
5736     SDValue Y = getValue(I.getArgOperand(1));
5737     SDValue Z = getValue(I.getArgOperand(2));
5738     EVT VT = X.getValueType();
5739     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5740     SDValue Zero = DAG.getConstant(0, sdl, VT);
5741     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5742 
5743     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
5744     // avoid the select that is necessary in the general case to filter out
5745     // the 0-shift possibility that leads to UB.
5746     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
5747       // TODO: This should also be done if the operation is custom, but we have
5748       // to make sure targets are handling the modulo shift amount as expected.
5749       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
5750       if (TLI.isOperationLegal(RotateOpcode, VT)) {
5751         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
5752         return nullptr;
5753       }
5754 
5755       // Some targets only rotate one way. Try the opposite direction.
5756       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
5757       if (TLI.isOperationLegal(RotateOpcode, VT)) {
5758         // Negate the shift amount because it is safe to ignore the high bits.
5759         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5760         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
5761         return nullptr;
5762       }
5763 
5764       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
5765       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
5766       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5767       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5768       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
5769       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
5770       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
5771       return nullptr;
5772     }
5773 
5774     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5775     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5776     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
5777     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5778     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5779     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5780 
5781     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5782     // and that is undefined. We must compare and select to avoid UB.
5783     EVT CCVT = MVT::i1;
5784     if (VT.isVector())
5785       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5786 
5787     // For fshl, 0-shift returns the 1st arg (X).
5788     // For fshr, 0-shift returns the 2nd arg (Y).
5789     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5790     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
5791     return nullptr;
5792   }
5793   case Intrinsic::sadd_sat: {
5794     SDValue Op1 = getValue(I.getArgOperand(0));
5795     SDValue Op2 = getValue(I.getArgOperand(1));
5796     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5797     return nullptr;
5798   }
5799   case Intrinsic::uadd_sat: {
5800     SDValue Op1 = getValue(I.getArgOperand(0));
5801     SDValue Op2 = getValue(I.getArgOperand(1));
5802     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5803     return nullptr;
5804   }
5805   case Intrinsic::ssub_sat: {
5806     SDValue Op1 = getValue(I.getArgOperand(0));
5807     SDValue Op2 = getValue(I.getArgOperand(1));
5808     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5809     return nullptr;
5810   }
5811   case Intrinsic::usub_sat: {
5812     SDValue Op1 = getValue(I.getArgOperand(0));
5813     SDValue Op2 = getValue(I.getArgOperand(1));
5814     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5815     return nullptr;
5816   }
5817   case Intrinsic::stacksave: {
5818     SDValue Op = getRoot();
5819     Res = DAG.getNode(
5820         ISD::STACKSAVE, sdl,
5821         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5822     setValue(&I, Res);
5823     DAG.setRoot(Res.getValue(1));
5824     return nullptr;
5825   }
5826   case Intrinsic::stackrestore:
5827     Res = getValue(I.getArgOperand(0));
5828     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5829     return nullptr;
5830   case Intrinsic::get_dynamic_area_offset: {
5831     SDValue Op = getRoot();
5832     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5833     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5834     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5835     // target.
5836     if (PtrTy != ResTy)
5837       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5838                          " intrinsic!");
5839     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5840                       Op);
5841     DAG.setRoot(Op);
5842     setValue(&I, Res);
5843     return nullptr;
5844   }
5845   case Intrinsic::stackguard: {
5846     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5847     MachineFunction &MF = DAG.getMachineFunction();
5848     const Module &M = *MF.getFunction().getParent();
5849     SDValue Chain = getRoot();
5850     if (TLI.useLoadStackGuardNode()) {
5851       Res = getLoadStackGuard(DAG, sdl, Chain);
5852     } else {
5853       const Value *Global = TLI.getSDagStackGuard(M);
5854       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5855       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5856                         MachinePointerInfo(Global, 0), Align,
5857                         MachineMemOperand::MOVolatile);
5858     }
5859     if (TLI.useStackGuardXorFP())
5860       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5861     DAG.setRoot(Chain);
5862     setValue(&I, Res);
5863     return nullptr;
5864   }
5865   case Intrinsic::stackprotector: {
5866     // Emit code into the DAG to store the stack guard onto the stack.
5867     MachineFunction &MF = DAG.getMachineFunction();
5868     MachineFrameInfo &MFI = MF.getFrameInfo();
5869     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5870     SDValue Src, Chain = getRoot();
5871 
5872     if (TLI.useLoadStackGuardNode())
5873       Src = getLoadStackGuard(DAG, sdl, Chain);
5874     else
5875       Src = getValue(I.getArgOperand(0));   // The guard's value.
5876 
5877     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5878 
5879     int FI = FuncInfo.StaticAllocaMap[Slot];
5880     MFI.setStackProtectorIndex(FI);
5881 
5882     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5883 
5884     // Store the stack protector onto the stack.
5885     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5886                                                  DAG.getMachineFunction(), FI),
5887                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5888     setValue(&I, Res);
5889     DAG.setRoot(Res);
5890     return nullptr;
5891   }
5892   case Intrinsic::objectsize: {
5893     // If we don't know by now, we're never going to know.
5894     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5895 
5896     assert(CI && "Non-constant type in __builtin_object_size?");
5897 
5898     SDValue Arg = getValue(I.getCalledValue());
5899     EVT Ty = Arg.getValueType();
5900 
5901     if (CI->isZero())
5902       Res = DAG.getConstant(-1ULL, sdl, Ty);
5903     else
5904       Res = DAG.getConstant(0, sdl, Ty);
5905 
5906     setValue(&I, Res);
5907     return nullptr;
5908   }
5909 
5910   case Intrinsic::is_constant:
5911     // If this wasn't constant-folded away by now, then it's not a
5912     // constant.
5913     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
5914     return nullptr;
5915 
5916   case Intrinsic::annotation:
5917   case Intrinsic::ptr_annotation:
5918   case Intrinsic::launder_invariant_group:
5919   case Intrinsic::strip_invariant_group:
5920     // Drop the intrinsic, but forward the value
5921     setValue(&I, getValue(I.getOperand(0)));
5922     return nullptr;
5923   case Intrinsic::assume:
5924   case Intrinsic::var_annotation:
5925   case Intrinsic::sideeffect:
5926     // Discard annotate attributes, assumptions, and artificial side-effects.
5927     return nullptr;
5928 
5929   case Intrinsic::codeview_annotation: {
5930     // Emit a label associated with this metadata.
5931     MachineFunction &MF = DAG.getMachineFunction();
5932     MCSymbol *Label =
5933         MF.getMMI().getContext().createTempSymbol("annotation", true);
5934     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5935     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5936     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5937     DAG.setRoot(Res);
5938     return nullptr;
5939   }
5940 
5941   case Intrinsic::init_trampoline: {
5942     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5943 
5944     SDValue Ops[6];
5945     Ops[0] = getRoot();
5946     Ops[1] = getValue(I.getArgOperand(0));
5947     Ops[2] = getValue(I.getArgOperand(1));
5948     Ops[3] = getValue(I.getArgOperand(2));
5949     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5950     Ops[5] = DAG.getSrcValue(F);
5951 
5952     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5953 
5954     DAG.setRoot(Res);
5955     return nullptr;
5956   }
5957   case Intrinsic::adjust_trampoline:
5958     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5959                              TLI.getPointerTy(DAG.getDataLayout()),
5960                              getValue(I.getArgOperand(0))));
5961     return nullptr;
5962   case Intrinsic::gcroot: {
5963     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5964            "only valid in functions with gc specified, enforced by Verifier");
5965     assert(GFI && "implied by previous");
5966     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5967     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5968 
5969     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5970     GFI->addStackRoot(FI->getIndex(), TypeMap);
5971     return nullptr;
5972   }
5973   case Intrinsic::gcread:
5974   case Intrinsic::gcwrite:
5975     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5976   case Intrinsic::flt_rounds:
5977     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5978     return nullptr;
5979 
5980   case Intrinsic::expect:
5981     // Just replace __builtin_expect(exp, c) with EXP.
5982     setValue(&I, getValue(I.getArgOperand(0)));
5983     return nullptr;
5984 
5985   case Intrinsic::debugtrap:
5986   case Intrinsic::trap: {
5987     StringRef TrapFuncName =
5988         I.getAttributes()
5989             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
5990             .getValueAsString();
5991     if (TrapFuncName.empty()) {
5992       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5993         ISD::TRAP : ISD::DEBUGTRAP;
5994       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5995       return nullptr;
5996     }
5997     TargetLowering::ArgListTy Args;
5998 
5999     TargetLowering::CallLoweringInfo CLI(DAG);
6000     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6001         CallingConv::C, I.getType(),
6002         DAG.getExternalSymbol(TrapFuncName.data(),
6003                               TLI.getPointerTy(DAG.getDataLayout())),
6004         std::move(Args));
6005 
6006     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6007     DAG.setRoot(Result.second);
6008     return nullptr;
6009   }
6010 
6011   case Intrinsic::uadd_with_overflow:
6012   case Intrinsic::sadd_with_overflow:
6013   case Intrinsic::usub_with_overflow:
6014   case Intrinsic::ssub_with_overflow:
6015   case Intrinsic::umul_with_overflow:
6016   case Intrinsic::smul_with_overflow: {
6017     ISD::NodeType Op;
6018     switch (Intrinsic) {
6019     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6020     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6021     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6022     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6023     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6024     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6025     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6026     }
6027     SDValue Op1 = getValue(I.getArgOperand(0));
6028     SDValue Op2 = getValue(I.getArgOperand(1));
6029 
6030     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
6031     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6032     return nullptr;
6033   }
6034   case Intrinsic::prefetch: {
6035     SDValue Ops[5];
6036     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6037     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6038     Ops[0] = DAG.getRoot();
6039     Ops[1] = getValue(I.getArgOperand(0));
6040     Ops[2] = getValue(I.getArgOperand(1));
6041     Ops[3] = getValue(I.getArgOperand(2));
6042     Ops[4] = getValue(I.getArgOperand(3));
6043     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6044                                              DAG.getVTList(MVT::Other), Ops,
6045                                              EVT::getIntegerVT(*Context, 8),
6046                                              MachinePointerInfo(I.getArgOperand(0)),
6047                                              0, /* align */
6048                                              Flags);
6049 
6050     // Chain the prefetch in parallell with any pending loads, to stay out of
6051     // the way of later optimizations.
6052     PendingLoads.push_back(Result);
6053     Result = getRoot();
6054     DAG.setRoot(Result);
6055     return nullptr;
6056   }
6057   case Intrinsic::lifetime_start:
6058   case Intrinsic::lifetime_end: {
6059     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6060     // Stack coloring is not enabled in O0, discard region information.
6061     if (TM.getOptLevel() == CodeGenOpt::None)
6062       return nullptr;
6063 
6064     SmallVector<Value *, 4> Allocas;
6065     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
6066 
6067     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6068            E = Allocas.end(); Object != E; ++Object) {
6069       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6070 
6071       // Could not find an Alloca.
6072       if (!LifetimeObject)
6073         continue;
6074 
6075       // First check that the Alloca is static, otherwise it won't have a
6076       // valid frame index.
6077       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6078       if (SI == FuncInfo.StaticAllocaMap.end())
6079         return nullptr;
6080 
6081       int FI = SI->second;
6082 
6083       SDValue Ops[2];
6084       Ops[0] = getRoot();
6085       Ops[1] =
6086           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6087       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6088 
6089       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6090       DAG.setRoot(Res);
6091     }
6092     return nullptr;
6093   }
6094   case Intrinsic::invariant_start:
6095     // Discard region information.
6096     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6097     return nullptr;
6098   case Intrinsic::invariant_end:
6099     // Discard region information.
6100     return nullptr;
6101   case Intrinsic::clear_cache:
6102     return TLI.getClearCacheBuiltinName();
6103   case Intrinsic::donothing:
6104     // ignore
6105     return nullptr;
6106   case Intrinsic::experimental_stackmap:
6107     visitStackmap(I);
6108     return nullptr;
6109   case Intrinsic::experimental_patchpoint_void:
6110   case Intrinsic::experimental_patchpoint_i64:
6111     visitPatchpoint(&I);
6112     return nullptr;
6113   case Intrinsic::experimental_gc_statepoint:
6114     LowerStatepoint(ImmutableStatepoint(&I));
6115     return nullptr;
6116   case Intrinsic::experimental_gc_result:
6117     visitGCResult(cast<GCResultInst>(I));
6118     return nullptr;
6119   case Intrinsic::experimental_gc_relocate:
6120     visitGCRelocate(cast<GCRelocateInst>(I));
6121     return nullptr;
6122   case Intrinsic::instrprof_increment:
6123     llvm_unreachable("instrprof failed to lower an increment");
6124   case Intrinsic::instrprof_value_profile:
6125     llvm_unreachable("instrprof failed to lower a value profiling call");
6126   case Intrinsic::localescape: {
6127     MachineFunction &MF = DAG.getMachineFunction();
6128     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6129 
6130     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6131     // is the same on all targets.
6132     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6133       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6134       if (isa<ConstantPointerNull>(Arg))
6135         continue; // Skip null pointers. They represent a hole in index space.
6136       AllocaInst *Slot = cast<AllocaInst>(Arg);
6137       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6138              "can only escape static allocas");
6139       int FI = FuncInfo.StaticAllocaMap[Slot];
6140       MCSymbol *FrameAllocSym =
6141           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6142               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6143       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6144               TII->get(TargetOpcode::LOCAL_ESCAPE))
6145           .addSym(FrameAllocSym)
6146           .addFrameIndex(FI);
6147     }
6148 
6149     return nullptr;
6150   }
6151 
6152   case Intrinsic::localrecover: {
6153     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6154     MachineFunction &MF = DAG.getMachineFunction();
6155     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6156 
6157     // Get the symbol that defines the frame offset.
6158     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6159     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6160     unsigned IdxVal =
6161         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6162     MCSymbol *FrameAllocSym =
6163         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6164             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6165 
6166     // Create a MCSymbol for the label to avoid any target lowering
6167     // that would make this PC relative.
6168     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6169     SDValue OffsetVal =
6170         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6171 
6172     // Add the offset to the FP.
6173     Value *FP = I.getArgOperand(1);
6174     SDValue FPVal = getValue(FP);
6175     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6176     setValue(&I, Add);
6177 
6178     return nullptr;
6179   }
6180 
6181   case Intrinsic::eh_exceptionpointer:
6182   case Intrinsic::eh_exceptioncode: {
6183     // Get the exception pointer vreg, copy from it, and resize it to fit.
6184     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6185     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6186     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6187     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6188     SDValue N =
6189         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6190     if (Intrinsic == Intrinsic::eh_exceptioncode)
6191       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6192     setValue(&I, N);
6193     return nullptr;
6194   }
6195   case Intrinsic::xray_customevent: {
6196     // Here we want to make sure that the intrinsic behaves as if it has a
6197     // specific calling convention, and only for x86_64.
6198     // FIXME: Support other platforms later.
6199     const auto &Triple = DAG.getTarget().getTargetTriple();
6200     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6201       return nullptr;
6202 
6203     SDLoc DL = getCurSDLoc();
6204     SmallVector<SDValue, 8> Ops;
6205 
6206     // We want to say that we always want the arguments in registers.
6207     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6208     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6209     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6210     SDValue Chain = getRoot();
6211     Ops.push_back(LogEntryVal);
6212     Ops.push_back(StrSizeVal);
6213     Ops.push_back(Chain);
6214 
6215     // We need to enforce the calling convention for the callsite, so that
6216     // argument ordering is enforced correctly, and that register allocation can
6217     // see that some registers may be assumed clobbered and have to preserve
6218     // them across calls to the intrinsic.
6219     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6220                                            DL, NodeTys, Ops);
6221     SDValue patchableNode = SDValue(MN, 0);
6222     DAG.setRoot(patchableNode);
6223     setValue(&I, patchableNode);
6224     return nullptr;
6225   }
6226   case Intrinsic::xray_typedevent: {
6227     // Here we want to make sure that the intrinsic behaves as if it has a
6228     // specific calling convention, and only for x86_64.
6229     // FIXME: Support other platforms later.
6230     const auto &Triple = DAG.getTarget().getTargetTriple();
6231     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6232       return nullptr;
6233 
6234     SDLoc DL = getCurSDLoc();
6235     SmallVector<SDValue, 8> Ops;
6236 
6237     // We want to say that we always want the arguments in registers.
6238     // It's unclear to me how manipulating the selection DAG here forces callers
6239     // to provide arguments in registers instead of on the stack.
6240     SDValue LogTypeId = getValue(I.getArgOperand(0));
6241     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6242     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6243     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6244     SDValue Chain = getRoot();
6245     Ops.push_back(LogTypeId);
6246     Ops.push_back(LogEntryVal);
6247     Ops.push_back(StrSizeVal);
6248     Ops.push_back(Chain);
6249 
6250     // We need to enforce the calling convention for the callsite, so that
6251     // argument ordering is enforced correctly, and that register allocation can
6252     // see that some registers may be assumed clobbered and have to preserve
6253     // them across calls to the intrinsic.
6254     MachineSDNode *MN = DAG.getMachineNode(
6255         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6256     SDValue patchableNode = SDValue(MN, 0);
6257     DAG.setRoot(patchableNode);
6258     setValue(&I, patchableNode);
6259     return nullptr;
6260   }
6261   case Intrinsic::experimental_deoptimize:
6262     LowerDeoptimizeCall(&I);
6263     return nullptr;
6264 
6265   case Intrinsic::experimental_vector_reduce_fadd:
6266   case Intrinsic::experimental_vector_reduce_fmul:
6267   case Intrinsic::experimental_vector_reduce_add:
6268   case Intrinsic::experimental_vector_reduce_mul:
6269   case Intrinsic::experimental_vector_reduce_and:
6270   case Intrinsic::experimental_vector_reduce_or:
6271   case Intrinsic::experimental_vector_reduce_xor:
6272   case Intrinsic::experimental_vector_reduce_smax:
6273   case Intrinsic::experimental_vector_reduce_smin:
6274   case Intrinsic::experimental_vector_reduce_umax:
6275   case Intrinsic::experimental_vector_reduce_umin:
6276   case Intrinsic::experimental_vector_reduce_fmax:
6277   case Intrinsic::experimental_vector_reduce_fmin:
6278     visitVectorReduce(I, Intrinsic);
6279     return nullptr;
6280 
6281   case Intrinsic::icall_branch_funnel: {
6282     SmallVector<SDValue, 16> Ops;
6283     Ops.push_back(DAG.getRoot());
6284     Ops.push_back(getValue(I.getArgOperand(0)));
6285 
6286     int64_t Offset;
6287     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6288         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6289     if (!Base)
6290       report_fatal_error(
6291           "llvm.icall.branch.funnel operand must be a GlobalValue");
6292     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6293 
6294     struct BranchFunnelTarget {
6295       int64_t Offset;
6296       SDValue Target;
6297     };
6298     SmallVector<BranchFunnelTarget, 8> Targets;
6299 
6300     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6301       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6302           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6303       if (ElemBase != Base)
6304         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6305                            "to the same GlobalValue");
6306 
6307       SDValue Val = getValue(I.getArgOperand(Op + 1));
6308       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6309       if (!GA)
6310         report_fatal_error(
6311             "llvm.icall.branch.funnel operand must be a GlobalValue");
6312       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6313                                      GA->getGlobal(), getCurSDLoc(),
6314                                      Val.getValueType(), GA->getOffset())});
6315     }
6316     llvm::sort(Targets,
6317                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6318                  return T1.Offset < T2.Offset;
6319                });
6320 
6321     for (auto &T : Targets) {
6322       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6323       Ops.push_back(T.Target);
6324     }
6325 
6326     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6327                                  getCurSDLoc(), MVT::Other, Ops),
6328               0);
6329     DAG.setRoot(N);
6330     setValue(&I, N);
6331     HasTailCall = true;
6332     return nullptr;
6333   }
6334 
6335   case Intrinsic::wasm_landingpad_index:
6336     // Information this intrinsic contained has been transferred to
6337     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6338     // delete it now.
6339     return nullptr;
6340   }
6341 }
6342 
6343 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6344     const ConstrainedFPIntrinsic &FPI) {
6345   SDLoc sdl = getCurSDLoc();
6346   unsigned Opcode;
6347   switch (FPI.getIntrinsicID()) {
6348   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6349   case Intrinsic::experimental_constrained_fadd:
6350     Opcode = ISD::STRICT_FADD;
6351     break;
6352   case Intrinsic::experimental_constrained_fsub:
6353     Opcode = ISD::STRICT_FSUB;
6354     break;
6355   case Intrinsic::experimental_constrained_fmul:
6356     Opcode = ISD::STRICT_FMUL;
6357     break;
6358   case Intrinsic::experimental_constrained_fdiv:
6359     Opcode = ISD::STRICT_FDIV;
6360     break;
6361   case Intrinsic::experimental_constrained_frem:
6362     Opcode = ISD::STRICT_FREM;
6363     break;
6364   case Intrinsic::experimental_constrained_fma:
6365     Opcode = ISD::STRICT_FMA;
6366     break;
6367   case Intrinsic::experimental_constrained_sqrt:
6368     Opcode = ISD::STRICT_FSQRT;
6369     break;
6370   case Intrinsic::experimental_constrained_pow:
6371     Opcode = ISD::STRICT_FPOW;
6372     break;
6373   case Intrinsic::experimental_constrained_powi:
6374     Opcode = ISD::STRICT_FPOWI;
6375     break;
6376   case Intrinsic::experimental_constrained_sin:
6377     Opcode = ISD::STRICT_FSIN;
6378     break;
6379   case Intrinsic::experimental_constrained_cos:
6380     Opcode = ISD::STRICT_FCOS;
6381     break;
6382   case Intrinsic::experimental_constrained_exp:
6383     Opcode = ISD::STRICT_FEXP;
6384     break;
6385   case Intrinsic::experimental_constrained_exp2:
6386     Opcode = ISD::STRICT_FEXP2;
6387     break;
6388   case Intrinsic::experimental_constrained_log:
6389     Opcode = ISD::STRICT_FLOG;
6390     break;
6391   case Intrinsic::experimental_constrained_log10:
6392     Opcode = ISD::STRICT_FLOG10;
6393     break;
6394   case Intrinsic::experimental_constrained_log2:
6395     Opcode = ISD::STRICT_FLOG2;
6396     break;
6397   case Intrinsic::experimental_constrained_rint:
6398     Opcode = ISD::STRICT_FRINT;
6399     break;
6400   case Intrinsic::experimental_constrained_nearbyint:
6401     Opcode = ISD::STRICT_FNEARBYINT;
6402     break;
6403   case Intrinsic::experimental_constrained_maxnum:
6404     Opcode = ISD::STRICT_FMAXNUM;
6405     break;
6406   case Intrinsic::experimental_constrained_minnum:
6407     Opcode = ISD::STRICT_FMINNUM;
6408     break;
6409   case Intrinsic::experimental_constrained_ceil:
6410     Opcode = ISD::STRICT_FCEIL;
6411     break;
6412   case Intrinsic::experimental_constrained_floor:
6413     Opcode = ISD::STRICT_FFLOOR;
6414     break;
6415   case Intrinsic::experimental_constrained_round:
6416     Opcode = ISD::STRICT_FROUND;
6417     break;
6418   case Intrinsic::experimental_constrained_trunc:
6419     Opcode = ISD::STRICT_FTRUNC;
6420     break;
6421   }
6422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6423   SDValue Chain = getRoot();
6424   SmallVector<EVT, 4> ValueVTs;
6425   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6426   ValueVTs.push_back(MVT::Other); // Out chain
6427 
6428   SDVTList VTs = DAG.getVTList(ValueVTs);
6429   SDValue Result;
6430   if (FPI.isUnaryOp())
6431     Result = DAG.getNode(Opcode, sdl, VTs,
6432                          { Chain, getValue(FPI.getArgOperand(0)) });
6433   else if (FPI.isTernaryOp())
6434     Result = DAG.getNode(Opcode, sdl, VTs,
6435                          { Chain, getValue(FPI.getArgOperand(0)),
6436                                   getValue(FPI.getArgOperand(1)),
6437                                   getValue(FPI.getArgOperand(2)) });
6438   else
6439     Result = DAG.getNode(Opcode, sdl, VTs,
6440                          { Chain, getValue(FPI.getArgOperand(0)),
6441                            getValue(FPI.getArgOperand(1))  });
6442 
6443   assert(Result.getNode()->getNumValues() == 2);
6444   SDValue OutChain = Result.getValue(1);
6445   DAG.setRoot(OutChain);
6446   SDValue FPResult = Result.getValue(0);
6447   setValue(&FPI, FPResult);
6448 }
6449 
6450 std::pair<SDValue, SDValue>
6451 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6452                                     const BasicBlock *EHPadBB) {
6453   MachineFunction &MF = DAG.getMachineFunction();
6454   MachineModuleInfo &MMI = MF.getMMI();
6455   MCSymbol *BeginLabel = nullptr;
6456 
6457   if (EHPadBB) {
6458     // Insert a label before the invoke call to mark the try range.  This can be
6459     // used to detect deletion of the invoke via the MachineModuleInfo.
6460     BeginLabel = MMI.getContext().createTempSymbol();
6461 
6462     // For SjLj, keep track of which landing pads go with which invokes
6463     // so as to maintain the ordering of pads in the LSDA.
6464     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6465     if (CallSiteIndex) {
6466       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6467       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6468 
6469       // Now that the call site is handled, stop tracking it.
6470       MMI.setCurrentCallSite(0);
6471     }
6472 
6473     // Both PendingLoads and PendingExports must be flushed here;
6474     // this call might not return.
6475     (void)getRoot();
6476     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6477 
6478     CLI.setChain(getRoot());
6479   }
6480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6481   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6482 
6483   assert((CLI.IsTailCall || Result.second.getNode()) &&
6484          "Non-null chain expected with non-tail call!");
6485   assert((Result.second.getNode() || !Result.first.getNode()) &&
6486          "Null value expected with tail call!");
6487 
6488   if (!Result.second.getNode()) {
6489     // As a special case, a null chain means that a tail call has been emitted
6490     // and the DAG root is already updated.
6491     HasTailCall = true;
6492 
6493     // Since there's no actual continuation from this block, nothing can be
6494     // relying on us setting vregs for them.
6495     PendingExports.clear();
6496   } else {
6497     DAG.setRoot(Result.second);
6498   }
6499 
6500   if (EHPadBB) {
6501     // Insert a label at the end of the invoke call to mark the try range.  This
6502     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6503     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6504     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6505 
6506     // Inform MachineModuleInfo of range.
6507     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6508     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6509     // actually use outlined funclets and their LSDA info style.
6510     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6511       assert(CLI.CS);
6512       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6513       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6514                                 BeginLabel, EndLabel);
6515     } else if (!isScopedEHPersonality(Pers)) {
6516       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6517     }
6518   }
6519 
6520   return Result;
6521 }
6522 
6523 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6524                                       bool isTailCall,
6525                                       const BasicBlock *EHPadBB) {
6526   auto &DL = DAG.getDataLayout();
6527   FunctionType *FTy = CS.getFunctionType();
6528   Type *RetTy = CS.getType();
6529 
6530   TargetLowering::ArgListTy Args;
6531   Args.reserve(CS.arg_size());
6532 
6533   const Value *SwiftErrorVal = nullptr;
6534   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6535 
6536   // We can't tail call inside a function with a swifterror argument. Lowering
6537   // does not support this yet. It would have to move into the swifterror
6538   // register before the call.
6539   auto *Caller = CS.getInstruction()->getParent()->getParent();
6540   if (TLI.supportSwiftError() &&
6541       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6542     isTailCall = false;
6543 
6544   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6545        i != e; ++i) {
6546     TargetLowering::ArgListEntry Entry;
6547     const Value *V = *i;
6548 
6549     // Skip empty types
6550     if (V->getType()->isEmptyTy())
6551       continue;
6552 
6553     SDValue ArgNode = getValue(V);
6554     Entry.Node = ArgNode; Entry.Ty = V->getType();
6555 
6556     Entry.setAttributes(&CS, i - CS.arg_begin());
6557 
6558     // Use swifterror virtual register as input to the call.
6559     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6560       SwiftErrorVal = V;
6561       // We find the virtual register for the actual swifterror argument.
6562       // Instead of using the Value, we use the virtual register instead.
6563       Entry.Node = DAG.getRegister(FuncInfo
6564                                        .getOrCreateSwiftErrorVRegUseAt(
6565                                            CS.getInstruction(), FuncInfo.MBB, V)
6566                                        .first,
6567                                    EVT(TLI.getPointerTy(DL)));
6568     }
6569 
6570     Args.push_back(Entry);
6571 
6572     // If we have an explicit sret argument that is an Instruction, (i.e., it
6573     // might point to function-local memory), we can't meaningfully tail-call.
6574     if (Entry.IsSRet && isa<Instruction>(V))
6575       isTailCall = false;
6576   }
6577 
6578   // Check if target-independent constraints permit a tail call here.
6579   // Target-dependent constraints are checked within TLI->LowerCallTo.
6580   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6581     isTailCall = false;
6582 
6583   // Disable tail calls if there is an swifterror argument. Targets have not
6584   // been updated to support tail calls.
6585   if (TLI.supportSwiftError() && SwiftErrorVal)
6586     isTailCall = false;
6587 
6588   TargetLowering::CallLoweringInfo CLI(DAG);
6589   CLI.setDebugLoc(getCurSDLoc())
6590       .setChain(getRoot())
6591       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6592       .setTailCall(isTailCall)
6593       .setConvergent(CS.isConvergent());
6594   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6595 
6596   if (Result.first.getNode()) {
6597     const Instruction *Inst = CS.getInstruction();
6598     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6599     setValue(Inst, Result.first);
6600   }
6601 
6602   // The last element of CLI.InVals has the SDValue for swifterror return.
6603   // Here we copy it to a virtual register and update SwiftErrorMap for
6604   // book-keeping.
6605   if (SwiftErrorVal && TLI.supportSwiftError()) {
6606     // Get the last element of InVals.
6607     SDValue Src = CLI.InVals.back();
6608     unsigned VReg; bool CreatedVReg;
6609     std::tie(VReg, CreatedVReg) =
6610         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6611     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6612     // We update the virtual register for the actual swifterror argument.
6613     if (CreatedVReg)
6614       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6615     DAG.setRoot(CopyNode);
6616   }
6617 }
6618 
6619 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6620                              SelectionDAGBuilder &Builder) {
6621   // Check to see if this load can be trivially constant folded, e.g. if the
6622   // input is from a string literal.
6623   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6624     // Cast pointer to the type we really want to load.
6625     Type *LoadTy =
6626         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6627     if (LoadVT.isVector())
6628       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6629 
6630     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6631                                          PointerType::getUnqual(LoadTy));
6632 
6633     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6634             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6635       return Builder.getValue(LoadCst);
6636   }
6637 
6638   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6639   // still constant memory, the input chain can be the entry node.
6640   SDValue Root;
6641   bool ConstantMemory = false;
6642 
6643   // Do not serialize (non-volatile) loads of constant memory with anything.
6644   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6645     Root = Builder.DAG.getEntryNode();
6646     ConstantMemory = true;
6647   } else {
6648     // Do not serialize non-volatile loads against each other.
6649     Root = Builder.DAG.getRoot();
6650   }
6651 
6652   SDValue Ptr = Builder.getValue(PtrVal);
6653   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6654                                         Ptr, MachinePointerInfo(PtrVal),
6655                                         /* Alignment = */ 1);
6656 
6657   if (!ConstantMemory)
6658     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6659   return LoadVal;
6660 }
6661 
6662 /// Record the value for an instruction that produces an integer result,
6663 /// converting the type where necessary.
6664 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6665                                                   SDValue Value,
6666                                                   bool IsSigned) {
6667   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6668                                                     I.getType(), true);
6669   if (IsSigned)
6670     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6671   else
6672     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6673   setValue(&I, Value);
6674 }
6675 
6676 /// See if we can lower a memcmp call into an optimized form. If so, return
6677 /// true and lower it. Otherwise return false, and it will be lowered like a
6678 /// normal call.
6679 /// The caller already checked that \p I calls the appropriate LibFunc with a
6680 /// correct prototype.
6681 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6682   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6683   const Value *Size = I.getArgOperand(2);
6684   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6685   if (CSize && CSize->getZExtValue() == 0) {
6686     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6687                                                           I.getType(), true);
6688     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6689     return true;
6690   }
6691 
6692   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6693   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6694       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6695       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6696   if (Res.first.getNode()) {
6697     processIntegerCallValue(I, Res.first, true);
6698     PendingLoads.push_back(Res.second);
6699     return true;
6700   }
6701 
6702   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6703   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6704   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6705     return false;
6706 
6707   // If the target has a fast compare for the given size, it will return a
6708   // preferred load type for that size. Require that the load VT is legal and
6709   // that the target supports unaligned loads of that type. Otherwise, return
6710   // INVALID.
6711   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6712     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6713     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6714     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6715       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6716       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6717       // TODO: Check alignment of src and dest ptrs.
6718       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6719       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6720       if (!TLI.isTypeLegal(LVT) ||
6721           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6722           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6723         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6724     }
6725 
6726     return LVT;
6727   };
6728 
6729   // This turns into unaligned loads. We only do this if the target natively
6730   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6731   // we'll only produce a small number of byte loads.
6732   MVT LoadVT;
6733   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6734   switch (NumBitsToCompare) {
6735   default:
6736     return false;
6737   case 16:
6738     LoadVT = MVT::i16;
6739     break;
6740   case 32:
6741     LoadVT = MVT::i32;
6742     break;
6743   case 64:
6744   case 128:
6745   case 256:
6746     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6747     break;
6748   }
6749 
6750   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6751     return false;
6752 
6753   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6754   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6755 
6756   // Bitcast to a wide integer type if the loads are vectors.
6757   if (LoadVT.isVector()) {
6758     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6759     LoadL = DAG.getBitcast(CmpVT, LoadL);
6760     LoadR = DAG.getBitcast(CmpVT, LoadR);
6761   }
6762 
6763   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6764   processIntegerCallValue(I, Cmp, false);
6765   return true;
6766 }
6767 
6768 /// See if we can lower a memchr call into an optimized form. If so, return
6769 /// true and lower it. Otherwise return false, and it will be lowered like a
6770 /// normal call.
6771 /// The caller already checked that \p I calls the appropriate LibFunc with a
6772 /// correct prototype.
6773 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6774   const Value *Src = I.getArgOperand(0);
6775   const Value *Char = I.getArgOperand(1);
6776   const Value *Length = I.getArgOperand(2);
6777 
6778   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6779   std::pair<SDValue, SDValue> Res =
6780     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6781                                 getValue(Src), getValue(Char), getValue(Length),
6782                                 MachinePointerInfo(Src));
6783   if (Res.first.getNode()) {
6784     setValue(&I, Res.first);
6785     PendingLoads.push_back(Res.second);
6786     return true;
6787   }
6788 
6789   return false;
6790 }
6791 
6792 /// See if we can lower a mempcpy call into an optimized form. If so, return
6793 /// true and lower it. Otherwise return false, and it will be lowered like a
6794 /// normal call.
6795 /// The caller already checked that \p I calls the appropriate LibFunc with a
6796 /// correct prototype.
6797 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6798   SDValue Dst = getValue(I.getArgOperand(0));
6799   SDValue Src = getValue(I.getArgOperand(1));
6800   SDValue Size = getValue(I.getArgOperand(2));
6801 
6802   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6803   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6804   unsigned Align = std::min(DstAlign, SrcAlign);
6805   if (Align == 0) // Alignment of one or both could not be inferred.
6806     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6807 
6808   bool isVol = false;
6809   SDLoc sdl = getCurSDLoc();
6810 
6811   // In the mempcpy context we need to pass in a false value for isTailCall
6812   // because the return pointer needs to be adjusted by the size of
6813   // the copied memory.
6814   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6815                              false, /*isTailCall=*/false,
6816                              MachinePointerInfo(I.getArgOperand(0)),
6817                              MachinePointerInfo(I.getArgOperand(1)));
6818   assert(MC.getNode() != nullptr &&
6819          "** memcpy should not be lowered as TailCall in mempcpy context **");
6820   DAG.setRoot(MC);
6821 
6822   // Check if Size needs to be truncated or extended.
6823   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6824 
6825   // Adjust return pointer to point just past the last dst byte.
6826   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6827                                     Dst, Size);
6828   setValue(&I, DstPlusSize);
6829   return true;
6830 }
6831 
6832 /// See if we can lower a strcpy call into an optimized form.  If so, return
6833 /// true and lower it, otherwise return false and it will be lowered like a
6834 /// normal call.
6835 /// The caller already checked that \p I calls the appropriate LibFunc with a
6836 /// correct prototype.
6837 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6838   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6839 
6840   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6841   std::pair<SDValue, SDValue> Res =
6842     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6843                                 getValue(Arg0), getValue(Arg1),
6844                                 MachinePointerInfo(Arg0),
6845                                 MachinePointerInfo(Arg1), isStpcpy);
6846   if (Res.first.getNode()) {
6847     setValue(&I, Res.first);
6848     DAG.setRoot(Res.second);
6849     return true;
6850   }
6851 
6852   return false;
6853 }
6854 
6855 /// See if we can lower a strcmp call into an optimized form.  If so, return
6856 /// true and lower it, otherwise return false and it will be lowered like a
6857 /// normal call.
6858 /// The caller already checked that \p I calls the appropriate LibFunc with a
6859 /// correct prototype.
6860 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6861   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6862 
6863   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6864   std::pair<SDValue, SDValue> Res =
6865     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6866                                 getValue(Arg0), getValue(Arg1),
6867                                 MachinePointerInfo(Arg0),
6868                                 MachinePointerInfo(Arg1));
6869   if (Res.first.getNode()) {
6870     processIntegerCallValue(I, Res.first, true);
6871     PendingLoads.push_back(Res.second);
6872     return true;
6873   }
6874 
6875   return false;
6876 }
6877 
6878 /// See if we can lower a strlen call into an optimized form.  If so, return
6879 /// true and lower it, otherwise return false and it will be lowered like a
6880 /// normal call.
6881 /// The caller already checked that \p I calls the appropriate LibFunc with a
6882 /// correct prototype.
6883 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6884   const Value *Arg0 = I.getArgOperand(0);
6885 
6886   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6887   std::pair<SDValue, SDValue> Res =
6888     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6889                                 getValue(Arg0), MachinePointerInfo(Arg0));
6890   if (Res.first.getNode()) {
6891     processIntegerCallValue(I, Res.first, false);
6892     PendingLoads.push_back(Res.second);
6893     return true;
6894   }
6895 
6896   return false;
6897 }
6898 
6899 /// See if we can lower a strnlen call into an optimized form.  If so, return
6900 /// true and lower it, otherwise return false and it will be lowered like a
6901 /// normal call.
6902 /// The caller already checked that \p I calls the appropriate LibFunc with a
6903 /// correct prototype.
6904 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6905   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6906 
6907   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6908   std::pair<SDValue, SDValue> Res =
6909     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6910                                  getValue(Arg0), getValue(Arg1),
6911                                  MachinePointerInfo(Arg0));
6912   if (Res.first.getNode()) {
6913     processIntegerCallValue(I, Res.first, false);
6914     PendingLoads.push_back(Res.second);
6915     return true;
6916   }
6917 
6918   return false;
6919 }
6920 
6921 /// See if we can lower a unary floating-point operation into an SDNode with
6922 /// the specified Opcode.  If so, return true and lower it, otherwise return
6923 /// false and it will be lowered like a normal call.
6924 /// The caller already checked that \p I calls the appropriate LibFunc with a
6925 /// correct prototype.
6926 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6927                                               unsigned Opcode) {
6928   // We already checked this call's prototype; verify it doesn't modify errno.
6929   if (!I.onlyReadsMemory())
6930     return false;
6931 
6932   SDValue Tmp = getValue(I.getArgOperand(0));
6933   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6934   return true;
6935 }
6936 
6937 /// See if we can lower a binary floating-point operation into an SDNode with
6938 /// the specified Opcode. If so, return true and lower it. Otherwise return
6939 /// false, and it will be lowered like a normal call.
6940 /// The caller already checked that \p I calls the appropriate LibFunc with a
6941 /// correct prototype.
6942 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6943                                                unsigned Opcode) {
6944   // We already checked this call's prototype; verify it doesn't modify errno.
6945   if (!I.onlyReadsMemory())
6946     return false;
6947 
6948   SDValue Tmp0 = getValue(I.getArgOperand(0));
6949   SDValue Tmp1 = getValue(I.getArgOperand(1));
6950   EVT VT = Tmp0.getValueType();
6951   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6952   return true;
6953 }
6954 
6955 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6956   // Handle inline assembly differently.
6957   if (isa<InlineAsm>(I.getCalledValue())) {
6958     visitInlineAsm(&I);
6959     return;
6960   }
6961 
6962   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6963   computeUsesVAFloatArgument(I, MMI);
6964 
6965   const char *RenameFn = nullptr;
6966   if (Function *F = I.getCalledFunction()) {
6967     if (F->isDeclaration()) {
6968       // Is this an LLVM intrinsic or a target-specific intrinsic?
6969       unsigned IID = F->getIntrinsicID();
6970       if (!IID)
6971         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
6972           IID = II->getIntrinsicID(F);
6973 
6974       if (IID) {
6975         RenameFn = visitIntrinsicCall(I, IID);
6976         if (!RenameFn)
6977           return;
6978       }
6979     }
6980 
6981     // Check for well-known libc/libm calls.  If the function is internal, it
6982     // can't be a library call.  Don't do the check if marked as nobuiltin for
6983     // some reason or the call site requires strict floating point semantics.
6984     LibFunc Func;
6985     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
6986         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
6987         LibInfo->hasOptimizedCodeGen(Func)) {
6988       switch (Func) {
6989       default: break;
6990       case LibFunc_copysign:
6991       case LibFunc_copysignf:
6992       case LibFunc_copysignl:
6993         // We already checked this call's prototype; verify it doesn't modify
6994         // errno.
6995         if (I.onlyReadsMemory()) {
6996           SDValue LHS = getValue(I.getArgOperand(0));
6997           SDValue RHS = getValue(I.getArgOperand(1));
6998           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6999                                    LHS.getValueType(), LHS, RHS));
7000           return;
7001         }
7002         break;
7003       case LibFunc_fabs:
7004       case LibFunc_fabsf:
7005       case LibFunc_fabsl:
7006         if (visitUnaryFloatCall(I, ISD::FABS))
7007           return;
7008         break;
7009       case LibFunc_fmin:
7010       case LibFunc_fminf:
7011       case LibFunc_fminl:
7012         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7013           return;
7014         break;
7015       case LibFunc_fmax:
7016       case LibFunc_fmaxf:
7017       case LibFunc_fmaxl:
7018         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7019           return;
7020         break;
7021       case LibFunc_sin:
7022       case LibFunc_sinf:
7023       case LibFunc_sinl:
7024         if (visitUnaryFloatCall(I, ISD::FSIN))
7025           return;
7026         break;
7027       case LibFunc_cos:
7028       case LibFunc_cosf:
7029       case LibFunc_cosl:
7030         if (visitUnaryFloatCall(I, ISD::FCOS))
7031           return;
7032         break;
7033       case LibFunc_sqrt:
7034       case LibFunc_sqrtf:
7035       case LibFunc_sqrtl:
7036       case LibFunc_sqrt_finite:
7037       case LibFunc_sqrtf_finite:
7038       case LibFunc_sqrtl_finite:
7039         if (visitUnaryFloatCall(I, ISD::FSQRT))
7040           return;
7041         break;
7042       case LibFunc_floor:
7043       case LibFunc_floorf:
7044       case LibFunc_floorl:
7045         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7046           return;
7047         break;
7048       case LibFunc_nearbyint:
7049       case LibFunc_nearbyintf:
7050       case LibFunc_nearbyintl:
7051         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7052           return;
7053         break;
7054       case LibFunc_ceil:
7055       case LibFunc_ceilf:
7056       case LibFunc_ceill:
7057         if (visitUnaryFloatCall(I, ISD::FCEIL))
7058           return;
7059         break;
7060       case LibFunc_rint:
7061       case LibFunc_rintf:
7062       case LibFunc_rintl:
7063         if (visitUnaryFloatCall(I, ISD::FRINT))
7064           return;
7065         break;
7066       case LibFunc_round:
7067       case LibFunc_roundf:
7068       case LibFunc_roundl:
7069         if (visitUnaryFloatCall(I, ISD::FROUND))
7070           return;
7071         break;
7072       case LibFunc_trunc:
7073       case LibFunc_truncf:
7074       case LibFunc_truncl:
7075         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7076           return;
7077         break;
7078       case LibFunc_log2:
7079       case LibFunc_log2f:
7080       case LibFunc_log2l:
7081         if (visitUnaryFloatCall(I, ISD::FLOG2))
7082           return;
7083         break;
7084       case LibFunc_exp2:
7085       case LibFunc_exp2f:
7086       case LibFunc_exp2l:
7087         if (visitUnaryFloatCall(I, ISD::FEXP2))
7088           return;
7089         break;
7090       case LibFunc_memcmp:
7091         if (visitMemCmpCall(I))
7092           return;
7093         break;
7094       case LibFunc_mempcpy:
7095         if (visitMemPCpyCall(I))
7096           return;
7097         break;
7098       case LibFunc_memchr:
7099         if (visitMemChrCall(I))
7100           return;
7101         break;
7102       case LibFunc_strcpy:
7103         if (visitStrCpyCall(I, false))
7104           return;
7105         break;
7106       case LibFunc_stpcpy:
7107         if (visitStrCpyCall(I, true))
7108           return;
7109         break;
7110       case LibFunc_strcmp:
7111         if (visitStrCmpCall(I))
7112           return;
7113         break;
7114       case LibFunc_strlen:
7115         if (visitStrLenCall(I))
7116           return;
7117         break;
7118       case LibFunc_strnlen:
7119         if (visitStrNLenCall(I))
7120           return;
7121         break;
7122       }
7123     }
7124   }
7125 
7126   SDValue Callee;
7127   if (!RenameFn)
7128     Callee = getValue(I.getCalledValue());
7129   else
7130     Callee = DAG.getExternalSymbol(
7131         RenameFn,
7132         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7133 
7134   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7135   // have to do anything here to lower funclet bundles.
7136   assert(!I.hasOperandBundlesOtherThan(
7137              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7138          "Cannot lower calls with arbitrary operand bundles!");
7139 
7140   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7141     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7142   else
7143     // Check if we can potentially perform a tail call. More detailed checking
7144     // is be done within LowerCallTo, after more information about the call is
7145     // known.
7146     LowerCallTo(&I, Callee, I.isTailCall());
7147 }
7148 
7149 namespace {
7150 
7151 /// AsmOperandInfo - This contains information for each constraint that we are
7152 /// lowering.
7153 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7154 public:
7155   /// CallOperand - If this is the result output operand or a clobber
7156   /// this is null, otherwise it is the incoming operand to the CallInst.
7157   /// This gets modified as the asm is processed.
7158   SDValue CallOperand;
7159 
7160   /// AssignedRegs - If this is a register or register class operand, this
7161   /// contains the set of register corresponding to the operand.
7162   RegsForValue AssignedRegs;
7163 
7164   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7165     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7166   }
7167 
7168   /// Whether or not this operand accesses memory
7169   bool hasMemory(const TargetLowering &TLI) const {
7170     // Indirect operand accesses access memory.
7171     if (isIndirect)
7172       return true;
7173 
7174     for (const auto &Code : Codes)
7175       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7176         return true;
7177 
7178     return false;
7179   }
7180 
7181   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7182   /// corresponds to.  If there is no Value* for this operand, it returns
7183   /// MVT::Other.
7184   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7185                            const DataLayout &DL) const {
7186     if (!CallOperandVal) return MVT::Other;
7187 
7188     if (isa<BasicBlock>(CallOperandVal))
7189       return TLI.getPointerTy(DL);
7190 
7191     llvm::Type *OpTy = CallOperandVal->getType();
7192 
7193     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7194     // If this is an indirect operand, the operand is a pointer to the
7195     // accessed type.
7196     if (isIndirect) {
7197       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7198       if (!PtrTy)
7199         report_fatal_error("Indirect operand for inline asm not a pointer!");
7200       OpTy = PtrTy->getElementType();
7201     }
7202 
7203     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7204     if (StructType *STy = dyn_cast<StructType>(OpTy))
7205       if (STy->getNumElements() == 1)
7206         OpTy = STy->getElementType(0);
7207 
7208     // If OpTy is not a single value, it may be a struct/union that we
7209     // can tile with integers.
7210     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7211       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7212       switch (BitSize) {
7213       default: break;
7214       case 1:
7215       case 8:
7216       case 16:
7217       case 32:
7218       case 64:
7219       case 128:
7220         OpTy = IntegerType::get(Context, BitSize);
7221         break;
7222       }
7223     }
7224 
7225     return TLI.getValueType(DL, OpTy, true);
7226   }
7227 };
7228 
7229 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7230 
7231 } // end anonymous namespace
7232 
7233 /// Make sure that the output operand \p OpInfo and its corresponding input
7234 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7235 /// out).
7236 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7237                                SDISelAsmOperandInfo &MatchingOpInfo,
7238                                SelectionDAG &DAG) {
7239   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7240     return;
7241 
7242   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7243   const auto &TLI = DAG.getTargetLoweringInfo();
7244 
7245   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7246       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7247                                        OpInfo.ConstraintVT);
7248   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7249       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7250                                        MatchingOpInfo.ConstraintVT);
7251   if ((OpInfo.ConstraintVT.isInteger() !=
7252        MatchingOpInfo.ConstraintVT.isInteger()) ||
7253       (MatchRC.second != InputRC.second)) {
7254     // FIXME: error out in a more elegant fashion
7255     report_fatal_error("Unsupported asm: input constraint"
7256                        " with a matching output constraint of"
7257                        " incompatible type!");
7258   }
7259   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7260 }
7261 
7262 /// Get a direct memory input to behave well as an indirect operand.
7263 /// This may introduce stores, hence the need for a \p Chain.
7264 /// \return The (possibly updated) chain.
7265 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7266                                         SDISelAsmOperandInfo &OpInfo,
7267                                         SelectionDAG &DAG) {
7268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7269 
7270   // If we don't have an indirect input, put it in the constpool if we can,
7271   // otherwise spill it to a stack slot.
7272   // TODO: This isn't quite right. We need to handle these according to
7273   // the addressing mode that the constraint wants. Also, this may take
7274   // an additional register for the computation and we don't want that
7275   // either.
7276 
7277   // If the operand is a float, integer, or vector constant, spill to a
7278   // constant pool entry to get its address.
7279   const Value *OpVal = OpInfo.CallOperandVal;
7280   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7281       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7282     OpInfo.CallOperand = DAG.getConstantPool(
7283         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7284     return Chain;
7285   }
7286 
7287   // Otherwise, create a stack slot and emit a store to it before the asm.
7288   Type *Ty = OpVal->getType();
7289   auto &DL = DAG.getDataLayout();
7290   uint64_t TySize = DL.getTypeAllocSize(Ty);
7291   unsigned Align = DL.getPrefTypeAlignment(Ty);
7292   MachineFunction &MF = DAG.getMachineFunction();
7293   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7294   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7295   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7296                        MachinePointerInfo::getFixedStack(MF, SSFI));
7297   OpInfo.CallOperand = StackSlot;
7298 
7299   return Chain;
7300 }
7301 
7302 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7303 /// specified operand.  We prefer to assign virtual registers, to allow the
7304 /// register allocator to handle the assignment process.  However, if the asm
7305 /// uses features that we can't model on machineinstrs, we have SDISel do the
7306 /// allocation.  This produces generally horrible, but correct, code.
7307 ///
7308 ///   OpInfo describes the operand
7309 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7310 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI,
7311                                  const SDLoc &DL, SDISelAsmOperandInfo &OpInfo,
7312                                  SDISelAsmOperandInfo &RefOpInfo) {
7313   LLVMContext &Context = *DAG.getContext();
7314 
7315   MachineFunction &MF = DAG.getMachineFunction();
7316   SmallVector<unsigned, 4> Regs;
7317   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7318 
7319   // If this is a constraint for a single physreg, or a constraint for a
7320   // register class, find it.
7321   std::pair<unsigned, const TargetRegisterClass *> PhysReg =
7322       TLI.getRegForInlineAsmConstraint(&TRI, RefOpInfo.ConstraintCode,
7323                                        RefOpInfo.ConstraintVT);
7324 
7325   unsigned NumRegs = 1;
7326   if (OpInfo.ConstraintVT != MVT::Other) {
7327     // If this is an FP operand in an integer register (or visa versa), or more
7328     // generally if the operand value disagrees with the register class we plan
7329     // to stick it in, fix the operand type.
7330     //
7331     // If this is an input value, the bitcast to the new type is done now.
7332     // Bitcast for output value is done at the end of visitInlineAsm().
7333     if ((OpInfo.Type == InlineAsm::isOutput ||
7334          OpInfo.Type == InlineAsm::isInput) &&
7335         PhysReg.second &&
7336         !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) {
7337       // Try to convert to the first EVT that the reg class contains.  If the
7338       // types are identical size, use a bitcast to convert (e.g. two differing
7339       // vector types).  Note: output bitcast is done at the end of
7340       // visitInlineAsm().
7341       MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second);
7342       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7343         // Exclude indirect inputs while they are unsupported because the code
7344         // to perform the load is missing and thus OpInfo.CallOperand still
7345         // refers to the input address rather than the pointed-to value.
7346         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7347           OpInfo.CallOperand =
7348               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7349         OpInfo.ConstraintVT = RegVT;
7350         // If the operand is an FP value and we want it in integer registers,
7351         // use the corresponding integer type. This turns an f64 value into
7352         // i64, which can be passed with two i32 values on a 32-bit machine.
7353       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7354         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7355         if (OpInfo.Type == InlineAsm::isInput)
7356           OpInfo.CallOperand =
7357               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7358         OpInfo.ConstraintVT = RegVT;
7359       }
7360     }
7361 
7362     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7363   }
7364 
7365   // No need to allocate a matching input constraint since the constraint it's
7366   // matching to has already been allocated.
7367   if (OpInfo.isMatchingInputConstraint())
7368     return;
7369 
7370   MVT RegVT;
7371   EVT ValueVT = OpInfo.ConstraintVT;
7372 
7373   // If this is a constraint for a specific physical register, like {r17},
7374   // assign it now.
7375   if (unsigned AssignedReg = PhysReg.first) {
7376     const TargetRegisterClass *RC = PhysReg.second;
7377     if (OpInfo.ConstraintVT == MVT::Other)
7378       ValueVT = *TRI.legalclasstypes_begin(*RC);
7379 
7380     // Get the actual register value type.  This is important, because the user
7381     // may have asked for (e.g.) the AX register in i32 type.  We need to
7382     // remember that AX is actually i16 to get the right extension.
7383     RegVT = *TRI.legalclasstypes_begin(*RC);
7384 
7385     // This is an explicit reference to a physical register.
7386     Regs.push_back(AssignedReg);
7387 
7388     // If this is an expanded reference, add the rest of the regs to Regs.
7389     if (NumRegs != 1) {
7390       TargetRegisterClass::iterator I = RC->begin();
7391       for (; *I != AssignedReg; ++I)
7392         assert(I != RC->end() && "Didn't find reg!");
7393 
7394       // Already added the first reg.
7395       --NumRegs; ++I;
7396       for (; NumRegs; --NumRegs, ++I) {
7397         assert(I != RC->end() && "Ran out of registers to allocate!");
7398         Regs.push_back(*I);
7399       }
7400     }
7401 
7402     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7403     return;
7404   }
7405 
7406   // Otherwise, if this was a reference to an LLVM register class, create vregs
7407   // for this reference.
7408   if (const TargetRegisterClass *RC = PhysReg.second) {
7409     RegVT = *TRI.legalclasstypes_begin(*RC);
7410     if (OpInfo.ConstraintVT == MVT::Other)
7411       ValueVT = RegVT;
7412 
7413     // Create the appropriate number of virtual registers.
7414     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7415     for (; NumRegs; --NumRegs)
7416       Regs.push_back(RegInfo.createVirtualRegister(RC));
7417 
7418     OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7419     return;
7420   }
7421 
7422   // Otherwise, we couldn't allocate enough registers for this.
7423 }
7424 
7425 static unsigned
7426 findMatchingInlineAsmOperand(unsigned OperandNo,
7427                              const std::vector<SDValue> &AsmNodeOperands) {
7428   // Scan until we find the definition we already emitted of this operand.
7429   unsigned CurOp = InlineAsm::Op_FirstOperand;
7430   for (; OperandNo; --OperandNo) {
7431     // Advance to the next operand.
7432     unsigned OpFlag =
7433         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7434     assert((InlineAsm::isRegDefKind(OpFlag) ||
7435             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7436             InlineAsm::isMemKind(OpFlag)) &&
7437            "Skipped past definitions?");
7438     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7439   }
7440   return CurOp;
7441 }
7442 
7443 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT
7444 /// \return true if it has succeeded, false otherwise
7445 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs,
7446                               MVT RegVT, SelectionDAG &DAG) {
7447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7448   MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
7449   for (unsigned i = 0, e = NumRegs; i != e; ++i) {
7450     if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
7451       Regs.push_back(RegInfo.createVirtualRegister(RC));
7452     else
7453       return false;
7454   }
7455   return true;
7456 }
7457 
7458 namespace {
7459 
7460 class ExtraFlags {
7461   unsigned Flags = 0;
7462 
7463 public:
7464   explicit ExtraFlags(ImmutableCallSite CS) {
7465     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7466     if (IA->hasSideEffects())
7467       Flags |= InlineAsm::Extra_HasSideEffects;
7468     if (IA->isAlignStack())
7469       Flags |= InlineAsm::Extra_IsAlignStack;
7470     if (CS.isConvergent())
7471       Flags |= InlineAsm::Extra_IsConvergent;
7472     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7473   }
7474 
7475   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7476     // Ideally, we would only check against memory constraints.  However, the
7477     // meaning of an Other constraint can be target-specific and we can't easily
7478     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7479     // for Other constraints as well.
7480     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7481         OpInfo.ConstraintType == TargetLowering::C_Other) {
7482       if (OpInfo.Type == InlineAsm::isInput)
7483         Flags |= InlineAsm::Extra_MayLoad;
7484       else if (OpInfo.Type == InlineAsm::isOutput)
7485         Flags |= InlineAsm::Extra_MayStore;
7486       else if (OpInfo.Type == InlineAsm::isClobber)
7487         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7488     }
7489   }
7490 
7491   unsigned get() const { return Flags; }
7492 };
7493 
7494 } // end anonymous namespace
7495 
7496 /// visitInlineAsm - Handle a call to an InlineAsm object.
7497 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7498   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7499 
7500   /// ConstraintOperands - Information about all of the constraints.
7501   SDISelAsmOperandInfoVector ConstraintOperands;
7502 
7503   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7504   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7505       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7506 
7507   bool hasMemory = false;
7508 
7509   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7510   ExtraFlags ExtraInfo(CS);
7511 
7512   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7513   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7514   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
7515     ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
7516     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7517 
7518     MVT OpVT = MVT::Other;
7519 
7520     // Compute the value type for each operand.
7521     if (OpInfo.Type == InlineAsm::isInput ||
7522         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7523       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7524 
7525       // Process the call argument. BasicBlocks are labels, currently appearing
7526       // only in asm's.
7527       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7528         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7529       } else {
7530         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7531       }
7532 
7533       OpVT =
7534           OpInfo
7535               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7536               .getSimpleVT();
7537     }
7538 
7539     if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7540       // The return value of the call is this value.  As such, there is no
7541       // corresponding argument.
7542       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7543       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7544         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
7545                                       STy->getElementType(ResNo));
7546       } else {
7547         assert(ResNo == 0 && "Asm only has one result!");
7548         OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7549       }
7550       ++ResNo;
7551     }
7552 
7553     OpInfo.ConstraintVT = OpVT;
7554 
7555     if (!hasMemory)
7556       hasMemory = OpInfo.hasMemory(TLI);
7557 
7558     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7559     // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]?
7560     auto TargetConstraint = TargetConstraints[i];
7561 
7562     // Compute the constraint code and ConstraintType to use.
7563     TLI.ComputeConstraintToUse(TargetConstraint, SDValue());
7564 
7565     ExtraInfo.update(TargetConstraint);
7566   }
7567 
7568   SDValue Chain, Flag;
7569 
7570   // We won't need to flush pending loads if this asm doesn't touch
7571   // memory and is nonvolatile.
7572   if (hasMemory || IA->hasSideEffects())
7573     Chain = getRoot();
7574   else
7575     Chain = DAG.getRoot();
7576 
7577   // Second pass over the constraints: compute which constraint option to use
7578   // and assign registers to constraints that want a specific physreg.
7579   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7580     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7581 
7582     // If this is an output operand with a matching input operand, look up the
7583     // matching input. If their types mismatch, e.g. one is an integer, the
7584     // other is floating point, or their sizes are different, flag it as an
7585     // error.
7586     if (OpInfo.hasMatchingInput()) {
7587       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7588       patchMatchingInput(OpInfo, Input, DAG);
7589     }
7590 
7591     // Compute the constraint code and ConstraintType to use.
7592     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7593 
7594     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7595         OpInfo.Type == InlineAsm::isClobber)
7596       continue;
7597 
7598     // If this is a memory input, and if the operand is not indirect, do what we
7599     // need to provide an address for the memory input.
7600     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7601         !OpInfo.isIndirect) {
7602       assert((OpInfo.isMultipleAlternative ||
7603               (OpInfo.Type == InlineAsm::isInput)) &&
7604              "Can only indirectify direct input operands!");
7605 
7606       // Memory operands really want the address of the value.
7607       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7608 
7609       // There is no longer a Value* corresponding to this operand.
7610       OpInfo.CallOperandVal = nullptr;
7611 
7612       // It is now an indirect operand.
7613       OpInfo.isIndirect = true;
7614     }
7615 
7616     // If this constraint is for a specific register, allocate it before
7617     // anything else.
7618     SDISelAsmOperandInfo &RefOpInfo =
7619         OpInfo.isMatchingInputConstraint()
7620             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7621             : ConstraintOperands[i];
7622     if (RefOpInfo.ConstraintType == TargetLowering::C_Register)
7623       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
7624   }
7625 
7626   // Third pass - Loop over all of the operands, assigning virtual or physregs
7627   // to register class operands.
7628   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7629     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7630     SDISelAsmOperandInfo &RefOpInfo =
7631         OpInfo.isMatchingInputConstraint()
7632             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7633             : ConstraintOperands[i];
7634 
7635     // C_Register operands have already been allocated, Other/Memory don't need
7636     // to be.
7637     if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7638       GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo, RefOpInfo);
7639   }
7640 
7641   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7642   std::vector<SDValue> AsmNodeOperands;
7643   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7644   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7645       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7646 
7647   // If we have a !srcloc metadata node associated with it, we want to attach
7648   // this to the ultimately generated inline asm machineinstr.  To do this, we
7649   // pass in the third operand as this (potentially null) inline asm MDNode.
7650   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7651   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7652 
7653   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7654   // bits as operand 3.
7655   AsmNodeOperands.push_back(DAG.getTargetConstant(
7656       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7657 
7658   // Loop over all of the inputs, copying the operand values into the
7659   // appropriate registers and processing the output regs.
7660   RegsForValue RetValRegs;
7661 
7662   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
7663   std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit;
7664 
7665   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
7666     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
7667 
7668     switch (OpInfo.Type) {
7669     case InlineAsm::isOutput:
7670       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7671           OpInfo.ConstraintType != TargetLowering::C_Register) {
7672         // Memory output, or 'other' output (e.g. 'X' constraint).
7673         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7674 
7675         unsigned ConstraintID =
7676             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7677         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7678                "Failed to convert memory constraint code to constraint id.");
7679 
7680         // Add information to the INLINEASM node to know about this output.
7681         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7682         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7683         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7684                                                         MVT::i32));
7685         AsmNodeOperands.push_back(OpInfo.CallOperand);
7686         break;
7687       }
7688 
7689       // Otherwise, this is a register or register class output.
7690 
7691       // Copy the output from the appropriate register.  Find a register that
7692       // we can use.
7693       if (OpInfo.AssignedRegs.Regs.empty()) {
7694         emitInlineAsmError(
7695             CS, "couldn't allocate output register for constraint '" +
7696                     Twine(OpInfo.ConstraintCode) + "'");
7697         return;
7698       }
7699 
7700       // If this is an indirect operand, store through the pointer after the
7701       // asm.
7702       if (OpInfo.isIndirect) {
7703         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
7704                                                       OpInfo.CallOperandVal));
7705       } else {
7706         // This is the result value of the call.
7707         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7708         // Concatenate this output onto the outputs list.
7709         RetValRegs.append(OpInfo.AssignedRegs);
7710       }
7711 
7712       // Add information to the INLINEASM node to know that this register is
7713       // set.
7714       OpInfo.AssignedRegs
7715           .AddInlineAsmOperands(OpInfo.isEarlyClobber
7716                                     ? InlineAsm::Kind_RegDefEarlyClobber
7717                                     : InlineAsm::Kind_RegDef,
7718                                 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7719       break;
7720 
7721     case InlineAsm::isInput: {
7722       SDValue InOperandVal = OpInfo.CallOperand;
7723 
7724       if (OpInfo.isMatchingInputConstraint()) {
7725         // If this is required to match an output register we have already set,
7726         // just use its register.
7727         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7728                                                   AsmNodeOperands);
7729         unsigned OpFlag =
7730           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7731         if (InlineAsm::isRegDefKind(OpFlag) ||
7732             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7733           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7734           if (OpInfo.isIndirect) {
7735             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7736             emitInlineAsmError(CS, "inline asm not supported yet:"
7737                                    " don't know how to handle tied "
7738                                    "indirect register inputs");
7739             return;
7740           }
7741 
7742           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7743           SmallVector<unsigned, 4> Regs;
7744 
7745           if (!createVirtualRegs(Regs,
7746                                  InlineAsm::getNumOperandRegisters(OpFlag),
7747                                  RegVT, DAG)) {
7748             emitInlineAsmError(CS, "inline asm error: This value type register "
7749                                    "class is not natively supported!");
7750             return;
7751           }
7752 
7753           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7754 
7755           SDLoc dl = getCurSDLoc();
7756           // Use the produced MatchedRegs object to
7757           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7758                                     CS.getInstruction());
7759           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7760                                            true, OpInfo.getMatchedOperand(), dl,
7761                                            DAG, AsmNodeOperands);
7762           break;
7763         }
7764 
7765         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7766         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7767                "Unexpected number of operands");
7768         // Add information to the INLINEASM node to know about this input.
7769         // See InlineAsm.h isUseOperandTiedToDef.
7770         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7771         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7772                                                     OpInfo.getMatchedOperand());
7773         AsmNodeOperands.push_back(DAG.getTargetConstant(
7774             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7775         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7776         break;
7777       }
7778 
7779       // Treat indirect 'X' constraint as memory.
7780       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7781           OpInfo.isIndirect)
7782         OpInfo.ConstraintType = TargetLowering::C_Memory;
7783 
7784       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7785         std::vector<SDValue> Ops;
7786         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7787                                           Ops, DAG);
7788         if (Ops.empty()) {
7789           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7790                                      Twine(OpInfo.ConstraintCode) + "'");
7791           return;
7792         }
7793 
7794         // Add information to the INLINEASM node to know about this input.
7795         unsigned ResOpType =
7796           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7797         AsmNodeOperands.push_back(DAG.getTargetConstant(
7798             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7799         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7800         break;
7801       }
7802 
7803       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7804         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7805         assert(InOperandVal.getValueType() ==
7806                    TLI.getPointerTy(DAG.getDataLayout()) &&
7807                "Memory operands expect pointer values");
7808 
7809         unsigned ConstraintID =
7810             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7811         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7812                "Failed to convert memory constraint code to constraint id.");
7813 
7814         // Add information to the INLINEASM node to know about this input.
7815         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7816         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7817         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7818                                                         getCurSDLoc(),
7819                                                         MVT::i32));
7820         AsmNodeOperands.push_back(InOperandVal);
7821         break;
7822       }
7823 
7824       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7825               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7826              "Unknown constraint type!");
7827 
7828       // TODO: Support this.
7829       if (OpInfo.isIndirect) {
7830         emitInlineAsmError(
7831             CS, "Don't know how to handle indirect register inputs yet "
7832                 "for constraint '" +
7833                     Twine(OpInfo.ConstraintCode) + "'");
7834         return;
7835       }
7836 
7837       // Copy the input into the appropriate registers.
7838       if (OpInfo.AssignedRegs.Regs.empty()) {
7839         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7840                                    Twine(OpInfo.ConstraintCode) + "'");
7841         return;
7842       }
7843 
7844       SDLoc dl = getCurSDLoc();
7845 
7846       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7847                                         Chain, &Flag, CS.getInstruction());
7848 
7849       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7850                                                dl, DAG, AsmNodeOperands);
7851       break;
7852     }
7853     case InlineAsm::isClobber:
7854       // Add the clobbered value to the operand list, so that the register
7855       // allocator is aware that the physreg got clobbered.
7856       if (!OpInfo.AssignedRegs.Regs.empty())
7857         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7858                                                  false, 0, getCurSDLoc(), DAG,
7859                                                  AsmNodeOperands);
7860       break;
7861     }
7862   }
7863 
7864   // Finish up input operands.  Set the input chain and add the flag last.
7865   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7866   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7867 
7868   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7869                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7870   Flag = Chain.getValue(1);
7871 
7872   // If this asm returns a register value, copy the result from that register
7873   // and set it as the value of the call.
7874   if (!RetValRegs.Regs.empty()) {
7875     SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7876                                              Chain, &Flag, CS.getInstruction());
7877 
7878     llvm::Type *CSResultType = CS.getType();
7879     unsigned numRet;
7880     ArrayRef<Type *> ResultTypes;
7881     SmallVector<SDValue, 1> ResultValues(1);
7882     if (CSResultType->isSingleValueType()) {
7883       numRet = 1;
7884       ResultValues[0] = Val;
7885       ResultTypes = makeArrayRef(CSResultType);
7886     } else {
7887       numRet = CSResultType->getNumContainedTypes();
7888       assert(Val->getNumOperands() == numRet &&
7889              "Mismatch in number of output operands in asm result");
7890       ResultTypes = CSResultType->subtypes();
7891       ArrayRef<SDUse> ValueUses = Val->ops();
7892       ResultValues.resize(numRet);
7893       std::transform(ValueUses.begin(), ValueUses.end(), ResultValues.begin(),
7894                      [](const SDUse &u) -> SDValue { return u.get(); });
7895     }
7896     SmallVector<EVT, 1> ResultVTs(numRet);
7897     for (unsigned i = 0; i < numRet; i++) {
7898       EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), ResultTypes[i]);
7899       SDValue Val = ResultValues[i];
7900       assert(ResultTypes[i]->isSized() && "Unexpected unsized type");
7901       // If the type of the inline asm call site return value is different but
7902       // has same size as the type of the asm output bitcast it.  One example
7903       // of this is for vectors with different width / number of elements.
7904       // This can happen for register classes that can contain multiple
7905       // different value types.  The preg or vreg allocated may not have the
7906       // same VT as was expected.
7907       //
7908       // This can also happen for a return value that disagrees with the
7909       // register class it is put in, eg. a double in a general-purpose
7910       // register on a 32-bit machine.
7911       if (ResultVT != Val.getValueType() &&
7912           ResultVT.getSizeInBits() == Val.getValueSizeInBits())
7913         Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, Val);
7914       else if (ResultVT != Val.getValueType() && ResultVT.isInteger() &&
7915                Val.getValueType().isInteger()) {
7916         // If a result value was tied to an input value, the computed result
7917         // may have a wider width than the expected result.  Extract the
7918         // relevant portion.
7919         Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, Val);
7920       }
7921 
7922       assert(ResultVT == Val.getValueType() && "Asm result value mismatch!");
7923       ResultVTs[i] = ResultVT;
7924       ResultValues[i] = Val;
7925     }
7926 
7927     Val = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
7928                       DAG.getVTList(ResultVTs), ResultValues);
7929     setValue(CS.getInstruction(), Val);
7930     // Don't need to use this as a chain in this case.
7931     if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
7932       return;
7933   }
7934 
7935   std::vector<std::pair<SDValue, const Value *>> StoresToEmit;
7936 
7937   // Process indirect outputs, first output all of the flagged copies out of
7938   // physregs.
7939   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
7940     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
7941     const Value *Ptr = IndirectStoresToEmit[i].second;
7942     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7943                                              Chain, &Flag, IA);
7944     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
7945   }
7946 
7947   // Emit the non-flagged stores from the physregs.
7948   SmallVector<SDValue, 8> OutChains;
7949   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
7950     SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first,
7951                                getValue(StoresToEmit[i].second),
7952                                MachinePointerInfo(StoresToEmit[i].second));
7953     OutChains.push_back(Val);
7954   }
7955 
7956   if (!OutChains.empty())
7957     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7958 
7959   DAG.setRoot(Chain);
7960 }
7961 
7962 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7963                                              const Twine &Message) {
7964   LLVMContext &Ctx = *DAG.getContext();
7965   Ctx.emitError(CS.getInstruction(), Message);
7966 
7967   // Make sure we leave the DAG in a valid state
7968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7969   SmallVector<EVT, 1> ValueVTs;
7970   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7971 
7972   if (ValueVTs.empty())
7973     return;
7974 
7975   SmallVector<SDValue, 1> Ops;
7976   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
7977     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
7978 
7979   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
7980 }
7981 
7982 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7983   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7984                           MVT::Other, getRoot(),
7985                           getValue(I.getArgOperand(0)),
7986                           DAG.getSrcValue(I.getArgOperand(0))));
7987 }
7988 
7989 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7991   const DataLayout &DL = DAG.getDataLayout();
7992   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7993                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7994                            DAG.getSrcValue(I.getOperand(0)),
7995                            DL.getABITypeAlignment(I.getType()));
7996   setValue(&I, V);
7997   DAG.setRoot(V.getValue(1));
7998 }
7999 
8000 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8001   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8002                           MVT::Other, getRoot(),
8003                           getValue(I.getArgOperand(0)),
8004                           DAG.getSrcValue(I.getArgOperand(0))));
8005 }
8006 
8007 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8008   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8009                           MVT::Other, getRoot(),
8010                           getValue(I.getArgOperand(0)),
8011                           getValue(I.getArgOperand(1)),
8012                           DAG.getSrcValue(I.getArgOperand(0)),
8013                           DAG.getSrcValue(I.getArgOperand(1))));
8014 }
8015 
8016 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8017                                                     const Instruction &I,
8018                                                     SDValue Op) {
8019   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8020   if (!Range)
8021     return Op;
8022 
8023   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8024   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
8025     return Op;
8026 
8027   APInt Lo = CR.getUnsignedMin();
8028   if (!Lo.isMinValue())
8029     return Op;
8030 
8031   APInt Hi = CR.getUnsignedMax();
8032   unsigned Bits = std::max(Hi.getActiveBits(),
8033                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8034 
8035   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8036 
8037   SDLoc SL = getCurSDLoc();
8038 
8039   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8040                              DAG.getValueType(SmallVT));
8041   unsigned NumVals = Op.getNode()->getNumValues();
8042   if (NumVals == 1)
8043     return ZExt;
8044 
8045   SmallVector<SDValue, 4> Ops;
8046 
8047   Ops.push_back(ZExt);
8048   for (unsigned I = 1; I != NumVals; ++I)
8049     Ops.push_back(Op.getValue(I));
8050 
8051   return DAG.getMergeValues(Ops, SL);
8052 }
8053 
8054 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8055 /// the call being lowered.
8056 ///
8057 /// This is a helper for lowering intrinsics that follow a target calling
8058 /// convention or require stack pointer adjustment. Only a subset of the
8059 /// intrinsic's operands need to participate in the calling convention.
8060 void SelectionDAGBuilder::populateCallLoweringInfo(
8061     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
8062     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8063     bool IsPatchPoint) {
8064   TargetLowering::ArgListTy Args;
8065   Args.reserve(NumArgs);
8066 
8067   // Populate the argument list.
8068   // Attributes for args start at offset 1, after the return attribute.
8069   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8070        ArgI != ArgE; ++ArgI) {
8071     const Value *V = CS->getOperand(ArgI);
8072 
8073     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8074 
8075     TargetLowering::ArgListEntry Entry;
8076     Entry.Node = getValue(V);
8077     Entry.Ty = V->getType();
8078     Entry.setAttributes(&CS, ArgI);
8079     Args.push_back(Entry);
8080   }
8081 
8082   CLI.setDebugLoc(getCurSDLoc())
8083       .setChain(getRoot())
8084       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
8085       .setDiscardResult(CS->use_empty())
8086       .setIsPatchPoint(IsPatchPoint);
8087 }
8088 
8089 /// Add a stack map intrinsic call's live variable operands to a stackmap
8090 /// or patchpoint target node's operand list.
8091 ///
8092 /// Constants are converted to TargetConstants purely as an optimization to
8093 /// avoid constant materialization and register allocation.
8094 ///
8095 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8096 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8097 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8098 /// address materialization and register allocation, but may also be required
8099 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8100 /// alloca in the entry block, then the runtime may assume that the alloca's
8101 /// StackMap location can be read immediately after compilation and that the
8102 /// location is valid at any point during execution (this is similar to the
8103 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8104 /// only available in a register, then the runtime would need to trap when
8105 /// execution reaches the StackMap in order to read the alloca's location.
8106 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8107                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8108                                 SelectionDAGBuilder &Builder) {
8109   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8110     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8111     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8112       Ops.push_back(
8113         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8114       Ops.push_back(
8115         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8116     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8117       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8118       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8119           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8120     } else
8121       Ops.push_back(OpVal);
8122   }
8123 }
8124 
8125 /// Lower llvm.experimental.stackmap directly to its target opcode.
8126 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8127   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8128   //                                  [live variables...])
8129 
8130   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8131 
8132   SDValue Chain, InFlag, Callee, NullPtr;
8133   SmallVector<SDValue, 32> Ops;
8134 
8135   SDLoc DL = getCurSDLoc();
8136   Callee = getValue(CI.getCalledValue());
8137   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8138 
8139   // The stackmap intrinsic only records the live variables (the arguemnts
8140   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8141   // intrinsic, this won't be lowered to a function call. This means we don't
8142   // have to worry about calling conventions and target specific lowering code.
8143   // Instead we perform the call lowering right here.
8144   //
8145   // chain, flag = CALLSEQ_START(chain, 0, 0)
8146   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8147   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8148   //
8149   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8150   InFlag = Chain.getValue(1);
8151 
8152   // Add the <id> and <numBytes> constants.
8153   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8154   Ops.push_back(DAG.getTargetConstant(
8155                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8156   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8157   Ops.push_back(DAG.getTargetConstant(
8158                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8159                   MVT::i32));
8160 
8161   // Push live variables for the stack map.
8162   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8163 
8164   // We are not pushing any register mask info here on the operands list,
8165   // because the stackmap doesn't clobber anything.
8166 
8167   // Push the chain and the glue flag.
8168   Ops.push_back(Chain);
8169   Ops.push_back(InFlag);
8170 
8171   // Create the STACKMAP node.
8172   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8173   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8174   Chain = SDValue(SM, 0);
8175   InFlag = Chain.getValue(1);
8176 
8177   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8178 
8179   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8180 
8181   // Set the root to the target-lowered call chain.
8182   DAG.setRoot(Chain);
8183 
8184   // Inform the Frame Information that we have a stackmap in this function.
8185   FuncInfo.MF->getFrameInfo().setHasStackMap();
8186 }
8187 
8188 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8189 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8190                                           const BasicBlock *EHPadBB) {
8191   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8192   //                                                 i32 <numBytes>,
8193   //                                                 i8* <target>,
8194   //                                                 i32 <numArgs>,
8195   //                                                 [Args...],
8196   //                                                 [live variables...])
8197 
8198   CallingConv::ID CC = CS.getCallingConv();
8199   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8200   bool HasDef = !CS->getType()->isVoidTy();
8201   SDLoc dl = getCurSDLoc();
8202   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8203 
8204   // Handle immediate and symbolic callees.
8205   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8206     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8207                                    /*isTarget=*/true);
8208   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8209     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8210                                          SDLoc(SymbolicCallee),
8211                                          SymbolicCallee->getValueType(0));
8212 
8213   // Get the real number of arguments participating in the call <numArgs>
8214   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8215   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8216 
8217   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8218   // Intrinsics include all meta-operands up to but not including CC.
8219   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8220   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8221          "Not enough arguments provided to the patchpoint intrinsic");
8222 
8223   // For AnyRegCC the arguments are lowered later on manually.
8224   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8225   Type *ReturnTy =
8226     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8227 
8228   TargetLowering::CallLoweringInfo CLI(DAG);
8229   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
8230                            true);
8231   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8232 
8233   SDNode *CallEnd = Result.second.getNode();
8234   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8235     CallEnd = CallEnd->getOperand(0).getNode();
8236 
8237   /// Get a call instruction from the call sequence chain.
8238   /// Tail calls are not allowed.
8239   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8240          "Expected a callseq node.");
8241   SDNode *Call = CallEnd->getOperand(0).getNode();
8242   bool HasGlue = Call->getGluedNode();
8243 
8244   // Replace the target specific call node with the patchable intrinsic.
8245   SmallVector<SDValue, 8> Ops;
8246 
8247   // Add the <id> and <numBytes> constants.
8248   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8249   Ops.push_back(DAG.getTargetConstant(
8250                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8251   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8252   Ops.push_back(DAG.getTargetConstant(
8253                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8254                   MVT::i32));
8255 
8256   // Add the callee.
8257   Ops.push_back(Callee);
8258 
8259   // Adjust <numArgs> to account for any arguments that have been passed on the
8260   // stack instead.
8261   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8262   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8263   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8264   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8265 
8266   // Add the calling convention
8267   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8268 
8269   // Add the arguments we omitted previously. The register allocator should
8270   // place these in any free register.
8271   if (IsAnyRegCC)
8272     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8273       Ops.push_back(getValue(CS.getArgument(i)));
8274 
8275   // Push the arguments from the call instruction up to the register mask.
8276   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8277   Ops.append(Call->op_begin() + 2, e);
8278 
8279   // Push live variables for the stack map.
8280   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8281 
8282   // Push the register mask info.
8283   if (HasGlue)
8284     Ops.push_back(*(Call->op_end()-2));
8285   else
8286     Ops.push_back(*(Call->op_end()-1));
8287 
8288   // Push the chain (this is originally the first operand of the call, but
8289   // becomes now the last or second to last operand).
8290   Ops.push_back(*(Call->op_begin()));
8291 
8292   // Push the glue flag (last operand).
8293   if (HasGlue)
8294     Ops.push_back(*(Call->op_end()-1));
8295 
8296   SDVTList NodeTys;
8297   if (IsAnyRegCC && HasDef) {
8298     // Create the return types based on the intrinsic definition
8299     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8300     SmallVector<EVT, 3> ValueVTs;
8301     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8302     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8303 
8304     // There is always a chain and a glue type at the end
8305     ValueVTs.push_back(MVT::Other);
8306     ValueVTs.push_back(MVT::Glue);
8307     NodeTys = DAG.getVTList(ValueVTs);
8308   } else
8309     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8310 
8311   // Replace the target specific call node with a PATCHPOINT node.
8312   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8313                                          dl, NodeTys, Ops);
8314 
8315   // Update the NodeMap.
8316   if (HasDef) {
8317     if (IsAnyRegCC)
8318       setValue(CS.getInstruction(), SDValue(MN, 0));
8319     else
8320       setValue(CS.getInstruction(), Result.first);
8321   }
8322 
8323   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8324   // call sequence. Furthermore the location of the chain and glue can change
8325   // when the AnyReg calling convention is used and the intrinsic returns a
8326   // value.
8327   if (IsAnyRegCC && HasDef) {
8328     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8329     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8330     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8331   } else
8332     DAG.ReplaceAllUsesWith(Call, MN);
8333   DAG.DeleteNode(Call);
8334 
8335   // Inform the Frame Information that we have a patchpoint in this function.
8336   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8337 }
8338 
8339 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8340                                             unsigned Intrinsic) {
8341   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8342   SDValue Op1 = getValue(I.getArgOperand(0));
8343   SDValue Op2;
8344   if (I.getNumArgOperands() > 1)
8345     Op2 = getValue(I.getArgOperand(1));
8346   SDLoc dl = getCurSDLoc();
8347   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8348   SDValue Res;
8349   FastMathFlags FMF;
8350   if (isa<FPMathOperator>(I))
8351     FMF = I.getFastMathFlags();
8352 
8353   switch (Intrinsic) {
8354   case Intrinsic::experimental_vector_reduce_fadd:
8355     if (FMF.isFast())
8356       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8357     else
8358       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8359     break;
8360   case Intrinsic::experimental_vector_reduce_fmul:
8361     if (FMF.isFast())
8362       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8363     else
8364       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8365     break;
8366   case Intrinsic::experimental_vector_reduce_add:
8367     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8368     break;
8369   case Intrinsic::experimental_vector_reduce_mul:
8370     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8371     break;
8372   case Intrinsic::experimental_vector_reduce_and:
8373     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8374     break;
8375   case Intrinsic::experimental_vector_reduce_or:
8376     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8377     break;
8378   case Intrinsic::experimental_vector_reduce_xor:
8379     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8380     break;
8381   case Intrinsic::experimental_vector_reduce_smax:
8382     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8383     break;
8384   case Intrinsic::experimental_vector_reduce_smin:
8385     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8386     break;
8387   case Intrinsic::experimental_vector_reduce_umax:
8388     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8389     break;
8390   case Intrinsic::experimental_vector_reduce_umin:
8391     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8392     break;
8393   case Intrinsic::experimental_vector_reduce_fmax:
8394     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8395     break;
8396   case Intrinsic::experimental_vector_reduce_fmin:
8397     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8398     break;
8399   default:
8400     llvm_unreachable("Unhandled vector reduce intrinsic");
8401   }
8402   setValue(&I, Res);
8403 }
8404 
8405 /// Returns an AttributeList representing the attributes applied to the return
8406 /// value of the given call.
8407 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8408   SmallVector<Attribute::AttrKind, 2> Attrs;
8409   if (CLI.RetSExt)
8410     Attrs.push_back(Attribute::SExt);
8411   if (CLI.RetZExt)
8412     Attrs.push_back(Attribute::ZExt);
8413   if (CLI.IsInReg)
8414     Attrs.push_back(Attribute::InReg);
8415 
8416   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8417                             Attrs);
8418 }
8419 
8420 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8421 /// implementation, which just calls LowerCall.
8422 /// FIXME: When all targets are
8423 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8424 std::pair<SDValue, SDValue>
8425 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8426   // Handle the incoming return values from the call.
8427   CLI.Ins.clear();
8428   Type *OrigRetTy = CLI.RetTy;
8429   SmallVector<EVT, 4> RetTys;
8430   SmallVector<uint64_t, 4> Offsets;
8431   auto &DL = CLI.DAG.getDataLayout();
8432   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8433 
8434   if (CLI.IsPostTypeLegalization) {
8435     // If we are lowering a libcall after legalization, split the return type.
8436     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8437     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8438     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8439       EVT RetVT = OldRetTys[i];
8440       uint64_t Offset = OldOffsets[i];
8441       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8442       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8443       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8444       RetTys.append(NumRegs, RegisterVT);
8445       for (unsigned j = 0; j != NumRegs; ++j)
8446         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8447     }
8448   }
8449 
8450   SmallVector<ISD::OutputArg, 4> Outs;
8451   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8452 
8453   bool CanLowerReturn =
8454       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8455                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8456 
8457   SDValue DemoteStackSlot;
8458   int DemoteStackIdx = -100;
8459   if (!CanLowerReturn) {
8460     // FIXME: equivalent assert?
8461     // assert(!CS.hasInAllocaArgument() &&
8462     //        "sret demotion is incompatible with inalloca");
8463     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8464     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8465     MachineFunction &MF = CLI.DAG.getMachineFunction();
8466     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8467     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8468                                               DL.getAllocaAddrSpace());
8469 
8470     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8471     ArgListEntry Entry;
8472     Entry.Node = DemoteStackSlot;
8473     Entry.Ty = StackSlotPtrType;
8474     Entry.IsSExt = false;
8475     Entry.IsZExt = false;
8476     Entry.IsInReg = false;
8477     Entry.IsSRet = true;
8478     Entry.IsNest = false;
8479     Entry.IsByVal = false;
8480     Entry.IsReturned = false;
8481     Entry.IsSwiftSelf = false;
8482     Entry.IsSwiftError = false;
8483     Entry.Alignment = Align;
8484     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8485     CLI.NumFixedArgs += 1;
8486     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8487 
8488     // sret demotion isn't compatible with tail-calls, since the sret argument
8489     // points into the callers stack frame.
8490     CLI.IsTailCall = false;
8491   } else {
8492     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8493       EVT VT = RetTys[I];
8494       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8495                                                      CLI.CallConv, VT);
8496       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8497                                                        CLI.CallConv, VT);
8498       for (unsigned i = 0; i != NumRegs; ++i) {
8499         ISD::InputArg MyFlags;
8500         MyFlags.VT = RegisterVT;
8501         MyFlags.ArgVT = VT;
8502         MyFlags.Used = CLI.IsReturnValueUsed;
8503         if (CLI.RetSExt)
8504           MyFlags.Flags.setSExt();
8505         if (CLI.RetZExt)
8506           MyFlags.Flags.setZExt();
8507         if (CLI.IsInReg)
8508           MyFlags.Flags.setInReg();
8509         CLI.Ins.push_back(MyFlags);
8510       }
8511     }
8512   }
8513 
8514   // We push in swifterror return as the last element of CLI.Ins.
8515   ArgListTy &Args = CLI.getArgs();
8516   if (supportSwiftError()) {
8517     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8518       if (Args[i].IsSwiftError) {
8519         ISD::InputArg MyFlags;
8520         MyFlags.VT = getPointerTy(DL);
8521         MyFlags.ArgVT = EVT(getPointerTy(DL));
8522         MyFlags.Flags.setSwiftError();
8523         CLI.Ins.push_back(MyFlags);
8524       }
8525     }
8526   }
8527 
8528   // Handle all of the outgoing arguments.
8529   CLI.Outs.clear();
8530   CLI.OutVals.clear();
8531   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8532     SmallVector<EVT, 4> ValueVTs;
8533     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8534     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8535     Type *FinalType = Args[i].Ty;
8536     if (Args[i].IsByVal)
8537       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8538     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8539         FinalType, CLI.CallConv, CLI.IsVarArg);
8540     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8541          ++Value) {
8542       EVT VT = ValueVTs[Value];
8543       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8544       SDValue Op = SDValue(Args[i].Node.getNode(),
8545                            Args[i].Node.getResNo() + Value);
8546       ISD::ArgFlagsTy Flags;
8547 
8548       // Certain targets (such as MIPS), may have a different ABI alignment
8549       // for a type depending on the context. Give the target a chance to
8550       // specify the alignment it wants.
8551       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8552 
8553       if (Args[i].IsZExt)
8554         Flags.setZExt();
8555       if (Args[i].IsSExt)
8556         Flags.setSExt();
8557       if (Args[i].IsInReg) {
8558         // If we are using vectorcall calling convention, a structure that is
8559         // passed InReg - is surely an HVA
8560         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8561             isa<StructType>(FinalType)) {
8562           // The first value of a structure is marked
8563           if (0 == Value)
8564             Flags.setHvaStart();
8565           Flags.setHva();
8566         }
8567         // Set InReg Flag
8568         Flags.setInReg();
8569       }
8570       if (Args[i].IsSRet)
8571         Flags.setSRet();
8572       if (Args[i].IsSwiftSelf)
8573         Flags.setSwiftSelf();
8574       if (Args[i].IsSwiftError)
8575         Flags.setSwiftError();
8576       if (Args[i].IsByVal)
8577         Flags.setByVal();
8578       if (Args[i].IsInAlloca) {
8579         Flags.setInAlloca();
8580         // Set the byval flag for CCAssignFn callbacks that don't know about
8581         // inalloca.  This way we can know how many bytes we should've allocated
8582         // and how many bytes a callee cleanup function will pop.  If we port
8583         // inalloca to more targets, we'll have to add custom inalloca handling
8584         // in the various CC lowering callbacks.
8585         Flags.setByVal();
8586       }
8587       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8588         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8589         Type *ElementTy = Ty->getElementType();
8590         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8591         // For ByVal, alignment should come from FE.  BE will guess if this
8592         // info is not there but there are cases it cannot get right.
8593         unsigned FrameAlign;
8594         if (Args[i].Alignment)
8595           FrameAlign = Args[i].Alignment;
8596         else
8597           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8598         Flags.setByValAlign(FrameAlign);
8599       }
8600       if (Args[i].IsNest)
8601         Flags.setNest();
8602       if (NeedsRegBlock)
8603         Flags.setInConsecutiveRegs();
8604       Flags.setOrigAlign(OriginalAlignment);
8605 
8606       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8607                                                  CLI.CallConv, VT);
8608       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8609                                                         CLI.CallConv, VT);
8610       SmallVector<SDValue, 4> Parts(NumParts);
8611       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8612 
8613       if (Args[i].IsSExt)
8614         ExtendKind = ISD::SIGN_EXTEND;
8615       else if (Args[i].IsZExt)
8616         ExtendKind = ISD::ZERO_EXTEND;
8617 
8618       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8619       // for now.
8620       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8621           CanLowerReturn) {
8622         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8623                "unexpected use of 'returned'");
8624         // Before passing 'returned' to the target lowering code, ensure that
8625         // either the register MVT and the actual EVT are the same size or that
8626         // the return value and argument are extended in the same way; in these
8627         // cases it's safe to pass the argument register value unchanged as the
8628         // return register value (although it's at the target's option whether
8629         // to do so)
8630         // TODO: allow code generation to take advantage of partially preserved
8631         // registers rather than clobbering the entire register when the
8632         // parameter extension method is not compatible with the return
8633         // extension method
8634         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8635             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8636              CLI.RetZExt == Args[i].IsZExt))
8637           Flags.setReturned();
8638       }
8639 
8640       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8641                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8642 
8643       for (unsigned j = 0; j != NumParts; ++j) {
8644         // if it isn't first piece, alignment must be 1
8645         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8646                                i < CLI.NumFixedArgs,
8647                                i, j*Parts[j].getValueType().getStoreSize());
8648         if (NumParts > 1 && j == 0)
8649           MyFlags.Flags.setSplit();
8650         else if (j != 0) {
8651           MyFlags.Flags.setOrigAlign(1);
8652           if (j == NumParts - 1)
8653             MyFlags.Flags.setSplitEnd();
8654         }
8655 
8656         CLI.Outs.push_back(MyFlags);
8657         CLI.OutVals.push_back(Parts[j]);
8658       }
8659 
8660       if (NeedsRegBlock && Value == NumValues - 1)
8661         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8662     }
8663   }
8664 
8665   SmallVector<SDValue, 4> InVals;
8666   CLI.Chain = LowerCall(CLI, InVals);
8667 
8668   // Update CLI.InVals to use outside of this function.
8669   CLI.InVals = InVals;
8670 
8671   // Verify that the target's LowerCall behaved as expected.
8672   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8673          "LowerCall didn't return a valid chain!");
8674   assert((!CLI.IsTailCall || InVals.empty()) &&
8675          "LowerCall emitted a return value for a tail call!");
8676   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8677          "LowerCall didn't emit the correct number of values!");
8678 
8679   // For a tail call, the return value is merely live-out and there aren't
8680   // any nodes in the DAG representing it. Return a special value to
8681   // indicate that a tail call has been emitted and no more Instructions
8682   // should be processed in the current block.
8683   if (CLI.IsTailCall) {
8684     CLI.DAG.setRoot(CLI.Chain);
8685     return std::make_pair(SDValue(), SDValue());
8686   }
8687 
8688 #ifndef NDEBUG
8689   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8690     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8691     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8692            "LowerCall emitted a value with the wrong type!");
8693   }
8694 #endif
8695 
8696   SmallVector<SDValue, 4> ReturnValues;
8697   if (!CanLowerReturn) {
8698     // The instruction result is the result of loading from the
8699     // hidden sret parameter.
8700     SmallVector<EVT, 1> PVTs;
8701     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8702 
8703     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8704     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8705     EVT PtrVT = PVTs[0];
8706 
8707     unsigned NumValues = RetTys.size();
8708     ReturnValues.resize(NumValues);
8709     SmallVector<SDValue, 4> Chains(NumValues);
8710 
8711     // An aggregate return value cannot wrap around the address space, so
8712     // offsets to its parts don't wrap either.
8713     SDNodeFlags Flags;
8714     Flags.setNoUnsignedWrap(true);
8715 
8716     for (unsigned i = 0; i < NumValues; ++i) {
8717       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8718                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8719                                                         PtrVT), Flags);
8720       SDValue L = CLI.DAG.getLoad(
8721           RetTys[i], CLI.DL, CLI.Chain, Add,
8722           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8723                                             DemoteStackIdx, Offsets[i]),
8724           /* Alignment = */ 1);
8725       ReturnValues[i] = L;
8726       Chains[i] = L.getValue(1);
8727     }
8728 
8729     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8730   } else {
8731     // Collect the legal value parts into potentially illegal values
8732     // that correspond to the original function's return values.
8733     Optional<ISD::NodeType> AssertOp;
8734     if (CLI.RetSExt)
8735       AssertOp = ISD::AssertSext;
8736     else if (CLI.RetZExt)
8737       AssertOp = ISD::AssertZext;
8738     unsigned CurReg = 0;
8739     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8740       EVT VT = RetTys[I];
8741       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8742                                                      CLI.CallConv, VT);
8743       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8744                                                        CLI.CallConv, VT);
8745 
8746       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8747                                               NumRegs, RegisterVT, VT, nullptr,
8748                                               CLI.CallConv, AssertOp));
8749       CurReg += NumRegs;
8750     }
8751 
8752     // For a function returning void, there is no return value. We can't create
8753     // such a node, so we just return a null return value in that case. In
8754     // that case, nothing will actually look at the value.
8755     if (ReturnValues.empty())
8756       return std::make_pair(SDValue(), CLI.Chain);
8757   }
8758 
8759   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8760                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8761   return std::make_pair(Res, CLI.Chain);
8762 }
8763 
8764 void TargetLowering::LowerOperationWrapper(SDNode *N,
8765                                            SmallVectorImpl<SDValue> &Results,
8766                                            SelectionDAG &DAG) const {
8767   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8768     Results.push_back(Res);
8769 }
8770 
8771 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8772   llvm_unreachable("LowerOperation not implemented for this target!");
8773 }
8774 
8775 void
8776 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8777   SDValue Op = getNonRegisterValue(V);
8778   assert((Op.getOpcode() != ISD::CopyFromReg ||
8779           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8780          "Copy from a reg to the same reg!");
8781   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8782 
8783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8784   // If this is an InlineAsm we have to match the registers required, not the
8785   // notional registers required by the type.
8786 
8787   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
8788                    None); // This is not an ABI copy.
8789   SDValue Chain = DAG.getEntryNode();
8790 
8791   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8792                               FuncInfo.PreferredExtendType.end())
8793                                  ? ISD::ANY_EXTEND
8794                                  : FuncInfo.PreferredExtendType[V];
8795   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8796   PendingExports.push_back(Chain);
8797 }
8798 
8799 #include "llvm/CodeGen/SelectionDAGISel.h"
8800 
8801 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8802 /// entry block, return true.  This includes arguments used by switches, since
8803 /// the switch may expand into multiple basic blocks.
8804 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8805   // With FastISel active, we may be splitting blocks, so force creation
8806   // of virtual registers for all non-dead arguments.
8807   if (FastISel)
8808     return A->use_empty();
8809 
8810   const BasicBlock &Entry = A->getParent()->front();
8811   for (const User *U : A->users())
8812     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8813       return false;  // Use not in entry block.
8814 
8815   return true;
8816 }
8817 
8818 using ArgCopyElisionMapTy =
8819     DenseMap<const Argument *,
8820              std::pair<const AllocaInst *, const StoreInst *>>;
8821 
8822 /// Scan the entry block of the function in FuncInfo for arguments that look
8823 /// like copies into a local alloca. Record any copied arguments in
8824 /// ArgCopyElisionCandidates.
8825 static void
8826 findArgumentCopyElisionCandidates(const DataLayout &DL,
8827                                   FunctionLoweringInfo *FuncInfo,
8828                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8829   // Record the state of every static alloca used in the entry block. Argument
8830   // allocas are all used in the entry block, so we need approximately as many
8831   // entries as we have arguments.
8832   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8833   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8834   unsigned NumArgs = FuncInfo->Fn->arg_size();
8835   StaticAllocas.reserve(NumArgs * 2);
8836 
8837   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8838     if (!V)
8839       return nullptr;
8840     V = V->stripPointerCasts();
8841     const auto *AI = dyn_cast<AllocaInst>(V);
8842     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8843       return nullptr;
8844     auto Iter = StaticAllocas.insert({AI, Unknown});
8845     return &Iter.first->second;
8846   };
8847 
8848   // Look for stores of arguments to static allocas. Look through bitcasts and
8849   // GEPs to handle type coercions, as long as the alloca is fully initialized
8850   // by the store. Any non-store use of an alloca escapes it and any subsequent
8851   // unanalyzed store might write it.
8852   // FIXME: Handle structs initialized with multiple stores.
8853   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8854     // Look for stores, and handle non-store uses conservatively.
8855     const auto *SI = dyn_cast<StoreInst>(&I);
8856     if (!SI) {
8857       // We will look through cast uses, so ignore them completely.
8858       if (I.isCast())
8859         continue;
8860       // Ignore debug info intrinsics, they don't escape or store to allocas.
8861       if (isa<DbgInfoIntrinsic>(I))
8862         continue;
8863       // This is an unknown instruction. Assume it escapes or writes to all
8864       // static alloca operands.
8865       for (const Use &U : I.operands()) {
8866         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8867           *Info = StaticAllocaInfo::Clobbered;
8868       }
8869       continue;
8870     }
8871 
8872     // If the stored value is a static alloca, mark it as escaped.
8873     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8874       *Info = StaticAllocaInfo::Clobbered;
8875 
8876     // Check if the destination is a static alloca.
8877     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8878     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8879     if (!Info)
8880       continue;
8881     const AllocaInst *AI = cast<AllocaInst>(Dst);
8882 
8883     // Skip allocas that have been initialized or clobbered.
8884     if (*Info != StaticAllocaInfo::Unknown)
8885       continue;
8886 
8887     // Check if the stored value is an argument, and that this store fully
8888     // initializes the alloca. Don't elide copies from the same argument twice.
8889     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8890     const auto *Arg = dyn_cast<Argument>(Val);
8891     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8892         Arg->getType()->isEmptyTy() ||
8893         DL.getTypeStoreSize(Arg->getType()) !=
8894             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8895         ArgCopyElisionCandidates.count(Arg)) {
8896       *Info = StaticAllocaInfo::Clobbered;
8897       continue;
8898     }
8899 
8900     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
8901                       << '\n');
8902 
8903     // Mark this alloca and store for argument copy elision.
8904     *Info = StaticAllocaInfo::Elidable;
8905     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8906 
8907     // Stop scanning if we've seen all arguments. This will happen early in -O0
8908     // builds, which is useful, because -O0 builds have large entry blocks and
8909     // many allocas.
8910     if (ArgCopyElisionCandidates.size() == NumArgs)
8911       break;
8912   }
8913 }
8914 
8915 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8916 /// ArgVal is a load from a suitable fixed stack object.
8917 static void tryToElideArgumentCopy(
8918     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8919     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8920     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8921     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8922     SDValue ArgVal, bool &ArgHasUses) {
8923   // Check if this is a load from a fixed stack object.
8924   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8925   if (!LNode)
8926     return;
8927   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8928   if (!FINode)
8929     return;
8930 
8931   // Check that the fixed stack object is the right size and alignment.
8932   // Look at the alignment that the user wrote on the alloca instead of looking
8933   // at the stack object.
8934   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8935   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8936   const AllocaInst *AI = ArgCopyIter->second.first;
8937   int FixedIndex = FINode->getIndex();
8938   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8939   int OldIndex = AllocaIndex;
8940   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8941   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8942     LLVM_DEBUG(
8943         dbgs() << "  argument copy elision failed due to bad fixed stack "
8944                   "object size\n");
8945     return;
8946   }
8947   unsigned RequiredAlignment = AI->getAlignment();
8948   if (!RequiredAlignment) {
8949     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8950         AI->getAllocatedType());
8951   }
8952   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8953     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8954                          "greater than stack argument alignment ("
8955                       << RequiredAlignment << " vs "
8956                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
8957     return;
8958   }
8959 
8960   // Perform the elision. Delete the old stack object and replace its only use
8961   // in the variable info map. Mark the stack object as mutable.
8962   LLVM_DEBUG({
8963     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8964            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8965            << '\n';
8966   });
8967   MFI.RemoveStackObject(OldIndex);
8968   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8969   AllocaIndex = FixedIndex;
8970   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8971   Chains.push_back(ArgVal.getValue(1));
8972 
8973   // Avoid emitting code for the store implementing the copy.
8974   const StoreInst *SI = ArgCopyIter->second.second;
8975   ElidedArgCopyInstrs.insert(SI);
8976 
8977   // Check for uses of the argument again so that we can avoid exporting ArgVal
8978   // if it is't used by anything other than the store.
8979   for (const Value *U : Arg.users()) {
8980     if (U != SI) {
8981       ArgHasUses = true;
8982       break;
8983     }
8984   }
8985 }
8986 
8987 void SelectionDAGISel::LowerArguments(const Function &F) {
8988   SelectionDAG &DAG = SDB->DAG;
8989   SDLoc dl = SDB->getCurSDLoc();
8990   const DataLayout &DL = DAG.getDataLayout();
8991   SmallVector<ISD::InputArg, 16> Ins;
8992 
8993   if (!FuncInfo->CanLowerReturn) {
8994     // Put in an sret pointer parameter before all the other parameters.
8995     SmallVector<EVT, 1> ValueVTs;
8996     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8997                     F.getReturnType()->getPointerTo(
8998                         DAG.getDataLayout().getAllocaAddrSpace()),
8999                     ValueVTs);
9000 
9001     // NOTE: Assuming that a pointer will never break down to more than one VT
9002     // or one register.
9003     ISD::ArgFlagsTy Flags;
9004     Flags.setSRet();
9005     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9006     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9007                          ISD::InputArg::NoArgIndex, 0);
9008     Ins.push_back(RetArg);
9009   }
9010 
9011   // Look for stores of arguments to static allocas. Mark such arguments with a
9012   // flag to ask the target to give us the memory location of that argument if
9013   // available.
9014   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9015   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9016 
9017   // Set up the incoming argument description vector.
9018   for (const Argument &Arg : F.args()) {
9019     unsigned ArgNo = Arg.getArgNo();
9020     SmallVector<EVT, 4> ValueVTs;
9021     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9022     bool isArgValueUsed = !Arg.use_empty();
9023     unsigned PartBase = 0;
9024     Type *FinalType = Arg.getType();
9025     if (Arg.hasAttribute(Attribute::ByVal))
9026       FinalType = cast<PointerType>(FinalType)->getElementType();
9027     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9028         FinalType, F.getCallingConv(), F.isVarArg());
9029     for (unsigned Value = 0, NumValues = ValueVTs.size();
9030          Value != NumValues; ++Value) {
9031       EVT VT = ValueVTs[Value];
9032       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9033       ISD::ArgFlagsTy Flags;
9034 
9035       // Certain targets (such as MIPS), may have a different ABI alignment
9036       // for a type depending on the context. Give the target a chance to
9037       // specify the alignment it wants.
9038       unsigned OriginalAlignment =
9039           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9040 
9041       if (Arg.hasAttribute(Attribute::ZExt))
9042         Flags.setZExt();
9043       if (Arg.hasAttribute(Attribute::SExt))
9044         Flags.setSExt();
9045       if (Arg.hasAttribute(Attribute::InReg)) {
9046         // If we are using vectorcall calling convention, a structure that is
9047         // passed InReg - is surely an HVA
9048         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9049             isa<StructType>(Arg.getType())) {
9050           // The first value of a structure is marked
9051           if (0 == Value)
9052             Flags.setHvaStart();
9053           Flags.setHva();
9054         }
9055         // Set InReg Flag
9056         Flags.setInReg();
9057       }
9058       if (Arg.hasAttribute(Attribute::StructRet))
9059         Flags.setSRet();
9060       if (Arg.hasAttribute(Attribute::SwiftSelf))
9061         Flags.setSwiftSelf();
9062       if (Arg.hasAttribute(Attribute::SwiftError))
9063         Flags.setSwiftError();
9064       if (Arg.hasAttribute(Attribute::ByVal))
9065         Flags.setByVal();
9066       if (Arg.hasAttribute(Attribute::InAlloca)) {
9067         Flags.setInAlloca();
9068         // Set the byval flag for CCAssignFn callbacks that don't know about
9069         // inalloca.  This way we can know how many bytes we should've allocated
9070         // and how many bytes a callee cleanup function will pop.  If we port
9071         // inalloca to more targets, we'll have to add custom inalloca handling
9072         // in the various CC lowering callbacks.
9073         Flags.setByVal();
9074       }
9075       if (F.getCallingConv() == CallingConv::X86_INTR) {
9076         // IA Interrupt passes frame (1st parameter) by value in the stack.
9077         if (ArgNo == 0)
9078           Flags.setByVal();
9079       }
9080       if (Flags.isByVal() || Flags.isInAlloca()) {
9081         PointerType *Ty = cast<PointerType>(Arg.getType());
9082         Type *ElementTy = Ty->getElementType();
9083         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9084         // For ByVal, alignment should be passed from FE.  BE will guess if
9085         // this info is not there but there are cases it cannot get right.
9086         unsigned FrameAlign;
9087         if (Arg.getParamAlignment())
9088           FrameAlign = Arg.getParamAlignment();
9089         else
9090           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9091         Flags.setByValAlign(FrameAlign);
9092       }
9093       if (Arg.hasAttribute(Attribute::Nest))
9094         Flags.setNest();
9095       if (NeedsRegBlock)
9096         Flags.setInConsecutiveRegs();
9097       Flags.setOrigAlign(OriginalAlignment);
9098       if (ArgCopyElisionCandidates.count(&Arg))
9099         Flags.setCopyElisionCandidate();
9100 
9101       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9102           *CurDAG->getContext(), F.getCallingConv(), VT);
9103       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9104           *CurDAG->getContext(), F.getCallingConv(), VT);
9105       for (unsigned i = 0; i != NumRegs; ++i) {
9106         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9107                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9108         if (NumRegs > 1 && i == 0)
9109           MyFlags.Flags.setSplit();
9110         // if it isn't first piece, alignment must be 1
9111         else if (i > 0) {
9112           MyFlags.Flags.setOrigAlign(1);
9113           if (i == NumRegs - 1)
9114             MyFlags.Flags.setSplitEnd();
9115         }
9116         Ins.push_back(MyFlags);
9117       }
9118       if (NeedsRegBlock && Value == NumValues - 1)
9119         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9120       PartBase += VT.getStoreSize();
9121     }
9122   }
9123 
9124   // Call the target to set up the argument values.
9125   SmallVector<SDValue, 8> InVals;
9126   SDValue NewRoot = TLI->LowerFormalArguments(
9127       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9128 
9129   // Verify that the target's LowerFormalArguments behaved as expected.
9130   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9131          "LowerFormalArguments didn't return a valid chain!");
9132   assert(InVals.size() == Ins.size() &&
9133          "LowerFormalArguments didn't emit the correct number of values!");
9134   LLVM_DEBUG({
9135     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9136       assert(InVals[i].getNode() &&
9137              "LowerFormalArguments emitted a null value!");
9138       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9139              "LowerFormalArguments emitted a value with the wrong type!");
9140     }
9141   });
9142 
9143   // Update the DAG with the new chain value resulting from argument lowering.
9144   DAG.setRoot(NewRoot);
9145 
9146   // Set up the argument values.
9147   unsigned i = 0;
9148   if (!FuncInfo->CanLowerReturn) {
9149     // Create a virtual register for the sret pointer, and put in a copy
9150     // from the sret argument into it.
9151     SmallVector<EVT, 1> ValueVTs;
9152     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9153                     F.getReturnType()->getPointerTo(
9154                         DAG.getDataLayout().getAllocaAddrSpace()),
9155                     ValueVTs);
9156     MVT VT = ValueVTs[0].getSimpleVT();
9157     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9158     Optional<ISD::NodeType> AssertOp = None;
9159     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9160                                         nullptr, F.getCallingConv(), AssertOp);
9161 
9162     MachineFunction& MF = SDB->DAG.getMachineFunction();
9163     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9164     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9165     FuncInfo->DemoteRegister = SRetReg;
9166     NewRoot =
9167         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9168     DAG.setRoot(NewRoot);
9169 
9170     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9171     ++i;
9172   }
9173 
9174   SmallVector<SDValue, 4> Chains;
9175   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9176   for (const Argument &Arg : F.args()) {
9177     SmallVector<SDValue, 4> ArgValues;
9178     SmallVector<EVT, 4> ValueVTs;
9179     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9180     unsigned NumValues = ValueVTs.size();
9181     if (NumValues == 0)
9182       continue;
9183 
9184     bool ArgHasUses = !Arg.use_empty();
9185 
9186     // Elide the copying store if the target loaded this argument from a
9187     // suitable fixed stack object.
9188     if (Ins[i].Flags.isCopyElisionCandidate()) {
9189       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9190                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9191                              InVals[i], ArgHasUses);
9192     }
9193 
9194     // If this argument is unused then remember its value. It is used to generate
9195     // debugging information.
9196     bool isSwiftErrorArg =
9197         TLI->supportSwiftError() &&
9198         Arg.hasAttribute(Attribute::SwiftError);
9199     if (!ArgHasUses && !isSwiftErrorArg) {
9200       SDB->setUnusedArgValue(&Arg, InVals[i]);
9201 
9202       // Also remember any frame index for use in FastISel.
9203       if (FrameIndexSDNode *FI =
9204           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9205         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9206     }
9207 
9208     for (unsigned Val = 0; Val != NumValues; ++Val) {
9209       EVT VT = ValueVTs[Val];
9210       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9211                                                       F.getCallingConv(), VT);
9212       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9213           *CurDAG->getContext(), F.getCallingConv(), VT);
9214 
9215       // Even an apparant 'unused' swifterror argument needs to be returned. So
9216       // we do generate a copy for it that can be used on return from the
9217       // function.
9218       if (ArgHasUses || isSwiftErrorArg) {
9219         Optional<ISD::NodeType> AssertOp;
9220         if (Arg.hasAttribute(Attribute::SExt))
9221           AssertOp = ISD::AssertSext;
9222         else if (Arg.hasAttribute(Attribute::ZExt))
9223           AssertOp = ISD::AssertZext;
9224 
9225         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9226                                              PartVT, VT, nullptr,
9227                                              F.getCallingConv(), AssertOp));
9228       }
9229 
9230       i += NumParts;
9231     }
9232 
9233     // We don't need to do anything else for unused arguments.
9234     if (ArgValues.empty())
9235       continue;
9236 
9237     // Note down frame index.
9238     if (FrameIndexSDNode *FI =
9239         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9240       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9241 
9242     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9243                                      SDB->getCurSDLoc());
9244 
9245     SDB->setValue(&Arg, Res);
9246     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9247       // We want to associate the argument with the frame index, among
9248       // involved operands, that correspond to the lowest address. The
9249       // getCopyFromParts function, called earlier, is swapping the order of
9250       // the operands to BUILD_PAIR depending on endianness. The result of
9251       // that swapping is that the least significant bits of the argument will
9252       // be in the first operand of the BUILD_PAIR node, and the most
9253       // significant bits will be in the second operand.
9254       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9255       if (LoadSDNode *LNode =
9256           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9257         if (FrameIndexSDNode *FI =
9258             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9259           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9260     }
9261 
9262     // Update the SwiftErrorVRegDefMap.
9263     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9264       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9265       if (TargetRegisterInfo::isVirtualRegister(Reg))
9266         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9267                                            FuncInfo->SwiftErrorArg, Reg);
9268     }
9269 
9270     // If this argument is live outside of the entry block, insert a copy from
9271     // wherever we got it to the vreg that other BB's will reference it as.
9272     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9273       // If we can, though, try to skip creating an unnecessary vreg.
9274       // FIXME: This isn't very clean... it would be nice to make this more
9275       // general.  It's also subtly incompatible with the hacks FastISel
9276       // uses with vregs.
9277       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9278       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9279         FuncInfo->ValueMap[&Arg] = Reg;
9280         continue;
9281       }
9282     }
9283     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9284       FuncInfo->InitializeRegForValue(&Arg);
9285       SDB->CopyToExportRegsIfNeeded(&Arg);
9286     }
9287   }
9288 
9289   if (!Chains.empty()) {
9290     Chains.push_back(NewRoot);
9291     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9292   }
9293 
9294   DAG.setRoot(NewRoot);
9295 
9296   assert(i == InVals.size() && "Argument register count mismatch!");
9297 
9298   // If any argument copy elisions occurred and we have debug info, update the
9299   // stale frame indices used in the dbg.declare variable info table.
9300   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9301   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9302     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9303       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9304       if (I != ArgCopyElisionFrameIndexMap.end())
9305         VI.Slot = I->second;
9306     }
9307   }
9308 
9309   // Finally, if the target has anything special to do, allow it to do so.
9310   EmitFunctionEntryCode();
9311 }
9312 
9313 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9314 /// ensure constants are generated when needed.  Remember the virtual registers
9315 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9316 /// directly add them, because expansion might result in multiple MBB's for one
9317 /// BB.  As such, the start of the BB might correspond to a different MBB than
9318 /// the end.
9319 void
9320 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9321   const Instruction *TI = LLVMBB->getTerminator();
9322 
9323   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9324 
9325   // Check PHI nodes in successors that expect a value to be available from this
9326   // block.
9327   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9328     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9329     if (!isa<PHINode>(SuccBB->begin())) continue;
9330     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9331 
9332     // If this terminator has multiple identical successors (common for
9333     // switches), only handle each succ once.
9334     if (!SuccsHandled.insert(SuccMBB).second)
9335       continue;
9336 
9337     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9338 
9339     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9340     // nodes and Machine PHI nodes, but the incoming operands have not been
9341     // emitted yet.
9342     for (const PHINode &PN : SuccBB->phis()) {
9343       // Ignore dead phi's.
9344       if (PN.use_empty())
9345         continue;
9346 
9347       // Skip empty types
9348       if (PN.getType()->isEmptyTy())
9349         continue;
9350 
9351       unsigned Reg;
9352       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9353 
9354       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9355         unsigned &RegOut = ConstantsOut[C];
9356         if (RegOut == 0) {
9357           RegOut = FuncInfo.CreateRegs(C->getType());
9358           CopyValueToVirtualRegister(C, RegOut);
9359         }
9360         Reg = RegOut;
9361       } else {
9362         DenseMap<const Value *, unsigned>::iterator I =
9363           FuncInfo.ValueMap.find(PHIOp);
9364         if (I != FuncInfo.ValueMap.end())
9365           Reg = I->second;
9366         else {
9367           assert(isa<AllocaInst>(PHIOp) &&
9368                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9369                  "Didn't codegen value into a register!??");
9370           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9371           CopyValueToVirtualRegister(PHIOp, Reg);
9372         }
9373       }
9374 
9375       // Remember that this register needs to added to the machine PHI node as
9376       // the input for this MBB.
9377       SmallVector<EVT, 4> ValueVTs;
9378       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9379       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9380       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9381         EVT VT = ValueVTs[vti];
9382         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9383         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9384           FuncInfo.PHINodesToUpdate.push_back(
9385               std::make_pair(&*MBBI++, Reg + i));
9386         Reg += NumRegisters;
9387       }
9388     }
9389   }
9390 
9391   ConstantsOut.clear();
9392 }
9393 
9394 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9395 /// is 0.
9396 MachineBasicBlock *
9397 SelectionDAGBuilder::StackProtectorDescriptor::
9398 AddSuccessorMBB(const BasicBlock *BB,
9399                 MachineBasicBlock *ParentMBB,
9400                 bool IsLikely,
9401                 MachineBasicBlock *SuccMBB) {
9402   // If SuccBB has not been created yet, create it.
9403   if (!SuccMBB) {
9404     MachineFunction *MF = ParentMBB->getParent();
9405     MachineFunction::iterator BBI(ParentMBB);
9406     SuccMBB = MF->CreateMachineBasicBlock(BB);
9407     MF->insert(++BBI, SuccMBB);
9408   }
9409   // Add it as a successor of ParentMBB.
9410   ParentMBB->addSuccessor(
9411       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9412   return SuccMBB;
9413 }
9414 
9415 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9416   MachineFunction::iterator I(MBB);
9417   if (++I == FuncInfo.MF->end())
9418     return nullptr;
9419   return &*I;
9420 }
9421 
9422 /// During lowering new call nodes can be created (such as memset, etc.).
9423 /// Those will become new roots of the current DAG, but complications arise
9424 /// when they are tail calls. In such cases, the call lowering will update
9425 /// the root, but the builder still needs to know that a tail call has been
9426 /// lowered in order to avoid generating an additional return.
9427 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9428   // If the node is null, we do have a tail call.
9429   if (MaybeTC.getNode() != nullptr)
9430     DAG.setRoot(MaybeTC);
9431   else
9432     HasTailCall = true;
9433 }
9434 
9435 uint64_t
9436 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9437                                        unsigned First, unsigned Last) const {
9438   assert(Last >= First);
9439   const APInt &LowCase = Clusters[First].Low->getValue();
9440   const APInt &HighCase = Clusters[Last].High->getValue();
9441   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9442 
9443   // FIXME: A range of consecutive cases has 100% density, but only requires one
9444   // comparison to lower. We should discriminate against such consecutive ranges
9445   // in jump tables.
9446 
9447   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9448 }
9449 
9450 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9451     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9452     unsigned Last) const {
9453   assert(Last >= First);
9454   assert(TotalCases[Last] >= TotalCases[First]);
9455   uint64_t NumCases =
9456       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9457   return NumCases;
9458 }
9459 
9460 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9461                                          unsigned First, unsigned Last,
9462                                          const SwitchInst *SI,
9463                                          MachineBasicBlock *DefaultMBB,
9464                                          CaseCluster &JTCluster) {
9465   assert(First <= Last);
9466 
9467   auto Prob = BranchProbability::getZero();
9468   unsigned NumCmps = 0;
9469   std::vector<MachineBasicBlock*> Table;
9470   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9471 
9472   // Initialize probabilities in JTProbs.
9473   for (unsigned I = First; I <= Last; ++I)
9474     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9475 
9476   for (unsigned I = First; I <= Last; ++I) {
9477     assert(Clusters[I].Kind == CC_Range);
9478     Prob += Clusters[I].Prob;
9479     const APInt &Low = Clusters[I].Low->getValue();
9480     const APInt &High = Clusters[I].High->getValue();
9481     NumCmps += (Low == High) ? 1 : 2;
9482     if (I != First) {
9483       // Fill the gap between this and the previous cluster.
9484       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9485       assert(PreviousHigh.slt(Low));
9486       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9487       for (uint64_t J = 0; J < Gap; J++)
9488         Table.push_back(DefaultMBB);
9489     }
9490     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9491     for (uint64_t J = 0; J < ClusterSize; ++J)
9492       Table.push_back(Clusters[I].MBB);
9493     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9494   }
9495 
9496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9497   unsigned NumDests = JTProbs.size();
9498   if (TLI.isSuitableForBitTests(
9499           NumDests, NumCmps, Clusters[First].Low->getValue(),
9500           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9501     // Clusters[First..Last] should be lowered as bit tests instead.
9502     return false;
9503   }
9504 
9505   // Create the MBB that will load from and jump through the table.
9506   // Note: We create it here, but it's not inserted into the function yet.
9507   MachineFunction *CurMF = FuncInfo.MF;
9508   MachineBasicBlock *JumpTableMBB =
9509       CurMF->CreateMachineBasicBlock(SI->getParent());
9510 
9511   // Add successors. Note: use table order for determinism.
9512   SmallPtrSet<MachineBasicBlock *, 8> Done;
9513   for (MachineBasicBlock *Succ : Table) {
9514     if (Done.count(Succ))
9515       continue;
9516     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9517     Done.insert(Succ);
9518   }
9519   JumpTableMBB->normalizeSuccProbs();
9520 
9521   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9522                      ->createJumpTableIndex(Table);
9523 
9524   // Set up the jump table info.
9525   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9526   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9527                       Clusters[Last].High->getValue(), SI->getCondition(),
9528                       nullptr, false);
9529   JTCases.emplace_back(std::move(JTH), std::move(JT));
9530 
9531   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9532                                      JTCases.size() - 1, Prob);
9533   return true;
9534 }
9535 
9536 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9537                                          const SwitchInst *SI,
9538                                          MachineBasicBlock *DefaultMBB) {
9539 #ifndef NDEBUG
9540   // Clusters must be non-empty, sorted, and only contain Range clusters.
9541   assert(!Clusters.empty());
9542   for (CaseCluster &C : Clusters)
9543     assert(C.Kind == CC_Range);
9544   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9545     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9546 #endif
9547 
9548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9549   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9550     return;
9551 
9552   const int64_t N = Clusters.size();
9553   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9554   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9555 
9556   if (N < 2 || N < MinJumpTableEntries)
9557     return;
9558 
9559   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9560   SmallVector<unsigned, 8> TotalCases(N);
9561   for (unsigned i = 0; i < N; ++i) {
9562     const APInt &Hi = Clusters[i].High->getValue();
9563     const APInt &Lo = Clusters[i].Low->getValue();
9564     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9565     if (i != 0)
9566       TotalCases[i] += TotalCases[i - 1];
9567   }
9568 
9569   // Cheap case: the whole range may be suitable for jump table.
9570   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9571   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9572   assert(NumCases < UINT64_MAX / 100);
9573   assert(Range >= NumCases);
9574   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9575     CaseCluster JTCluster;
9576     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9577       Clusters[0] = JTCluster;
9578       Clusters.resize(1);
9579       return;
9580     }
9581   }
9582 
9583   // The algorithm below is not suitable for -O0.
9584   if (TM.getOptLevel() == CodeGenOpt::None)
9585     return;
9586 
9587   // Split Clusters into minimum number of dense partitions. The algorithm uses
9588   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9589   // for the Case Statement'" (1994), but builds the MinPartitions array in
9590   // reverse order to make it easier to reconstruct the partitions in ascending
9591   // order. In the choice between two optimal partitionings, it picks the one
9592   // which yields more jump tables.
9593 
9594   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9595   SmallVector<unsigned, 8> MinPartitions(N);
9596   // LastElement[i] is the last element of the partition starting at i.
9597   SmallVector<unsigned, 8> LastElement(N);
9598   // PartitionsScore[i] is used to break ties when choosing between two
9599   // partitionings resulting in the same number of partitions.
9600   SmallVector<unsigned, 8> PartitionsScore(N);
9601   // For PartitionsScore, a small number of comparisons is considered as good as
9602   // a jump table and a single comparison is considered better than a jump
9603   // table.
9604   enum PartitionScores : unsigned {
9605     NoTable = 0,
9606     Table = 1,
9607     FewCases = 1,
9608     SingleCase = 2
9609   };
9610 
9611   // Base case: There is only one way to partition Clusters[N-1].
9612   MinPartitions[N - 1] = 1;
9613   LastElement[N - 1] = N - 1;
9614   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9615 
9616   // Note: loop indexes are signed to avoid underflow.
9617   for (int64_t i = N - 2; i >= 0; i--) {
9618     // Find optimal partitioning of Clusters[i..N-1].
9619     // Baseline: Put Clusters[i] into a partition on its own.
9620     MinPartitions[i] = MinPartitions[i + 1] + 1;
9621     LastElement[i] = i;
9622     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9623 
9624     // Search for a solution that results in fewer partitions.
9625     for (int64_t j = N - 1; j > i; j--) {
9626       // Try building a partition from Clusters[i..j].
9627       uint64_t Range = getJumpTableRange(Clusters, i, j);
9628       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9629       assert(NumCases < UINT64_MAX / 100);
9630       assert(Range >= NumCases);
9631       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9632         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9633         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9634         int64_t NumEntries = j - i + 1;
9635 
9636         if (NumEntries == 1)
9637           Score += PartitionScores::SingleCase;
9638         else if (NumEntries <= SmallNumberOfEntries)
9639           Score += PartitionScores::FewCases;
9640         else if (NumEntries >= MinJumpTableEntries)
9641           Score += PartitionScores::Table;
9642 
9643         // If this leads to fewer partitions, or to the same number of
9644         // partitions with better score, it is a better partitioning.
9645         if (NumPartitions < MinPartitions[i] ||
9646             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9647           MinPartitions[i] = NumPartitions;
9648           LastElement[i] = j;
9649           PartitionsScore[i] = Score;
9650         }
9651       }
9652     }
9653   }
9654 
9655   // Iterate over the partitions, replacing some with jump tables in-place.
9656   unsigned DstIndex = 0;
9657   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9658     Last = LastElement[First];
9659     assert(Last >= First);
9660     assert(DstIndex <= First);
9661     unsigned NumClusters = Last - First + 1;
9662 
9663     CaseCluster JTCluster;
9664     if (NumClusters >= MinJumpTableEntries &&
9665         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9666       Clusters[DstIndex++] = JTCluster;
9667     } else {
9668       for (unsigned I = First; I <= Last; ++I)
9669         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9670     }
9671   }
9672   Clusters.resize(DstIndex);
9673 }
9674 
9675 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9676                                         unsigned First, unsigned Last,
9677                                         const SwitchInst *SI,
9678                                         CaseCluster &BTCluster) {
9679   assert(First <= Last);
9680   if (First == Last)
9681     return false;
9682 
9683   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9684   unsigned NumCmps = 0;
9685   for (int64_t I = First; I <= Last; ++I) {
9686     assert(Clusters[I].Kind == CC_Range);
9687     Dests.set(Clusters[I].MBB->getNumber());
9688     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9689   }
9690   unsigned NumDests = Dests.count();
9691 
9692   APInt Low = Clusters[First].Low->getValue();
9693   APInt High = Clusters[Last].High->getValue();
9694   assert(Low.slt(High));
9695 
9696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9697   const DataLayout &DL = DAG.getDataLayout();
9698   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9699     return false;
9700 
9701   APInt LowBound;
9702   APInt CmpRange;
9703 
9704   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9705   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9706          "Case range must fit in bit mask!");
9707 
9708   // Check if the clusters cover a contiguous range such that no value in the
9709   // range will jump to the default statement.
9710   bool ContiguousRange = true;
9711   for (int64_t I = First + 1; I <= Last; ++I) {
9712     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9713       ContiguousRange = false;
9714       break;
9715     }
9716   }
9717 
9718   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9719     // Optimize the case where all the case values fit in a word without having
9720     // to subtract minValue. In this case, we can optimize away the subtraction.
9721     LowBound = APInt::getNullValue(Low.getBitWidth());
9722     CmpRange = High;
9723     ContiguousRange = false;
9724   } else {
9725     LowBound = Low;
9726     CmpRange = High - Low;
9727   }
9728 
9729   CaseBitsVector CBV;
9730   auto TotalProb = BranchProbability::getZero();
9731   for (unsigned i = First; i <= Last; ++i) {
9732     // Find the CaseBits for this destination.
9733     unsigned j;
9734     for (j = 0; j < CBV.size(); ++j)
9735       if (CBV[j].BB == Clusters[i].MBB)
9736         break;
9737     if (j == CBV.size())
9738       CBV.push_back(
9739           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9740     CaseBits *CB = &CBV[j];
9741 
9742     // Update Mask, Bits and ExtraProb.
9743     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9744     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9745     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9746     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9747     CB->Bits += Hi - Lo + 1;
9748     CB->ExtraProb += Clusters[i].Prob;
9749     TotalProb += Clusters[i].Prob;
9750   }
9751 
9752   BitTestInfo BTI;
9753   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
9754     // Sort by probability first, number of bits second, bit mask third.
9755     if (a.ExtraProb != b.ExtraProb)
9756       return a.ExtraProb > b.ExtraProb;
9757     if (a.Bits != b.Bits)
9758       return a.Bits > b.Bits;
9759     return a.Mask < b.Mask;
9760   });
9761 
9762   for (auto &CB : CBV) {
9763     MachineBasicBlock *BitTestBB =
9764         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9765     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9766   }
9767   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9768                             SI->getCondition(), -1U, MVT::Other, false,
9769                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9770                             TotalProb);
9771 
9772   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9773                                     BitTestCases.size() - 1, TotalProb);
9774   return true;
9775 }
9776 
9777 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9778                                               const SwitchInst *SI) {
9779 // Partition Clusters into as few subsets as possible, where each subset has a
9780 // range that fits in a machine word and has <= 3 unique destinations.
9781 
9782 #ifndef NDEBUG
9783   // Clusters must be sorted and contain Range or JumpTable clusters.
9784   assert(!Clusters.empty());
9785   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9786   for (const CaseCluster &C : Clusters)
9787     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9788   for (unsigned i = 1; i < Clusters.size(); ++i)
9789     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9790 #endif
9791 
9792   // The algorithm below is not suitable for -O0.
9793   if (TM.getOptLevel() == CodeGenOpt::None)
9794     return;
9795 
9796   // If target does not have legal shift left, do not emit bit tests at all.
9797   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9798   const DataLayout &DL = DAG.getDataLayout();
9799 
9800   EVT PTy = TLI.getPointerTy(DL);
9801   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9802     return;
9803 
9804   int BitWidth = PTy.getSizeInBits();
9805   const int64_t N = Clusters.size();
9806 
9807   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9808   SmallVector<unsigned, 8> MinPartitions(N);
9809   // LastElement[i] is the last element of the partition starting at i.
9810   SmallVector<unsigned, 8> LastElement(N);
9811 
9812   // FIXME: This might not be the best algorithm for finding bit test clusters.
9813 
9814   // Base case: There is only one way to partition Clusters[N-1].
9815   MinPartitions[N - 1] = 1;
9816   LastElement[N - 1] = N - 1;
9817 
9818   // Note: loop indexes are signed to avoid underflow.
9819   for (int64_t i = N - 2; i >= 0; --i) {
9820     // Find optimal partitioning of Clusters[i..N-1].
9821     // Baseline: Put Clusters[i] into a partition on its own.
9822     MinPartitions[i] = MinPartitions[i + 1] + 1;
9823     LastElement[i] = i;
9824 
9825     // Search for a solution that results in fewer partitions.
9826     // Note: the search is limited by BitWidth, reducing time complexity.
9827     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9828       // Try building a partition from Clusters[i..j].
9829 
9830       // Check the range.
9831       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9832                                Clusters[j].High->getValue(), DL))
9833         continue;
9834 
9835       // Check nbr of destinations and cluster types.
9836       // FIXME: This works, but doesn't seem very efficient.
9837       bool RangesOnly = true;
9838       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9839       for (int64_t k = i; k <= j; k++) {
9840         if (Clusters[k].Kind != CC_Range) {
9841           RangesOnly = false;
9842           break;
9843         }
9844         Dests.set(Clusters[k].MBB->getNumber());
9845       }
9846       if (!RangesOnly || Dests.count() > 3)
9847         break;
9848 
9849       // Check if it's a better partition.
9850       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9851       if (NumPartitions < MinPartitions[i]) {
9852         // Found a better partition.
9853         MinPartitions[i] = NumPartitions;
9854         LastElement[i] = j;
9855       }
9856     }
9857   }
9858 
9859   // Iterate over the partitions, replacing with bit-test clusters in-place.
9860   unsigned DstIndex = 0;
9861   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9862     Last = LastElement[First];
9863     assert(First <= Last);
9864     assert(DstIndex <= First);
9865 
9866     CaseCluster BitTestCluster;
9867     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9868       Clusters[DstIndex++] = BitTestCluster;
9869     } else {
9870       size_t NumClusters = Last - First + 1;
9871       std::memmove(&Clusters[DstIndex], &Clusters[First],
9872                    sizeof(Clusters[0]) * NumClusters);
9873       DstIndex += NumClusters;
9874     }
9875   }
9876   Clusters.resize(DstIndex);
9877 }
9878 
9879 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9880                                         MachineBasicBlock *SwitchMBB,
9881                                         MachineBasicBlock *DefaultMBB) {
9882   MachineFunction *CurMF = FuncInfo.MF;
9883   MachineBasicBlock *NextMBB = nullptr;
9884   MachineFunction::iterator BBI(W.MBB);
9885   if (++BBI != FuncInfo.MF->end())
9886     NextMBB = &*BBI;
9887 
9888   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9889 
9890   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9891 
9892   if (Size == 2 && W.MBB == SwitchMBB) {
9893     // If any two of the cases has the same destination, and if one value
9894     // is the same as the other, but has one bit unset that the other has set,
9895     // use bit manipulation to do two compares at once.  For example:
9896     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9897     // TODO: This could be extended to merge any 2 cases in switches with 3
9898     // cases.
9899     // TODO: Handle cases where W.CaseBB != SwitchBB.
9900     CaseCluster &Small = *W.FirstCluster;
9901     CaseCluster &Big = *W.LastCluster;
9902 
9903     if (Small.Low == Small.High && Big.Low == Big.High &&
9904         Small.MBB == Big.MBB) {
9905       const APInt &SmallValue = Small.Low->getValue();
9906       const APInt &BigValue = Big.Low->getValue();
9907 
9908       // Check that there is only one bit different.
9909       APInt CommonBit = BigValue ^ SmallValue;
9910       if (CommonBit.isPowerOf2()) {
9911         SDValue CondLHS = getValue(Cond);
9912         EVT VT = CondLHS.getValueType();
9913         SDLoc DL = getCurSDLoc();
9914 
9915         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9916                                  DAG.getConstant(CommonBit, DL, VT));
9917         SDValue Cond = DAG.getSetCC(
9918             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9919             ISD::SETEQ);
9920 
9921         // Update successor info.
9922         // Both Small and Big will jump to Small.BB, so we sum up the
9923         // probabilities.
9924         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9925         if (BPI)
9926           addSuccessorWithProb(
9927               SwitchMBB, DefaultMBB,
9928               // The default destination is the first successor in IR.
9929               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9930         else
9931           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9932 
9933         // Insert the true branch.
9934         SDValue BrCond =
9935             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9936                         DAG.getBasicBlock(Small.MBB));
9937         // Insert the false branch.
9938         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9939                              DAG.getBasicBlock(DefaultMBB));
9940 
9941         DAG.setRoot(BrCond);
9942         return;
9943       }
9944     }
9945   }
9946 
9947   if (TM.getOptLevel() != CodeGenOpt::None) {
9948     // Here, we order cases by probability so the most likely case will be
9949     // checked first. However, two clusters can have the same probability in
9950     // which case their relative ordering is non-deterministic. So we use Low
9951     // as a tie-breaker as clusters are guaranteed to never overlap.
9952     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9953                [](const CaseCluster &a, const CaseCluster &b) {
9954       return a.Prob != b.Prob ?
9955              a.Prob > b.Prob :
9956              a.Low->getValue().slt(b.Low->getValue());
9957     });
9958 
9959     // Rearrange the case blocks so that the last one falls through if possible
9960     // without changing the order of probabilities.
9961     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9962       --I;
9963       if (I->Prob > W.LastCluster->Prob)
9964         break;
9965       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9966         std::swap(*I, *W.LastCluster);
9967         break;
9968       }
9969     }
9970   }
9971 
9972   // Compute total probability.
9973   BranchProbability DefaultProb = W.DefaultProb;
9974   BranchProbability UnhandledProbs = DefaultProb;
9975   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9976     UnhandledProbs += I->Prob;
9977 
9978   MachineBasicBlock *CurMBB = W.MBB;
9979   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9980     MachineBasicBlock *Fallthrough;
9981     if (I == W.LastCluster) {
9982       // For the last cluster, fall through to the default destination.
9983       Fallthrough = DefaultMBB;
9984     } else {
9985       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9986       CurMF->insert(BBI, Fallthrough);
9987       // Put Cond in a virtual register to make it available from the new blocks.
9988       ExportFromCurrentBlock(Cond);
9989     }
9990     UnhandledProbs -= I->Prob;
9991 
9992     switch (I->Kind) {
9993       case CC_JumpTable: {
9994         // FIXME: Optimize away range check based on pivot comparisons.
9995         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9996         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9997 
9998         // The jump block hasn't been inserted yet; insert it here.
9999         MachineBasicBlock *JumpMBB = JT->MBB;
10000         CurMF->insert(BBI, JumpMBB);
10001 
10002         auto JumpProb = I->Prob;
10003         auto FallthroughProb = UnhandledProbs;
10004 
10005         // If the default statement is a target of the jump table, we evenly
10006         // distribute the default probability to successors of CurMBB. Also
10007         // update the probability on the edge from JumpMBB to Fallthrough.
10008         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10009                                               SE = JumpMBB->succ_end();
10010              SI != SE; ++SI) {
10011           if (*SI == DefaultMBB) {
10012             JumpProb += DefaultProb / 2;
10013             FallthroughProb -= DefaultProb / 2;
10014             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10015             JumpMBB->normalizeSuccProbs();
10016             break;
10017           }
10018         }
10019 
10020         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10021         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10022         CurMBB->normalizeSuccProbs();
10023 
10024         // The jump table header will be inserted in our current block, do the
10025         // range check, and fall through to our fallthrough block.
10026         JTH->HeaderBB = CurMBB;
10027         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10028 
10029         // If we're in the right place, emit the jump table header right now.
10030         if (CurMBB == SwitchMBB) {
10031           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10032           JTH->Emitted = true;
10033         }
10034         break;
10035       }
10036       case CC_BitTests: {
10037         // FIXME: Optimize away range check based on pivot comparisons.
10038         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10039 
10040         // The bit test blocks haven't been inserted yet; insert them here.
10041         for (BitTestCase &BTC : BTB->Cases)
10042           CurMF->insert(BBI, BTC.ThisBB);
10043 
10044         // Fill in fields of the BitTestBlock.
10045         BTB->Parent = CurMBB;
10046         BTB->Default = Fallthrough;
10047 
10048         BTB->DefaultProb = UnhandledProbs;
10049         // If the cases in bit test don't form a contiguous range, we evenly
10050         // distribute the probability on the edge to Fallthrough to two
10051         // successors of CurMBB.
10052         if (!BTB->ContiguousRange) {
10053           BTB->Prob += DefaultProb / 2;
10054           BTB->DefaultProb -= DefaultProb / 2;
10055         }
10056 
10057         // If we're in the right place, emit the bit test header right now.
10058         if (CurMBB == SwitchMBB) {
10059           visitBitTestHeader(*BTB, SwitchMBB);
10060           BTB->Emitted = true;
10061         }
10062         break;
10063       }
10064       case CC_Range: {
10065         const Value *RHS, *LHS, *MHS;
10066         ISD::CondCode CC;
10067         if (I->Low == I->High) {
10068           // Check Cond == I->Low.
10069           CC = ISD::SETEQ;
10070           LHS = Cond;
10071           RHS=I->Low;
10072           MHS = nullptr;
10073         } else {
10074           // Check I->Low <= Cond <= I->High.
10075           CC = ISD::SETLE;
10076           LHS = I->Low;
10077           MHS = Cond;
10078           RHS = I->High;
10079         }
10080 
10081         // The false probability is the sum of all unhandled cases.
10082         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10083                      getCurSDLoc(), I->Prob, UnhandledProbs);
10084 
10085         if (CurMBB == SwitchMBB)
10086           visitSwitchCase(CB, SwitchMBB);
10087         else
10088           SwitchCases.push_back(CB);
10089 
10090         break;
10091       }
10092     }
10093     CurMBB = Fallthrough;
10094   }
10095 }
10096 
10097 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10098                                               CaseClusterIt First,
10099                                               CaseClusterIt Last) {
10100   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10101     if (X.Prob != CC.Prob)
10102       return X.Prob > CC.Prob;
10103 
10104     // Ties are broken by comparing the case value.
10105     return X.Low->getValue().slt(CC.Low->getValue());
10106   });
10107 }
10108 
10109 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10110                                         const SwitchWorkListItem &W,
10111                                         Value *Cond,
10112                                         MachineBasicBlock *SwitchMBB) {
10113   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10114          "Clusters not sorted?");
10115 
10116   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10117 
10118   // Balance the tree based on branch probabilities to create a near-optimal (in
10119   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10120   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10121   CaseClusterIt LastLeft = W.FirstCluster;
10122   CaseClusterIt FirstRight = W.LastCluster;
10123   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10124   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10125 
10126   // Move LastLeft and FirstRight towards each other from opposite directions to
10127   // find a partitioning of the clusters which balances the probability on both
10128   // sides. If LeftProb and RightProb are equal, alternate which side is
10129   // taken to ensure 0-probability nodes are distributed evenly.
10130   unsigned I = 0;
10131   while (LastLeft + 1 < FirstRight) {
10132     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10133       LeftProb += (++LastLeft)->Prob;
10134     else
10135       RightProb += (--FirstRight)->Prob;
10136     I++;
10137   }
10138 
10139   while (true) {
10140     // Our binary search tree differs from a typical BST in that ours can have up
10141     // to three values in each leaf. The pivot selection above doesn't take that
10142     // into account, which means the tree might require more nodes and be less
10143     // efficient. We compensate for this here.
10144 
10145     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10146     unsigned NumRight = W.LastCluster - FirstRight + 1;
10147 
10148     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10149       // If one side has less than 3 clusters, and the other has more than 3,
10150       // consider taking a cluster from the other side.
10151 
10152       if (NumLeft < NumRight) {
10153         // Consider moving the first cluster on the right to the left side.
10154         CaseCluster &CC = *FirstRight;
10155         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10156         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10157         if (LeftSideRank <= RightSideRank) {
10158           // Moving the cluster to the left does not demote it.
10159           ++LastLeft;
10160           ++FirstRight;
10161           continue;
10162         }
10163       } else {
10164         assert(NumRight < NumLeft);
10165         // Consider moving the last element on the left to the right side.
10166         CaseCluster &CC = *LastLeft;
10167         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10168         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10169         if (RightSideRank <= LeftSideRank) {
10170           // Moving the cluster to the right does not demot it.
10171           --LastLeft;
10172           --FirstRight;
10173           continue;
10174         }
10175       }
10176     }
10177     break;
10178   }
10179 
10180   assert(LastLeft + 1 == FirstRight);
10181   assert(LastLeft >= W.FirstCluster);
10182   assert(FirstRight <= W.LastCluster);
10183 
10184   // Use the first element on the right as pivot since we will make less-than
10185   // comparisons against it.
10186   CaseClusterIt PivotCluster = FirstRight;
10187   assert(PivotCluster > W.FirstCluster);
10188   assert(PivotCluster <= W.LastCluster);
10189 
10190   CaseClusterIt FirstLeft = W.FirstCluster;
10191   CaseClusterIt LastRight = W.LastCluster;
10192 
10193   const ConstantInt *Pivot = PivotCluster->Low;
10194 
10195   // New blocks will be inserted immediately after the current one.
10196   MachineFunction::iterator BBI(W.MBB);
10197   ++BBI;
10198 
10199   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10200   // we can branch to its destination directly if it's squeezed exactly in
10201   // between the known lower bound and Pivot - 1.
10202   MachineBasicBlock *LeftMBB;
10203   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10204       FirstLeft->Low == W.GE &&
10205       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10206     LeftMBB = FirstLeft->MBB;
10207   } else {
10208     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10209     FuncInfo.MF->insert(BBI, LeftMBB);
10210     WorkList.push_back(
10211         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10212     // Put Cond in a virtual register to make it available from the new blocks.
10213     ExportFromCurrentBlock(Cond);
10214   }
10215 
10216   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10217   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10218   // directly if RHS.High equals the current upper bound.
10219   MachineBasicBlock *RightMBB;
10220   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10221       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10222     RightMBB = FirstRight->MBB;
10223   } else {
10224     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10225     FuncInfo.MF->insert(BBI, RightMBB);
10226     WorkList.push_back(
10227         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10228     // Put Cond in a virtual register to make it available from the new blocks.
10229     ExportFromCurrentBlock(Cond);
10230   }
10231 
10232   // Create the CaseBlock record that will be used to lower the branch.
10233   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10234                getCurSDLoc(), LeftProb, RightProb);
10235 
10236   if (W.MBB == SwitchMBB)
10237     visitSwitchCase(CB, SwitchMBB);
10238   else
10239     SwitchCases.push_back(CB);
10240 }
10241 
10242 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10243 // from the swith statement.
10244 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10245                                             BranchProbability PeeledCaseProb) {
10246   if (PeeledCaseProb == BranchProbability::getOne())
10247     return BranchProbability::getZero();
10248   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10249 
10250   uint32_t Numerator = CaseProb.getNumerator();
10251   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10252   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10253 }
10254 
10255 // Try to peel the top probability case if it exceeds the threshold.
10256 // Return current MachineBasicBlock for the switch statement if the peeling
10257 // does not occur.
10258 // If the peeling is performed, return the newly created MachineBasicBlock
10259 // for the peeled switch statement. Also update Clusters to remove the peeled
10260 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10261 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10262     const SwitchInst &SI, CaseClusterVector &Clusters,
10263     BranchProbability &PeeledCaseProb) {
10264   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10265   // Don't perform if there is only one cluster or optimizing for size.
10266   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10267       TM.getOptLevel() == CodeGenOpt::None ||
10268       SwitchMBB->getParent()->getFunction().optForMinSize())
10269     return SwitchMBB;
10270 
10271   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10272   unsigned PeeledCaseIndex = 0;
10273   bool SwitchPeeled = false;
10274   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10275     CaseCluster &CC = Clusters[Index];
10276     if (CC.Prob < TopCaseProb)
10277       continue;
10278     TopCaseProb = CC.Prob;
10279     PeeledCaseIndex = Index;
10280     SwitchPeeled = true;
10281   }
10282   if (!SwitchPeeled)
10283     return SwitchMBB;
10284 
10285   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10286                     << TopCaseProb << "\n");
10287 
10288   // Record the MBB for the peeled switch statement.
10289   MachineFunction::iterator BBI(SwitchMBB);
10290   ++BBI;
10291   MachineBasicBlock *PeeledSwitchMBB =
10292       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10293   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10294 
10295   ExportFromCurrentBlock(SI.getCondition());
10296   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10297   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10298                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10299   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10300 
10301   Clusters.erase(PeeledCaseIt);
10302   for (CaseCluster &CC : Clusters) {
10303     LLVM_DEBUG(
10304         dbgs() << "Scale the probablity for one cluster, before scaling: "
10305                << CC.Prob << "\n");
10306     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10307     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10308   }
10309   PeeledCaseProb = TopCaseProb;
10310   return PeeledSwitchMBB;
10311 }
10312 
10313 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10314   // Extract cases from the switch.
10315   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10316   CaseClusterVector Clusters;
10317   Clusters.reserve(SI.getNumCases());
10318   for (auto I : SI.cases()) {
10319     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10320     const ConstantInt *CaseVal = I.getCaseValue();
10321     BranchProbability Prob =
10322         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10323             : BranchProbability(1, SI.getNumCases() + 1);
10324     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10325   }
10326 
10327   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10328 
10329   // Cluster adjacent cases with the same destination. We do this at all
10330   // optimization levels because it's cheap to do and will make codegen faster
10331   // if there are many clusters.
10332   sortAndRangeify(Clusters);
10333 
10334   if (TM.getOptLevel() != CodeGenOpt::None) {
10335     // Replace an unreachable default with the most popular destination.
10336     // FIXME: Exploit unreachable default more aggressively.
10337     bool UnreachableDefault =
10338         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10339     if (UnreachableDefault && !Clusters.empty()) {
10340       DenseMap<const BasicBlock *, unsigned> Popularity;
10341       unsigned MaxPop = 0;
10342       const BasicBlock *MaxBB = nullptr;
10343       for (auto I : SI.cases()) {
10344         const BasicBlock *BB = I.getCaseSuccessor();
10345         if (++Popularity[BB] > MaxPop) {
10346           MaxPop = Popularity[BB];
10347           MaxBB = BB;
10348         }
10349       }
10350       // Set new default.
10351       assert(MaxPop > 0 && MaxBB);
10352       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10353 
10354       // Remove cases that were pointing to the destination that is now the
10355       // default.
10356       CaseClusterVector New;
10357       New.reserve(Clusters.size());
10358       for (CaseCluster &CC : Clusters) {
10359         if (CC.MBB != DefaultMBB)
10360           New.push_back(CC);
10361       }
10362       Clusters = std::move(New);
10363     }
10364   }
10365 
10366   // The branch probablity of the peeled case.
10367   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10368   MachineBasicBlock *PeeledSwitchMBB =
10369       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10370 
10371   // If there is only the default destination, jump there directly.
10372   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10373   if (Clusters.empty()) {
10374     assert(PeeledSwitchMBB == SwitchMBB);
10375     SwitchMBB->addSuccessor(DefaultMBB);
10376     if (DefaultMBB != NextBlock(SwitchMBB)) {
10377       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10378                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10379     }
10380     return;
10381   }
10382 
10383   findJumpTables(Clusters, &SI, DefaultMBB);
10384   findBitTestClusters(Clusters, &SI);
10385 
10386   LLVM_DEBUG({
10387     dbgs() << "Case clusters: ";
10388     for (const CaseCluster &C : Clusters) {
10389       if (C.Kind == CC_JumpTable)
10390         dbgs() << "JT:";
10391       if (C.Kind == CC_BitTests)
10392         dbgs() << "BT:";
10393 
10394       C.Low->getValue().print(dbgs(), true);
10395       if (C.Low != C.High) {
10396         dbgs() << '-';
10397         C.High->getValue().print(dbgs(), true);
10398       }
10399       dbgs() << ' ';
10400     }
10401     dbgs() << '\n';
10402   });
10403 
10404   assert(!Clusters.empty());
10405   SwitchWorkList WorkList;
10406   CaseClusterIt First = Clusters.begin();
10407   CaseClusterIt Last = Clusters.end() - 1;
10408   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10409   // Scale the branchprobability for DefaultMBB if the peel occurs and
10410   // DefaultMBB is not replaced.
10411   if (PeeledCaseProb != BranchProbability::getZero() &&
10412       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10413     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10414   WorkList.push_back(
10415       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10416 
10417   while (!WorkList.empty()) {
10418     SwitchWorkListItem W = WorkList.back();
10419     WorkList.pop_back();
10420     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10421 
10422     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10423         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10424       // For optimized builds, lower large range as a balanced binary tree.
10425       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10426       continue;
10427     }
10428 
10429     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10430   }
10431 }
10432