xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision a255931c40558edf87994c2a8ed9b274c3fbda30)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.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/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallingConv.h"
73 #include "llvm/IR/Constant.h"
74 #include "llvm/IR/ConstantRange.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DataLayout.h"
77 #include "llvm/IR/DebugInfoMetadata.h"
78 #include "llvm/IR/DebugLoc.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/GetElementPtrTypeIterator.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/InstrTypes.h"
84 #include "llvm/IR/Instruction.h"
85 #include "llvm/IR/Instructions.h"
86 #include "llvm/IR/IntrinsicInst.h"
87 #include "llvm/IR/Intrinsics.h"
88 #include "llvm/IR/IntrinsicsAArch64.h"
89 #include "llvm/IR/IntrinsicsWebAssembly.h"
90 #include "llvm/IR/LLVMContext.h"
91 #include "llvm/IR/Metadata.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/Operator.h"
94 #include "llvm/IR/PatternMatch.h"
95 #include "llvm/IR/Statepoint.h"
96 #include "llvm/IR/Type.h"
97 #include "llvm/IR/User.h"
98 #include "llvm/IR/Value.h"
99 #include "llvm/MC/MCContext.h"
100 #include "llvm/MC/MCSymbol.h"
101 #include "llvm/Support/AtomicOrdering.h"
102 #include "llvm/Support/BranchProbability.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CodeGen.h"
105 #include "llvm/Support/CommandLine.h"
106 #include "llvm/Support/Compiler.h"
107 #include "llvm/Support/Debug.h"
108 #include "llvm/Support/ErrorHandling.h"
109 #include "llvm/Support/MachineValueType.h"
110 #include "llvm/Support/MathExtras.h"
111 #include "llvm/Support/raw_ostream.h"
112 #include "llvm/Target/TargetIntrinsicInfo.h"
113 #include "llvm/Target/TargetMachine.h"
114 #include "llvm/Target/TargetOptions.h"
115 #include "llvm/Transforms/Utils/Local.h"
116 #include <algorithm>
117 #include <cassert>
118 #include <cstddef>
119 #include <cstdint>
120 #include <cstring>
121 #include <iterator>
122 #include <limits>
123 #include <numeric>
124 #include <tuple>
125 #include <utility>
126 #include <vector>
127 
128 using namespace llvm;
129 using namespace PatternMatch;
130 using namespace SwitchCG;
131 
132 #define DEBUG_TYPE "isel"
133 
134 /// LimitFloatPrecision - Generate low-precision inline sequences for
135 /// some float libcalls (6, 8 or 12 bits).
136 static unsigned LimitFloatPrecision;
137 
138 static cl::opt<unsigned, true>
139     LimitFPPrecision("limit-float-precision",
140                      cl::desc("Generate low-precision inline sequences "
141                               "for some float libcalls"),
142                      cl::location(LimitFloatPrecision), cl::Hidden,
143                      cl::init(0));
144 
145 static cl::opt<unsigned> SwitchPeelThreshold(
146     "switch-peel-threshold", cl::Hidden, cl::init(66),
147     cl::desc("Set the case probability threshold for peeling the case from a "
148              "switch statement. A value greater than 100 will void this "
149              "optimization"));
150 
151 // Limit the width of DAG chains. This is important in general to prevent
152 // DAG-based analysis from blowing up. For example, alias analysis and
153 // load clustering may not complete in reasonable time. It is difficult to
154 // recognize and avoid this situation within each individual analysis, and
155 // future analyses are likely to have the same behavior. Limiting DAG width is
156 // the safe approach and will be especially important with global DAGs.
157 //
158 // MaxParallelChains default is arbitrarily high to avoid affecting
159 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
160 // sequence over this should have been converted to llvm.memcpy by the
161 // frontend. It is easy to induce this behavior with .ll code such as:
162 // %buffer = alloca [4096 x i8]
163 // %data = load [4096 x i8]* %argPtr
164 // store [4096 x i8] %data, [4096 x i8]* %buffer
165 static const unsigned MaxParallelChains = 64;
166 
167 // Return the calling convention if the Value passed requires ABI mangling as it
168 // is a parameter to a function or a return value from a function which is not
169 // an intrinsic.
170 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
171   if (auto *R = dyn_cast<ReturnInst>(V))
172     return R->getParent()->getParent()->getCallingConv();
173 
174   if (auto *CI = dyn_cast<CallInst>(V)) {
175     const bool IsInlineAsm = CI->isInlineAsm();
176     const bool IsIndirectFunctionCall =
177         !IsInlineAsm && !CI->getCalledFunction();
178 
179     // It is possible that the call instruction is an inline asm statement or an
180     // indirect function call in which case the return value of
181     // getCalledFunction() would be nullptr.
182     const bool IsInstrinsicCall =
183         !IsInlineAsm && !IsIndirectFunctionCall &&
184         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
185 
186     if (!IsInlineAsm && !IsInstrinsicCall)
187       return CI->getCallingConv();
188   }
189 
190   return None;
191 }
192 
193 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
194                                       const SDValue *Parts, unsigned NumParts,
195                                       MVT PartVT, EVT ValueVT, const Value *V,
196                                       Optional<CallingConv::ID> CC);
197 
198 /// getCopyFromParts - Create a value that contains the specified legal parts
199 /// combined into the value they represent.  If the parts combine to a type
200 /// larger than ValueVT then AssertOp can be used to specify whether the extra
201 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
202 /// (ISD::AssertSext).
203 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
204                                 const SDValue *Parts, unsigned NumParts,
205                                 MVT PartVT, EVT ValueVT, const Value *V,
206                                 Optional<CallingConv::ID> CC = None,
207                                 Optional<ISD::NodeType> AssertOp = None) {
208   // Let the target assemble the parts if it wants to
209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
210   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
211                                                    PartVT, ValueVT, CC))
212     return Val;
213 
214   if (ValueVT.isVector())
215     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
216                                   CC);
217 
218   assert(NumParts > 0 && "No parts to assemble!");
219   SDValue Val = Parts[0];
220 
221   if (NumParts > 1) {
222     // Assemble the value from multiple parts.
223     if (ValueVT.isInteger()) {
224       unsigned PartBits = PartVT.getSizeInBits();
225       unsigned ValueBits = ValueVT.getSizeInBits();
226 
227       // Assemble the power of 2 part.
228       unsigned RoundParts =
229           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
230       unsigned RoundBits = PartBits * RoundParts;
231       EVT RoundVT = RoundBits == ValueBits ?
232         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
233       SDValue Lo, Hi;
234 
235       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
236 
237       if (RoundParts > 2) {
238         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
239                               PartVT, HalfVT, V);
240         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
241                               RoundParts / 2, PartVT, HalfVT, V);
242       } else {
243         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
244         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
245       }
246 
247       if (DAG.getDataLayout().isBigEndian())
248         std::swap(Lo, Hi);
249 
250       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
251 
252       if (RoundParts < NumParts) {
253         // Assemble the trailing non-power-of-2 part.
254         unsigned OddParts = NumParts - RoundParts;
255         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
256         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
257                               OddVT, V, CC);
258 
259         // Combine the round and odd parts.
260         Lo = Val;
261         if (DAG.getDataLayout().isBigEndian())
262           std::swap(Lo, Hi);
263         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
264         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
265         Hi =
266             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
267                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
268                                         TLI.getPointerTy(DAG.getDataLayout())));
269         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
270         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
271       }
272     } else if (PartVT.isFloatingPoint()) {
273       // FP split into multiple FP parts (for ppcf128)
274       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
275              "Unexpected split");
276       SDValue Lo, Hi;
277       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
278       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
279       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
280         std::swap(Lo, Hi);
281       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
282     } else {
283       // FP split into integer parts (soft fp)
284       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
285              !PartVT.isVector() && "Unexpected split");
286       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
287       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
288     }
289   }
290 
291   // There is now one part, held in Val.  Correct it to match ValueVT.
292   // PartEVT is the type of the register class that holds the value.
293   // ValueVT is the type of the inline asm operation.
294   EVT PartEVT = Val.getValueType();
295 
296   if (PartEVT == ValueVT)
297     return Val;
298 
299   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
300       ValueVT.bitsLT(PartEVT)) {
301     // For an FP value in an integer part, we need to truncate to the right
302     // width first.
303     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
304     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
305   }
306 
307   // Handle types that have the same size.
308   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
309     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
310 
311   // Handle types with different sizes.
312   if (PartEVT.isInteger() && ValueVT.isInteger()) {
313     if (ValueVT.bitsLT(PartEVT)) {
314       // For a truncate, see if we have any information to
315       // indicate whether the truncated bits will always be
316       // zero or sign-extension.
317       if (AssertOp.hasValue())
318         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
319                           DAG.getValueType(ValueVT));
320       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
321     }
322     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
323   }
324 
325   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
326     // FP_ROUND's are always exact here.
327     if (ValueVT.bitsLT(Val.getValueType()))
328       return DAG.getNode(
329           ISD::FP_ROUND, DL, ValueVT, Val,
330           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
331 
332     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
333   }
334 
335   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
336   // then truncating.
337   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
338       ValueVT.bitsLT(PartEVT)) {
339     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
340     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
341   }
342 
343   report_fatal_error("Unknown mismatch in getCopyFromParts!");
344 }
345 
346 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
347                                               const Twine &ErrMsg) {
348   const Instruction *I = dyn_cast_or_null<Instruction>(V);
349   if (!V)
350     return Ctx.emitError(ErrMsg);
351 
352   const char *AsmError = ", possible invalid constraint for vector type";
353   if (const CallInst *CI = dyn_cast<CallInst>(I))
354     if (CI->isInlineAsm())
355       return Ctx.emitError(I, ErrMsg + AsmError);
356 
357   return Ctx.emitError(I, ErrMsg);
358 }
359 
360 /// getCopyFromPartsVector - Create a value that contains the specified legal
361 /// parts combined into the value they represent.  If the parts combine to a
362 /// type larger than ValueVT then AssertOp can be used to specify whether the
363 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
364 /// ValueVT (ISD::AssertSext).
365 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
366                                       const SDValue *Parts, unsigned NumParts,
367                                       MVT PartVT, EVT ValueVT, const Value *V,
368                                       Optional<CallingConv::ID> CallConv) {
369   assert(ValueVT.isVector() && "Not a vector value");
370   assert(NumParts > 0 && "No parts to assemble!");
371   const bool IsABIRegCopy = CallConv.hasValue();
372 
373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
374   SDValue Val = Parts[0];
375 
376   // Handle a multi-element vector.
377   if (NumParts > 1) {
378     EVT IntermediateVT;
379     MVT RegisterVT;
380     unsigned NumIntermediates;
381     unsigned NumRegs;
382 
383     if (IsABIRegCopy) {
384       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
385           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
386           NumIntermediates, RegisterVT);
387     } else {
388       NumRegs =
389           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
390                                      NumIntermediates, RegisterVT);
391     }
392 
393     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
394     NumParts = NumRegs; // Silence a compiler warning.
395     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
396     assert(RegisterVT.getSizeInBits() ==
397            Parts[0].getSimpleValueType().getSizeInBits() &&
398            "Part type sizes don't match!");
399 
400     // Assemble the parts into intermediate operands.
401     SmallVector<SDValue, 8> Ops(NumIntermediates);
402     if (NumIntermediates == NumParts) {
403       // If the register was not expanded, truncate or copy the value,
404       // as appropriate.
405       for (unsigned i = 0; i != NumParts; ++i)
406         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
407                                   PartVT, IntermediateVT, V);
408     } else if (NumParts > 0) {
409       // If the intermediate type was expanded, build the intermediate
410       // operands from the parts.
411       assert(NumParts % NumIntermediates == 0 &&
412              "Must expand into a divisible number of parts!");
413       unsigned Factor = NumParts / NumIntermediates;
414       for (unsigned i = 0; i != NumIntermediates; ++i)
415         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
416                                   PartVT, IntermediateVT, V);
417     }
418 
419     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
420     // intermediate operands.
421     EVT BuiltVectorTy =
422         IntermediateVT.isVector()
423             ? EVT::getVectorVT(
424                   *DAG.getContext(), IntermediateVT.getScalarType(),
425                   IntermediateVT.getVectorElementCount() * NumParts)
426             : EVT::getVectorVT(*DAG.getContext(),
427                                IntermediateVT.getScalarType(),
428                                NumIntermediates);
429     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
430                                                 : ISD::BUILD_VECTOR,
431                       DL, BuiltVectorTy, Ops);
432   }
433 
434   // There is now one part, held in Val.  Correct it to match ValueVT.
435   EVT PartEVT = Val.getValueType();
436 
437   if (PartEVT == ValueVT)
438     return Val;
439 
440   if (PartEVT.isVector()) {
441     // If the element type of the source/dest vectors are the same, but the
442     // parts vector has more elements than the value vector, then we have a
443     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
444     // elements we want.
445     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
446       assert((PartEVT.getVectorElementCount().Min >
447               ValueVT.getVectorElementCount().Min) &&
448              (PartEVT.getVectorElementCount().Scalable ==
449               ValueVT.getVectorElementCount().Scalable) &&
450              "Cannot narrow, it would be a lossy transformation");
451       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
452                          DAG.getVectorIdxConstant(0, DL));
453     }
454 
455     // Vector/Vector bitcast.
456     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
457       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
458 
459     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
460       "Cannot handle this kind of promotion");
461     // Promoted vector extract
462     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
463 
464   }
465 
466   // Trivial bitcast if the types are the same size and the destination
467   // vector type is legal.
468   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
469       TLI.isTypeLegal(ValueVT))
470     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
471 
472   if (ValueVT.getVectorNumElements() != 1) {
473      // Certain ABIs require that vectors are passed as integers. For vectors
474      // are the same size, this is an obvious bitcast.
475      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
476        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
477      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
478        // Bitcast Val back the original type and extract the corresponding
479        // vector we want.
480        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
481        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
482                                            ValueVT.getVectorElementType(), Elts);
483        Val = DAG.getBitcast(WiderVecType, Val);
484        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
485                           DAG.getVectorIdxConstant(0, DL));
486      }
487 
488      diagnosePossiblyInvalidConstraint(
489          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
490      return DAG.getUNDEF(ValueVT);
491   }
492 
493   // Handle cases such as i8 -> <1 x i1>
494   EVT ValueSVT = ValueVT.getVectorElementType();
495   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
496     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
497       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
498     else
499       Val = ValueVT.isFloatingPoint()
500                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
501                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
502   }
503 
504   return DAG.getBuildVector(ValueVT, DL, Val);
505 }
506 
507 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
508                                  SDValue Val, SDValue *Parts, unsigned NumParts,
509                                  MVT PartVT, const Value *V,
510                                  Optional<CallingConv::ID> CallConv);
511 
512 /// getCopyToParts - Create a series of nodes that contain the specified value
513 /// split into legal parts.  If the parts contain more bits than Val, then, for
514 /// integers, ExtendKind can be used to specify how to generate the extra bits.
515 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
516                            SDValue *Parts, unsigned NumParts, MVT PartVT,
517                            const Value *V,
518                            Optional<CallingConv::ID> CallConv = None,
519                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
520   // Let the target split the parts if it wants to
521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
522   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
523                                       CallConv))
524     return;
525   EVT ValueVT = Val.getValueType();
526 
527   // Handle the vector case separately.
528   if (ValueVT.isVector())
529     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
530                                 CallConv);
531 
532   unsigned PartBits = PartVT.getSizeInBits();
533   unsigned OrigNumParts = NumParts;
534   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
535          "Copying to an illegal type!");
536 
537   if (NumParts == 0)
538     return;
539 
540   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
541   EVT PartEVT = PartVT;
542   if (PartEVT == ValueVT) {
543     assert(NumParts == 1 && "No-op copy with multiple parts!");
544     Parts[0] = Val;
545     return;
546   }
547 
548   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
549     // If the parts cover more bits than the value has, promote the value.
550     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
551       assert(NumParts == 1 && "Do not know what to promote to!");
552       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
553     } else {
554       if (ValueVT.isFloatingPoint()) {
555         // FP values need to be bitcast, then extended if they are being put
556         // into a larger container.
557         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
558         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
559       }
560       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
561              ValueVT.isInteger() &&
562              "Unknown mismatch!");
563       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
564       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
565       if (PartVT == MVT::x86mmx)
566         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
567     }
568   } else if (PartBits == ValueVT.getSizeInBits()) {
569     // Different types of the same size.
570     assert(NumParts == 1 && PartEVT != ValueVT);
571     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
573     // If the parts cover less bits than value has, truncate the value.
574     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
575            ValueVT.isInteger() &&
576            "Unknown mismatch!");
577     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
578     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
579     if (PartVT == MVT::x86mmx)
580       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
581   }
582 
583   // The value may have changed - recompute ValueVT.
584   ValueVT = Val.getValueType();
585   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
586          "Failed to tile the value with PartVT!");
587 
588   if (NumParts == 1) {
589     if (PartEVT != ValueVT) {
590       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
591                                         "scalar-to-vector conversion failed");
592       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
593     }
594 
595     Parts[0] = Val;
596     return;
597   }
598 
599   // Expand the value into multiple parts.
600   if (NumParts & (NumParts - 1)) {
601     // The number of parts is not a power of 2.  Split off and copy the tail.
602     assert(PartVT.isInteger() && ValueVT.isInteger() &&
603            "Do not know what to expand to!");
604     unsigned RoundParts = 1 << Log2_32(NumParts);
605     unsigned RoundBits = RoundParts * PartBits;
606     unsigned OddParts = NumParts - RoundParts;
607     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
608       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
609 
610     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
611                    CallConv);
612 
613     if (DAG.getDataLayout().isBigEndian())
614       // The odd parts were reversed by getCopyToParts - unreverse them.
615       std::reverse(Parts + RoundParts, Parts + NumParts);
616 
617     NumParts = RoundParts;
618     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
619     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
620   }
621 
622   // The number of parts is a power of 2.  Repeatedly bisect the value using
623   // EXTRACT_ELEMENT.
624   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
625                          EVT::getIntegerVT(*DAG.getContext(),
626                                            ValueVT.getSizeInBits()),
627                          Val);
628 
629   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
630     for (unsigned i = 0; i < NumParts; i += StepSize) {
631       unsigned ThisBits = StepSize * PartBits / 2;
632       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
633       SDValue &Part0 = Parts[i];
634       SDValue &Part1 = Parts[i+StepSize/2];
635 
636       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
637                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
638       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
639                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
640 
641       if (ThisBits == PartBits && ThisVT != PartVT) {
642         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
643         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
644       }
645     }
646   }
647 
648   if (DAG.getDataLayout().isBigEndian())
649     std::reverse(Parts, Parts + OrigNumParts);
650 }
651 
652 static SDValue widenVectorToPartType(SelectionDAG &DAG,
653                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
654   if (!PartVT.isVector())
655     return SDValue();
656 
657   EVT ValueVT = Val.getValueType();
658   unsigned PartNumElts = PartVT.getVectorNumElements();
659   unsigned ValueNumElts = ValueVT.getVectorNumElements();
660   if (PartNumElts > ValueNumElts &&
661       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
662     EVT ElementVT = PartVT.getVectorElementType();
663     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
664     // undef elements.
665     SmallVector<SDValue, 16> Ops;
666     DAG.ExtractVectorElements(Val, Ops);
667     SDValue EltUndef = DAG.getUNDEF(ElementVT);
668     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
669       Ops.push_back(EltUndef);
670 
671     // FIXME: Use CONCAT for 2x -> 4x.
672     return DAG.getBuildVector(PartVT, DL, Ops);
673   }
674 
675   return SDValue();
676 }
677 
678 /// getCopyToPartsVector - Create a series of nodes that contain the specified
679 /// value split into legal parts.
680 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
681                                  SDValue Val, SDValue *Parts, unsigned NumParts,
682                                  MVT PartVT, const Value *V,
683                                  Optional<CallingConv::ID> CallConv) {
684   EVT ValueVT = Val.getValueType();
685   assert(ValueVT.isVector() && "Not a vector");
686   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
687   const bool IsABIRegCopy = CallConv.hasValue();
688 
689   if (NumParts == 1) {
690     EVT PartEVT = PartVT;
691     if (PartEVT == ValueVT) {
692       // Nothing to do.
693     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
694       // Bitconvert vector->vector case.
695       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
696     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
697       Val = Widened;
698     } else if (PartVT.isVector() &&
699                PartEVT.getVectorElementType().bitsGE(
700                  ValueVT.getVectorElementType()) &&
701                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
702 
703       // Promoted vector extract
704       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
705     } else {
706       if (ValueVT.getVectorNumElements() == 1) {
707         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
708                           DAG.getVectorIdxConstant(0, DL));
709       } else {
710         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
711                "lossy conversion of vector to scalar type");
712         EVT IntermediateType =
713             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
714         Val = DAG.getBitcast(IntermediateType, Val);
715         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
716       }
717     }
718 
719     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
720     Parts[0] = Val;
721     return;
722   }
723 
724   // Handle a multi-element vector.
725   EVT IntermediateVT;
726   MVT RegisterVT;
727   unsigned NumIntermediates;
728   unsigned NumRegs;
729   if (IsABIRegCopy) {
730     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
731         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
732         NumIntermediates, RegisterVT);
733   } else {
734     NumRegs =
735         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
736                                    NumIntermediates, RegisterVT);
737   }
738 
739   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
740   NumParts = NumRegs; // Silence a compiler warning.
741   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
742 
743   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
744     IntermediateVT.getVectorNumElements() : 1;
745 
746   // Convert the vector to the appropriate type if necessary.
747   auto DestEltCnt = ElementCount(NumIntermediates * IntermediateNumElts,
748                                  ValueVT.isScalableVector());
749   EVT BuiltVectorTy = EVT::getVectorVT(
750       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt);
751   if (ValueVT != BuiltVectorTy) {
752     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
753       Val = Widened;
754 
755     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
756   }
757 
758   // Split the vector into intermediate operands.
759   SmallVector<SDValue, 8> Ops(NumIntermediates);
760   for (unsigned i = 0; i != NumIntermediates; ++i) {
761     if (IntermediateVT.isVector()) {
762       Ops[i] =
763           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
764                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
765     } else {
766       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
767                            DAG.getVectorIdxConstant(i, DL));
768     }
769   }
770 
771   // Split the intermediate operands into legal parts.
772   if (NumParts == NumIntermediates) {
773     // If the register was not expanded, promote or copy the value,
774     // as appropriate.
775     for (unsigned i = 0; i != NumParts; ++i)
776       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
777   } else if (NumParts > 0) {
778     // If the intermediate type was expanded, split each the value into
779     // legal parts.
780     assert(NumIntermediates != 0 && "division by zero");
781     assert(NumParts % NumIntermediates == 0 &&
782            "Must expand into a divisible number of parts!");
783     unsigned Factor = NumParts / NumIntermediates;
784     for (unsigned i = 0; i != NumIntermediates; ++i)
785       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
786                      CallConv);
787   }
788 }
789 
790 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
791                            EVT valuevt, Optional<CallingConv::ID> CC)
792     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
793       RegCount(1, regs.size()), CallConv(CC) {}
794 
795 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
796                            const DataLayout &DL, unsigned Reg, Type *Ty,
797                            Optional<CallingConv::ID> CC) {
798   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
799 
800   CallConv = CC;
801 
802   for (EVT ValueVT : ValueVTs) {
803     unsigned NumRegs =
804         isABIMangled()
805             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
806             : TLI.getNumRegisters(Context, ValueVT);
807     MVT RegisterVT =
808         isABIMangled()
809             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
810             : TLI.getRegisterType(Context, ValueVT);
811     for (unsigned i = 0; i != NumRegs; ++i)
812       Regs.push_back(Reg + i);
813     RegVTs.push_back(RegisterVT);
814     RegCount.push_back(NumRegs);
815     Reg += NumRegs;
816   }
817 }
818 
819 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
820                                       FunctionLoweringInfo &FuncInfo,
821                                       const SDLoc &dl, SDValue &Chain,
822                                       SDValue *Flag, const Value *V) const {
823   // A Value with type {} or [0 x %t] needs no registers.
824   if (ValueVTs.empty())
825     return SDValue();
826 
827   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
828 
829   // Assemble the legal parts into the final values.
830   SmallVector<SDValue, 4> Values(ValueVTs.size());
831   SmallVector<SDValue, 8> Parts;
832   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
833     // Copy the legal parts from the registers.
834     EVT ValueVT = ValueVTs[Value];
835     unsigned NumRegs = RegCount[Value];
836     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
837                                           *DAG.getContext(),
838                                           CallConv.getValue(), RegVTs[Value])
839                                     : RegVTs[Value];
840 
841     Parts.resize(NumRegs);
842     for (unsigned i = 0; i != NumRegs; ++i) {
843       SDValue P;
844       if (!Flag) {
845         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
846       } else {
847         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
848         *Flag = P.getValue(2);
849       }
850 
851       Chain = P.getValue(1);
852       Parts[i] = P;
853 
854       // If the source register was virtual and if we know something about it,
855       // add an assert node.
856       if (!Register::isVirtualRegister(Regs[Part + i]) ||
857           !RegisterVT.isInteger())
858         continue;
859 
860       const FunctionLoweringInfo::LiveOutInfo *LOI =
861         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
862       if (!LOI)
863         continue;
864 
865       unsigned RegSize = RegisterVT.getScalarSizeInBits();
866       unsigned NumSignBits = LOI->NumSignBits;
867       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
868 
869       if (NumZeroBits == RegSize) {
870         // The current value is a zero.
871         // Explicitly express that as it would be easier for
872         // optimizations to kick in.
873         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
874         continue;
875       }
876 
877       // FIXME: We capture more information than the dag can represent.  For
878       // now, just use the tightest assertzext/assertsext possible.
879       bool isSExt;
880       EVT FromVT(MVT::Other);
881       if (NumZeroBits) {
882         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
883         isSExt = false;
884       } else if (NumSignBits > 1) {
885         FromVT =
886             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
887         isSExt = true;
888       } else {
889         continue;
890       }
891       // Add an assertion node.
892       assert(FromVT != MVT::Other);
893       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
894                              RegisterVT, P, DAG.getValueType(FromVT));
895     }
896 
897     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
898                                      RegisterVT, ValueVT, V, CallConv);
899     Part += NumRegs;
900     Parts.clear();
901   }
902 
903   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
904 }
905 
906 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
907                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
908                                  const Value *V,
909                                  ISD::NodeType PreferredExtendType) const {
910   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
911   ISD::NodeType ExtendKind = PreferredExtendType;
912 
913   // Get the list of the values's legal parts.
914   unsigned NumRegs = Regs.size();
915   SmallVector<SDValue, 8> Parts(NumRegs);
916   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
917     unsigned NumParts = RegCount[Value];
918 
919     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
920                                           *DAG.getContext(),
921                                           CallConv.getValue(), RegVTs[Value])
922                                     : RegVTs[Value];
923 
924     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
925       ExtendKind = ISD::ZERO_EXTEND;
926 
927     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
928                    NumParts, RegisterVT, V, CallConv, ExtendKind);
929     Part += NumParts;
930   }
931 
932   // Copy the parts into the registers.
933   SmallVector<SDValue, 8> Chains(NumRegs);
934   for (unsigned i = 0; i != NumRegs; ++i) {
935     SDValue Part;
936     if (!Flag) {
937       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
938     } else {
939       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
940       *Flag = Part.getValue(1);
941     }
942 
943     Chains[i] = Part.getValue(0);
944   }
945 
946   if (NumRegs == 1 || Flag)
947     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
948     // flagged to it. That is the CopyToReg nodes and the user are considered
949     // a single scheduling unit. If we create a TokenFactor and return it as
950     // chain, then the TokenFactor is both a predecessor (operand) of the
951     // user as well as a successor (the TF operands are flagged to the user).
952     // c1, f1 = CopyToReg
953     // c2, f2 = CopyToReg
954     // c3     = TokenFactor c1, c2
955     // ...
956     //        = op c3, ..., f2
957     Chain = Chains[NumRegs-1];
958   else
959     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
960 }
961 
962 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
963                                         unsigned MatchingIdx, const SDLoc &dl,
964                                         SelectionDAG &DAG,
965                                         std::vector<SDValue> &Ops) const {
966   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
967 
968   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
969   if (HasMatching)
970     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
971   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
972     // Put the register class of the virtual registers in the flag word.  That
973     // way, later passes can recompute register class constraints for inline
974     // assembly as well as normal instructions.
975     // Don't do this for tied operands that can use the regclass information
976     // from the def.
977     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
978     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
979     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
980   }
981 
982   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
983   Ops.push_back(Res);
984 
985   if (Code == InlineAsm::Kind_Clobber) {
986     // Clobbers should always have a 1:1 mapping with registers, and may
987     // reference registers that have illegal (e.g. vector) types. Hence, we
988     // shouldn't try to apply any sort of splitting logic to them.
989     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
990            "No 1:1 mapping from clobbers to regs?");
991     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
992     (void)SP;
993     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
994       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
995       assert(
996           (Regs[I] != SP ||
997            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
998           "If we clobbered the stack pointer, MFI should know about it.");
999     }
1000     return;
1001   }
1002 
1003   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1004     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
1005     MVT RegisterVT = RegVTs[Value];
1006     for (unsigned i = 0; i != NumRegs; ++i) {
1007       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1008       unsigned TheReg = Regs[Reg++];
1009       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1010     }
1011   }
1012 }
1013 
1014 SmallVector<std::pair<unsigned, unsigned>, 4>
1015 RegsForValue::getRegsAndSizes() const {
1016   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1017   unsigned I = 0;
1018   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1019     unsigned RegCount = std::get<0>(CountAndVT);
1020     MVT RegisterVT = std::get<1>(CountAndVT);
1021     unsigned RegisterSize = RegisterVT.getSizeInBits();
1022     for (unsigned E = I + RegCount; I != E; ++I)
1023       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1024   }
1025   return OutVec;
1026 }
1027 
1028 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1029                                const TargetLibraryInfo *li) {
1030   AA = aa;
1031   GFI = gfi;
1032   LibInfo = li;
1033   DL = &DAG.getDataLayout();
1034   Context = DAG.getContext();
1035   LPadToCallSiteMap.clear();
1036   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1037 }
1038 
1039 void SelectionDAGBuilder::clear() {
1040   NodeMap.clear();
1041   UnusedArgNodeMap.clear();
1042   PendingLoads.clear();
1043   PendingExports.clear();
1044   PendingConstrainedFP.clear();
1045   PendingConstrainedFPStrict.clear();
1046   CurInst = nullptr;
1047   HasTailCall = false;
1048   SDNodeOrder = LowestSDNodeOrder;
1049   StatepointLowering.clear();
1050 }
1051 
1052 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1053   DanglingDebugInfoMap.clear();
1054 }
1055 
1056 // Update DAG root to include dependencies on Pending chains.
1057 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1058   SDValue Root = DAG.getRoot();
1059 
1060   if (Pending.empty())
1061     return Root;
1062 
1063   // Add current root to PendingChains, unless we already indirectly
1064   // depend on it.
1065   if (Root.getOpcode() != ISD::EntryToken) {
1066     unsigned i = 0, e = Pending.size();
1067     for (; i != e; ++i) {
1068       assert(Pending[i].getNode()->getNumOperands() > 1);
1069       if (Pending[i].getNode()->getOperand(0) == Root)
1070         break;  // Don't add the root if we already indirectly depend on it.
1071     }
1072 
1073     if (i == e)
1074       Pending.push_back(Root);
1075   }
1076 
1077   if (Pending.size() == 1)
1078     Root = Pending[0];
1079   else
1080     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1081 
1082   DAG.setRoot(Root);
1083   Pending.clear();
1084   return Root;
1085 }
1086 
1087 SDValue SelectionDAGBuilder::getMemoryRoot() {
1088   return updateRoot(PendingLoads);
1089 }
1090 
1091 SDValue SelectionDAGBuilder::getRoot() {
1092   // Chain up all pending constrained intrinsics together with all
1093   // pending loads, by simply appending them to PendingLoads and
1094   // then calling getMemoryRoot().
1095   PendingLoads.reserve(PendingLoads.size() +
1096                        PendingConstrainedFP.size() +
1097                        PendingConstrainedFPStrict.size());
1098   PendingLoads.append(PendingConstrainedFP.begin(),
1099                       PendingConstrainedFP.end());
1100   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1101                       PendingConstrainedFPStrict.end());
1102   PendingConstrainedFP.clear();
1103   PendingConstrainedFPStrict.clear();
1104   return getMemoryRoot();
1105 }
1106 
1107 SDValue SelectionDAGBuilder::getControlRoot() {
1108   // We need to emit pending fpexcept.strict constrained intrinsics,
1109   // so append them to the PendingExports list.
1110   PendingExports.append(PendingConstrainedFPStrict.begin(),
1111                         PendingConstrainedFPStrict.end());
1112   PendingConstrainedFPStrict.clear();
1113   return updateRoot(PendingExports);
1114 }
1115 
1116 void SelectionDAGBuilder::visit(const Instruction &I) {
1117   // Set up outgoing PHI node register values before emitting the terminator.
1118   if (I.isTerminator()) {
1119     HandlePHINodesInSuccessorBlocks(I.getParent());
1120   }
1121 
1122   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1123   if (!isa<DbgInfoIntrinsic>(I))
1124     ++SDNodeOrder;
1125 
1126   CurInst = &I;
1127 
1128   visit(I.getOpcode(), I);
1129 
1130   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1131     // ConstrainedFPIntrinsics handle their own FMF.
1132     if (!isa<ConstrainedFPIntrinsic>(&I)) {
1133       // Propagate the fast-math-flags of this IR instruction to the DAG node that
1134       // maps to this instruction.
1135       // TODO: We could handle all flags (nsw, etc) here.
1136       // TODO: If an IR instruction maps to >1 node, only the final node will have
1137       //       flags set.
1138       if (SDNode *Node = getNodeForIRValue(&I)) {
1139         SDNodeFlags IncomingFlags;
1140         IncomingFlags.copyFMF(*FPMO);
1141         if (!Node->getFlags().isDefined())
1142           Node->setFlags(IncomingFlags);
1143         else
1144           Node->intersectFlagsWith(IncomingFlags);
1145       }
1146     }
1147   }
1148 
1149   if (!I.isTerminator() && !HasTailCall &&
1150       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1151     CopyToExportRegsIfNeeded(&I);
1152 
1153   CurInst = nullptr;
1154 }
1155 
1156 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1157   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1158 }
1159 
1160 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1161   // Note: this doesn't use InstVisitor, because it has to work with
1162   // ConstantExpr's in addition to instructions.
1163   switch (Opcode) {
1164   default: llvm_unreachable("Unknown instruction type encountered!");
1165     // Build the switch statement using the Instruction.def file.
1166 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1167     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1168 #include "llvm/IR/Instruction.def"
1169   }
1170 }
1171 
1172 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1173                                                 const DIExpression *Expr) {
1174   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1175     const DbgValueInst *DI = DDI.getDI();
1176     DIVariable *DanglingVariable = DI->getVariable();
1177     DIExpression *DanglingExpr = DI->getExpression();
1178     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1179       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1180       return true;
1181     }
1182     return false;
1183   };
1184 
1185   for (auto &DDIMI : DanglingDebugInfoMap) {
1186     DanglingDebugInfoVector &DDIV = DDIMI.second;
1187 
1188     // If debug info is to be dropped, run it through final checks to see
1189     // whether it can be salvaged.
1190     for (auto &DDI : DDIV)
1191       if (isMatchingDbgValue(DDI))
1192         salvageUnresolvedDbgValue(DDI);
1193 
1194     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1195   }
1196 }
1197 
1198 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1199 // generate the debug data structures now that we've seen its definition.
1200 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1201                                                    SDValue Val) {
1202   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1203   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1204     return;
1205 
1206   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1207   for (auto &DDI : DDIV) {
1208     const DbgValueInst *DI = DDI.getDI();
1209     assert(DI && "Ill-formed DanglingDebugInfo");
1210     DebugLoc dl = DDI.getdl();
1211     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1212     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1213     DILocalVariable *Variable = DI->getVariable();
1214     DIExpression *Expr = DI->getExpression();
1215     assert(Variable->isValidLocationForIntrinsic(dl) &&
1216            "Expected inlined-at fields to agree");
1217     SDDbgValue *SDV;
1218     if (Val.getNode()) {
1219       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1220       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1221       // we couldn't resolve it directly when examining the DbgValue intrinsic
1222       // in the first place we should not be more successful here). Unless we
1223       // have some test case that prove this to be correct we should avoid
1224       // calling EmitFuncArgumentDbgValue here.
1225       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1226         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1227                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1228         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1229         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1230         // inserted after the definition of Val when emitting the instructions
1231         // after ISel. An alternative could be to teach
1232         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1233         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1234                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1235                    << ValSDNodeOrder << "\n");
1236         SDV = getDbgValue(Val, Variable, Expr, dl,
1237                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1238         DAG.AddDbgValue(SDV, Val.getNode(), false);
1239       } else
1240         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1241                           << "in EmitFuncArgumentDbgValue\n");
1242     } else {
1243       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1244       auto Undef =
1245           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1246       auto SDV =
1247           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1248       DAG.AddDbgValue(SDV, nullptr, false);
1249     }
1250   }
1251   DDIV.clear();
1252 }
1253 
1254 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1255   Value *V = DDI.getDI()->getValue();
1256   DILocalVariable *Var = DDI.getDI()->getVariable();
1257   DIExpression *Expr = DDI.getDI()->getExpression();
1258   DebugLoc DL = DDI.getdl();
1259   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1260   unsigned SDOrder = DDI.getSDNodeOrder();
1261 
1262   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1263   // that DW_OP_stack_value is desired.
1264   assert(isa<DbgValueInst>(DDI.getDI()));
1265   bool StackValue = true;
1266 
1267   // Can this Value can be encoded without any further work?
1268   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1269     return;
1270 
1271   // Attempt to salvage back through as many instructions as possible. Bail if
1272   // a non-instruction is seen, such as a constant expression or global
1273   // variable. FIXME: Further work could recover those too.
1274   while (isa<Instruction>(V)) {
1275     Instruction &VAsInst = *cast<Instruction>(V);
1276     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1277 
1278     // If we cannot salvage any further, and haven't yet found a suitable debug
1279     // expression, bail out.
1280     if (!NewExpr)
1281       break;
1282 
1283     // New value and expr now represent this debuginfo.
1284     V = VAsInst.getOperand(0);
1285     Expr = NewExpr;
1286 
1287     // Some kind of simplification occurred: check whether the operand of the
1288     // salvaged debug expression can be encoded in this DAG.
1289     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1290       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1291                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1292       return;
1293     }
1294   }
1295 
1296   // This was the final opportunity to salvage this debug information, and it
1297   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1298   // any earlier variable location.
1299   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1300   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1301   DAG.AddDbgValue(SDV, nullptr, false);
1302 
1303   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1304                     << "\n");
1305   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1306                     << "\n");
1307 }
1308 
1309 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1310                                            DIExpression *Expr, DebugLoc dl,
1311                                            DebugLoc InstDL, unsigned Order) {
1312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1313   SDDbgValue *SDV;
1314   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1315       isa<ConstantPointerNull>(V)) {
1316     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1317     DAG.AddDbgValue(SDV, nullptr, false);
1318     return true;
1319   }
1320 
1321   // If the Value is a frame index, we can create a FrameIndex debug value
1322   // without relying on the DAG at all.
1323   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1324     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1325     if (SI != FuncInfo.StaticAllocaMap.end()) {
1326       auto SDV =
1327           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1328                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1329       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1330       // is still available even if the SDNode gets optimized out.
1331       DAG.AddDbgValue(SDV, nullptr, false);
1332       return true;
1333     }
1334   }
1335 
1336   // Do not use getValue() in here; we don't want to generate code at
1337   // this point if it hasn't been done yet.
1338   SDValue N = NodeMap[V];
1339   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1340     N = UnusedArgNodeMap[V];
1341   if (N.getNode()) {
1342     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1343       return true;
1344     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1345     DAG.AddDbgValue(SDV, N.getNode(), false);
1346     return true;
1347   }
1348 
1349   // Special rules apply for the first dbg.values of parameter variables in a
1350   // function. Identify them by the fact they reference Argument Values, that
1351   // they're parameters, and they are parameters of the current function. We
1352   // need to let them dangle until they get an SDNode.
1353   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1354                        !InstDL.getInlinedAt();
1355   if (!IsParamOfFunc) {
1356     // The value is not used in this block yet (or it would have an SDNode).
1357     // We still want the value to appear for the user if possible -- if it has
1358     // an associated VReg, we can refer to that instead.
1359     auto VMI = FuncInfo.ValueMap.find(V);
1360     if (VMI != FuncInfo.ValueMap.end()) {
1361       unsigned Reg = VMI->second;
1362       // If this is a PHI node, it may be split up into several MI PHI nodes
1363       // (in FunctionLoweringInfo::set).
1364       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1365                        V->getType(), None);
1366       if (RFV.occupiesMultipleRegs()) {
1367         unsigned Offset = 0;
1368         unsigned BitsToDescribe = 0;
1369         if (auto VarSize = Var->getSizeInBits())
1370           BitsToDescribe = *VarSize;
1371         if (auto Fragment = Expr->getFragmentInfo())
1372           BitsToDescribe = Fragment->SizeInBits;
1373         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1374           unsigned RegisterSize = RegAndSize.second;
1375           // Bail out if all bits are described already.
1376           if (Offset >= BitsToDescribe)
1377             break;
1378           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1379               ? BitsToDescribe - Offset
1380               : RegisterSize;
1381           auto FragmentExpr = DIExpression::createFragmentExpression(
1382               Expr, Offset, FragmentSize);
1383           if (!FragmentExpr)
1384               continue;
1385           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1386                                     false, dl, SDNodeOrder);
1387           DAG.AddDbgValue(SDV, nullptr, false);
1388           Offset += RegisterSize;
1389         }
1390       } else {
1391         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1392         DAG.AddDbgValue(SDV, nullptr, false);
1393       }
1394       return true;
1395     }
1396   }
1397 
1398   return false;
1399 }
1400 
1401 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1402   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1403   for (auto &Pair : DanglingDebugInfoMap)
1404     for (auto &DDI : Pair.second)
1405       salvageUnresolvedDbgValue(DDI);
1406   clearDanglingDebugInfo();
1407 }
1408 
1409 /// getCopyFromRegs - If there was virtual register allocated for the value V
1410 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1411 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1412   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1413   SDValue Result;
1414 
1415   if (It != FuncInfo.ValueMap.end()) {
1416     Register InReg = It->second;
1417 
1418     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1419                      DAG.getDataLayout(), InReg, Ty,
1420                      None); // This is not an ABI copy.
1421     SDValue Chain = DAG.getEntryNode();
1422     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1423                                  V);
1424     resolveDanglingDebugInfo(V, Result);
1425   }
1426 
1427   return Result;
1428 }
1429 
1430 /// getValue - Return an SDValue for the given Value.
1431 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1432   // If we already have an SDValue for this value, use it. It's important
1433   // to do this first, so that we don't create a CopyFromReg if we already
1434   // have a regular SDValue.
1435   SDValue &N = NodeMap[V];
1436   if (N.getNode()) return N;
1437 
1438   // If there's a virtual register allocated and initialized for this
1439   // value, use it.
1440   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1441     return copyFromReg;
1442 
1443   // Otherwise create a new SDValue and remember it.
1444   SDValue Val = getValueImpl(V);
1445   NodeMap[V] = Val;
1446   resolveDanglingDebugInfo(V, Val);
1447   return Val;
1448 }
1449 
1450 /// getNonRegisterValue - Return an SDValue for the given Value, but
1451 /// don't look in FuncInfo.ValueMap for a virtual register.
1452 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1453   // If we already have an SDValue for this value, use it.
1454   SDValue &N = NodeMap[V];
1455   if (N.getNode()) {
1456     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1457       // Remove the debug location from the node as the node is about to be used
1458       // in a location which may differ from the original debug location.  This
1459       // is relevant to Constant and ConstantFP nodes because they can appear
1460       // as constant expressions inside PHI nodes.
1461       N->setDebugLoc(DebugLoc());
1462     }
1463     return N;
1464   }
1465 
1466   // Otherwise create a new SDValue and remember it.
1467   SDValue Val = getValueImpl(V);
1468   NodeMap[V] = Val;
1469   resolveDanglingDebugInfo(V, Val);
1470   return Val;
1471 }
1472 
1473 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1474 /// Create an SDValue for the given value.
1475 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1477 
1478   if (const Constant *C = dyn_cast<Constant>(V)) {
1479     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1480 
1481     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1482       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1483 
1484     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1485       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1486 
1487     if (isa<ConstantPointerNull>(C)) {
1488       unsigned AS = V->getType()->getPointerAddressSpace();
1489       return DAG.getConstant(0, getCurSDLoc(),
1490                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1491     }
1492 
1493     if (match(C, m_VScale(DAG.getDataLayout())))
1494       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1495 
1496     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1497       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1498 
1499     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1500       return DAG.getUNDEF(VT);
1501 
1502     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1503       visit(CE->getOpcode(), *CE);
1504       SDValue N1 = NodeMap[V];
1505       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1506       return N1;
1507     }
1508 
1509     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1510       SmallVector<SDValue, 4> Constants;
1511       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1512            OI != OE; ++OI) {
1513         SDNode *Val = getValue(*OI).getNode();
1514         // If the operand is an empty aggregate, there are no values.
1515         if (!Val) continue;
1516         // Add each leaf value from the operand to the Constants list
1517         // to form a flattened list of all the values.
1518         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1519           Constants.push_back(SDValue(Val, i));
1520       }
1521 
1522       return DAG.getMergeValues(Constants, getCurSDLoc());
1523     }
1524 
1525     if (const ConstantDataSequential *CDS =
1526           dyn_cast<ConstantDataSequential>(C)) {
1527       SmallVector<SDValue, 4> Ops;
1528       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1529         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1530         // Add each leaf value from the operand to the Constants list
1531         // to form a flattened list of all the values.
1532         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1533           Ops.push_back(SDValue(Val, i));
1534       }
1535 
1536       if (isa<ArrayType>(CDS->getType()))
1537         return DAG.getMergeValues(Ops, getCurSDLoc());
1538       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1539     }
1540 
1541     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1542       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1543              "Unknown struct or array constant!");
1544 
1545       SmallVector<EVT, 4> ValueVTs;
1546       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1547       unsigned NumElts = ValueVTs.size();
1548       if (NumElts == 0)
1549         return SDValue(); // empty struct
1550       SmallVector<SDValue, 4> Constants(NumElts);
1551       for (unsigned i = 0; i != NumElts; ++i) {
1552         EVT EltVT = ValueVTs[i];
1553         if (isa<UndefValue>(C))
1554           Constants[i] = DAG.getUNDEF(EltVT);
1555         else if (EltVT.isFloatingPoint())
1556           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1557         else
1558           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1559       }
1560 
1561       return DAG.getMergeValues(Constants, getCurSDLoc());
1562     }
1563 
1564     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1565       return DAG.getBlockAddress(BA, VT);
1566 
1567     VectorType *VecTy = cast<VectorType>(V->getType());
1568 
1569     // Now that we know the number and type of the elements, get that number of
1570     // elements into the Ops array based on what kind of constant it is.
1571     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1572       SmallVector<SDValue, 16> Ops;
1573       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1574       for (unsigned i = 0; i != NumElements; ++i)
1575         Ops.push_back(getValue(CV->getOperand(i)));
1576 
1577       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1578     } else if (isa<ConstantAggregateZero>(C)) {
1579       EVT EltVT =
1580           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1581 
1582       SDValue Op;
1583       if (EltVT.isFloatingPoint())
1584         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1585       else
1586         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1587 
1588       if (isa<ScalableVectorType>(VecTy))
1589         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1590       else {
1591         SmallVector<SDValue, 16> Ops;
1592         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1593         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1594       }
1595     }
1596     llvm_unreachable("Unknown vector constant");
1597   }
1598 
1599   // If this is a static alloca, generate it as the frameindex instead of
1600   // computation.
1601   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1602     DenseMap<const AllocaInst*, int>::iterator SI =
1603       FuncInfo.StaticAllocaMap.find(AI);
1604     if (SI != FuncInfo.StaticAllocaMap.end())
1605       return DAG.getFrameIndex(SI->second,
1606                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1607   }
1608 
1609   // If this is an instruction which fast-isel has deferred, select it now.
1610   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1611     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1612 
1613     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1614                      Inst->getType(), getABIRegCopyCC(V));
1615     SDValue Chain = DAG.getEntryNode();
1616     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1617   }
1618 
1619   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1620     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1621   }
1622   llvm_unreachable("Can't get register for value!");
1623 }
1624 
1625 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1626   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1627   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1628   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1629   bool IsSEH = isAsynchronousEHPersonality(Pers);
1630   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1631   if (!IsSEH)
1632     CatchPadMBB->setIsEHScopeEntry();
1633   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1634   if (IsMSVCCXX || IsCoreCLR)
1635     CatchPadMBB->setIsEHFuncletEntry();
1636 }
1637 
1638 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1639   // Update machine-CFG edge.
1640   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1641   FuncInfo.MBB->addSuccessor(TargetMBB);
1642 
1643   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1644   bool IsSEH = isAsynchronousEHPersonality(Pers);
1645   if (IsSEH) {
1646     // If this is not a fall-through branch or optimizations are switched off,
1647     // emit the branch.
1648     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1649         TM.getOptLevel() == CodeGenOpt::None)
1650       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1651                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1652     return;
1653   }
1654 
1655   // Figure out the funclet membership for the catchret's successor.
1656   // This will be used by the FuncletLayout pass to determine how to order the
1657   // BB's.
1658   // A 'catchret' returns to the outer scope's color.
1659   Value *ParentPad = I.getCatchSwitchParentPad();
1660   const BasicBlock *SuccessorColor;
1661   if (isa<ConstantTokenNone>(ParentPad))
1662     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1663   else
1664     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1665   assert(SuccessorColor && "No parent funclet for catchret!");
1666   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1667   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1668 
1669   // Create the terminator node.
1670   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1671                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1672                             DAG.getBasicBlock(SuccessorColorMBB));
1673   DAG.setRoot(Ret);
1674 }
1675 
1676 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1677   // Don't emit any special code for the cleanuppad instruction. It just marks
1678   // the start of an EH scope/funclet.
1679   FuncInfo.MBB->setIsEHScopeEntry();
1680   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1681   if (Pers != EHPersonality::Wasm_CXX) {
1682     FuncInfo.MBB->setIsEHFuncletEntry();
1683     FuncInfo.MBB->setIsCleanupFuncletEntry();
1684   }
1685 }
1686 
1687 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1688 // the control flow always stops at the single catch pad, as it does for a
1689 // cleanup pad. In case the exception caught is not of the types the catch pad
1690 // catches, it will be rethrown by a rethrow.
1691 static void findWasmUnwindDestinations(
1692     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1693     BranchProbability Prob,
1694     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1695         &UnwindDests) {
1696   while (EHPadBB) {
1697     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1698     if (isa<CleanupPadInst>(Pad)) {
1699       // Stop on cleanup pads.
1700       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1701       UnwindDests.back().first->setIsEHScopeEntry();
1702       break;
1703     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1704       // Add the catchpad handlers to the possible destinations. We don't
1705       // continue to the unwind destination of the catchswitch for wasm.
1706       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1707         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1708         UnwindDests.back().first->setIsEHScopeEntry();
1709       }
1710       break;
1711     } else {
1712       continue;
1713     }
1714   }
1715 }
1716 
1717 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1718 /// many places it could ultimately go. In the IR, we have a single unwind
1719 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1720 /// This function skips over imaginary basic blocks that hold catchswitch
1721 /// instructions, and finds all the "real" machine
1722 /// basic block destinations. As those destinations may not be successors of
1723 /// EHPadBB, here we also calculate the edge probability to those destinations.
1724 /// The passed-in Prob is the edge probability to EHPadBB.
1725 static void findUnwindDestinations(
1726     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1727     BranchProbability Prob,
1728     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1729         &UnwindDests) {
1730   EHPersonality Personality =
1731     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1732   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1733   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1734   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1735   bool IsSEH = isAsynchronousEHPersonality(Personality);
1736 
1737   if (IsWasmCXX) {
1738     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1739     assert(UnwindDests.size() <= 1 &&
1740            "There should be at most one unwind destination for wasm");
1741     return;
1742   }
1743 
1744   while (EHPadBB) {
1745     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1746     BasicBlock *NewEHPadBB = nullptr;
1747     if (isa<LandingPadInst>(Pad)) {
1748       // Stop on landingpads. They are not funclets.
1749       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1750       break;
1751     } else if (isa<CleanupPadInst>(Pad)) {
1752       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1753       // personalities.
1754       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1755       UnwindDests.back().first->setIsEHScopeEntry();
1756       UnwindDests.back().first->setIsEHFuncletEntry();
1757       break;
1758     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1759       // Add the catchpad handlers to the possible destinations.
1760       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1761         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1762         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1763         if (IsMSVCCXX || IsCoreCLR)
1764           UnwindDests.back().first->setIsEHFuncletEntry();
1765         if (!IsSEH)
1766           UnwindDests.back().first->setIsEHScopeEntry();
1767       }
1768       NewEHPadBB = CatchSwitch->getUnwindDest();
1769     } else {
1770       continue;
1771     }
1772 
1773     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1774     if (BPI && NewEHPadBB)
1775       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1776     EHPadBB = NewEHPadBB;
1777   }
1778 }
1779 
1780 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1781   // Update successor info.
1782   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1783   auto UnwindDest = I.getUnwindDest();
1784   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1785   BranchProbability UnwindDestProb =
1786       (BPI && UnwindDest)
1787           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1788           : BranchProbability::getZero();
1789   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1790   for (auto &UnwindDest : UnwindDests) {
1791     UnwindDest.first->setIsEHPad();
1792     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1793   }
1794   FuncInfo.MBB->normalizeSuccProbs();
1795 
1796   // Create the terminator node.
1797   SDValue Ret =
1798       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1799   DAG.setRoot(Ret);
1800 }
1801 
1802 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1803   report_fatal_error("visitCatchSwitch not yet implemented!");
1804 }
1805 
1806 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1808   auto &DL = DAG.getDataLayout();
1809   SDValue Chain = getControlRoot();
1810   SmallVector<ISD::OutputArg, 8> Outs;
1811   SmallVector<SDValue, 8> OutVals;
1812 
1813   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1814   // lower
1815   //
1816   //   %val = call <ty> @llvm.experimental.deoptimize()
1817   //   ret <ty> %val
1818   //
1819   // differently.
1820   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1821     LowerDeoptimizingReturn();
1822     return;
1823   }
1824 
1825   if (!FuncInfo.CanLowerReturn) {
1826     unsigned DemoteReg = FuncInfo.DemoteRegister;
1827     const Function *F = I.getParent()->getParent();
1828 
1829     // Emit a store of the return value through the virtual register.
1830     // Leave Outs empty so that LowerReturn won't try to load return
1831     // registers the usual way.
1832     SmallVector<EVT, 1> PtrValueVTs;
1833     ComputeValueVTs(TLI, DL,
1834                     F->getReturnType()->getPointerTo(
1835                         DAG.getDataLayout().getAllocaAddrSpace()),
1836                     PtrValueVTs);
1837 
1838     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1839                                         DemoteReg, PtrValueVTs[0]);
1840     SDValue RetOp = getValue(I.getOperand(0));
1841 
1842     SmallVector<EVT, 4> ValueVTs, MemVTs;
1843     SmallVector<uint64_t, 4> Offsets;
1844     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1845                     &Offsets);
1846     unsigned NumValues = ValueVTs.size();
1847 
1848     SmallVector<SDValue, 4> Chains(NumValues);
1849     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1850     for (unsigned i = 0; i != NumValues; ++i) {
1851       // An aggregate return value cannot wrap around the address space, so
1852       // offsets to its parts don't wrap either.
1853       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1854 
1855       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1856       if (MemVTs[i] != ValueVTs[i])
1857         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1858       Chains[i] = DAG.getStore(
1859           Chain, getCurSDLoc(), Val,
1860           // FIXME: better loc info would be nice.
1861           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1862           commonAlignment(BaseAlign, Offsets[i]));
1863     }
1864 
1865     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1866                         MVT::Other, Chains);
1867   } else if (I.getNumOperands() != 0) {
1868     SmallVector<EVT, 4> ValueVTs;
1869     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1870     unsigned NumValues = ValueVTs.size();
1871     if (NumValues) {
1872       SDValue RetOp = getValue(I.getOperand(0));
1873 
1874       const Function *F = I.getParent()->getParent();
1875 
1876       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1877           I.getOperand(0)->getType(), F->getCallingConv(),
1878           /*IsVarArg*/ false);
1879 
1880       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1881       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1882                                           Attribute::SExt))
1883         ExtendKind = ISD::SIGN_EXTEND;
1884       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1885                                                Attribute::ZExt))
1886         ExtendKind = ISD::ZERO_EXTEND;
1887 
1888       LLVMContext &Context = F->getContext();
1889       bool RetInReg = F->getAttributes().hasAttribute(
1890           AttributeList::ReturnIndex, Attribute::InReg);
1891 
1892       for (unsigned j = 0; j != NumValues; ++j) {
1893         EVT VT = ValueVTs[j];
1894 
1895         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1896           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1897 
1898         CallingConv::ID CC = F->getCallingConv();
1899 
1900         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1901         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1902         SmallVector<SDValue, 4> Parts(NumParts);
1903         getCopyToParts(DAG, getCurSDLoc(),
1904                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1905                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1906 
1907         // 'inreg' on function refers to return value
1908         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1909         if (RetInReg)
1910           Flags.setInReg();
1911 
1912         if (I.getOperand(0)->getType()->isPointerTy()) {
1913           Flags.setPointer();
1914           Flags.setPointerAddrSpace(
1915               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1916         }
1917 
1918         if (NeedsRegBlock) {
1919           Flags.setInConsecutiveRegs();
1920           if (j == NumValues - 1)
1921             Flags.setInConsecutiveRegsLast();
1922         }
1923 
1924         // Propagate extension type if any
1925         if (ExtendKind == ISD::SIGN_EXTEND)
1926           Flags.setSExt();
1927         else if (ExtendKind == ISD::ZERO_EXTEND)
1928           Flags.setZExt();
1929 
1930         for (unsigned i = 0; i < NumParts; ++i) {
1931           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1932                                         VT, /*isfixed=*/true, 0, 0));
1933           OutVals.push_back(Parts[i]);
1934         }
1935       }
1936     }
1937   }
1938 
1939   // Push in swifterror virtual register as the last element of Outs. This makes
1940   // sure swifterror virtual register will be returned in the swifterror
1941   // physical register.
1942   const Function *F = I.getParent()->getParent();
1943   if (TLI.supportSwiftError() &&
1944       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1945     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1946     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1947     Flags.setSwiftError();
1948     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1949                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1950                                   true /*isfixed*/, 1 /*origidx*/,
1951                                   0 /*partOffs*/));
1952     // Create SDNode for the swifterror virtual register.
1953     OutVals.push_back(
1954         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1955                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1956                         EVT(TLI.getPointerTy(DL))));
1957   }
1958 
1959   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1960   CallingConv::ID CallConv =
1961     DAG.getMachineFunction().getFunction().getCallingConv();
1962   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1963       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1964 
1965   // Verify that the target's LowerReturn behaved as expected.
1966   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1967          "LowerReturn didn't return a valid chain!");
1968 
1969   // Update the DAG with the new chain value resulting from return lowering.
1970   DAG.setRoot(Chain);
1971 }
1972 
1973 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1974 /// created for it, emit nodes to copy the value into the virtual
1975 /// registers.
1976 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1977   // Skip empty types
1978   if (V->getType()->isEmptyTy())
1979     return;
1980 
1981   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1982   if (VMI != FuncInfo.ValueMap.end()) {
1983     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1984     CopyValueToVirtualRegister(V, VMI->second);
1985   }
1986 }
1987 
1988 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1989 /// the current basic block, add it to ValueMap now so that we'll get a
1990 /// CopyTo/FromReg.
1991 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1992   // No need to export constants.
1993   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1994 
1995   // Already exported?
1996   if (FuncInfo.isExportedInst(V)) return;
1997 
1998   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1999   CopyValueToVirtualRegister(V, Reg);
2000 }
2001 
2002 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2003                                                      const BasicBlock *FromBB) {
2004   // The operands of the setcc have to be in this block.  We don't know
2005   // how to export them from some other block.
2006   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2007     // Can export from current BB.
2008     if (VI->getParent() == FromBB)
2009       return true;
2010 
2011     // Is already exported, noop.
2012     return FuncInfo.isExportedInst(V);
2013   }
2014 
2015   // If this is an argument, we can export it if the BB is the entry block or
2016   // if it is already exported.
2017   if (isa<Argument>(V)) {
2018     if (FromBB == &FromBB->getParent()->getEntryBlock())
2019       return true;
2020 
2021     // Otherwise, can only export this if it is already exported.
2022     return FuncInfo.isExportedInst(V);
2023   }
2024 
2025   // Otherwise, constants can always be exported.
2026   return true;
2027 }
2028 
2029 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2030 BranchProbability
2031 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2032                                         const MachineBasicBlock *Dst) const {
2033   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2034   const BasicBlock *SrcBB = Src->getBasicBlock();
2035   const BasicBlock *DstBB = Dst->getBasicBlock();
2036   if (!BPI) {
2037     // If BPI is not available, set the default probability as 1 / N, where N is
2038     // the number of successors.
2039     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2040     return BranchProbability(1, SuccSize);
2041   }
2042   return BPI->getEdgeProbability(SrcBB, DstBB);
2043 }
2044 
2045 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2046                                                MachineBasicBlock *Dst,
2047                                                BranchProbability Prob) {
2048   if (!FuncInfo.BPI)
2049     Src->addSuccessorWithoutProb(Dst);
2050   else {
2051     if (Prob.isUnknown())
2052       Prob = getEdgeProbability(Src, Dst);
2053     Src->addSuccessor(Dst, Prob);
2054   }
2055 }
2056 
2057 static bool InBlock(const Value *V, const BasicBlock *BB) {
2058   if (const Instruction *I = dyn_cast<Instruction>(V))
2059     return I->getParent() == BB;
2060   return true;
2061 }
2062 
2063 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2064 /// This function emits a branch and is used at the leaves of an OR or an
2065 /// AND operator tree.
2066 void
2067 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2068                                                   MachineBasicBlock *TBB,
2069                                                   MachineBasicBlock *FBB,
2070                                                   MachineBasicBlock *CurBB,
2071                                                   MachineBasicBlock *SwitchBB,
2072                                                   BranchProbability TProb,
2073                                                   BranchProbability FProb,
2074                                                   bool InvertCond) {
2075   const BasicBlock *BB = CurBB->getBasicBlock();
2076 
2077   // If the leaf of the tree is a comparison, merge the condition into
2078   // the caseblock.
2079   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2080     // The operands of the cmp have to be in this block.  We don't know
2081     // how to export them from some other block.  If this is the first block
2082     // of the sequence, no exporting is needed.
2083     if (CurBB == SwitchBB ||
2084         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2085          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2086       ISD::CondCode Condition;
2087       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2088         ICmpInst::Predicate Pred =
2089             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2090         Condition = getICmpCondCode(Pred);
2091       } else {
2092         const FCmpInst *FC = cast<FCmpInst>(Cond);
2093         FCmpInst::Predicate Pred =
2094             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2095         Condition = getFCmpCondCode(Pred);
2096         if (TM.Options.NoNaNsFPMath)
2097           Condition = getFCmpCodeWithoutNaN(Condition);
2098       }
2099 
2100       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2101                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2102       SL->SwitchCases.push_back(CB);
2103       return;
2104     }
2105   }
2106 
2107   // Create a CaseBlock record representing this branch.
2108   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2109   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2110                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2111   SL->SwitchCases.push_back(CB);
2112 }
2113 
2114 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2115                                                MachineBasicBlock *TBB,
2116                                                MachineBasicBlock *FBB,
2117                                                MachineBasicBlock *CurBB,
2118                                                MachineBasicBlock *SwitchBB,
2119                                                Instruction::BinaryOps Opc,
2120                                                BranchProbability TProb,
2121                                                BranchProbability FProb,
2122                                                bool InvertCond) {
2123   // Skip over not part of the tree and remember to invert op and operands at
2124   // next level.
2125   Value *NotCond;
2126   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2127       InBlock(NotCond, CurBB->getBasicBlock())) {
2128     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2129                          !InvertCond);
2130     return;
2131   }
2132 
2133   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2134   // Compute the effective opcode for Cond, taking into account whether it needs
2135   // to be inverted, e.g.
2136   //   and (not (or A, B)), C
2137   // gets lowered as
2138   //   and (and (not A, not B), C)
2139   unsigned BOpc = 0;
2140   if (BOp) {
2141     BOpc = BOp->getOpcode();
2142     if (InvertCond) {
2143       if (BOpc == Instruction::And)
2144         BOpc = Instruction::Or;
2145       else if (BOpc == Instruction::Or)
2146         BOpc = Instruction::And;
2147     }
2148   }
2149 
2150   // If this node is not part of the or/and tree, emit it as a branch.
2151   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2152       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2153       BOp->getParent() != CurBB->getBasicBlock() ||
2154       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2155       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2156     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2157                                  TProb, FProb, InvertCond);
2158     return;
2159   }
2160 
2161   //  Create TmpBB after CurBB.
2162   MachineFunction::iterator BBI(CurBB);
2163   MachineFunction &MF = DAG.getMachineFunction();
2164   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2165   CurBB->getParent()->insert(++BBI, TmpBB);
2166 
2167   if (Opc == Instruction::Or) {
2168     // Codegen X | Y as:
2169     // BB1:
2170     //   jmp_if_X TBB
2171     //   jmp TmpBB
2172     // TmpBB:
2173     //   jmp_if_Y TBB
2174     //   jmp FBB
2175     //
2176 
2177     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2178     // The requirement is that
2179     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2180     //     = TrueProb for original BB.
2181     // Assuming the original probabilities are A and B, one choice is to set
2182     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2183     // A/(1+B) and 2B/(1+B). This choice assumes that
2184     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2185     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2186     // TmpBB, but the math is more complicated.
2187 
2188     auto NewTrueProb = TProb / 2;
2189     auto NewFalseProb = TProb / 2 + FProb;
2190     // Emit the LHS condition.
2191     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2192                          NewTrueProb, NewFalseProb, InvertCond);
2193 
2194     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2195     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2196     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2197     // Emit the RHS condition into TmpBB.
2198     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2199                          Probs[0], Probs[1], InvertCond);
2200   } else {
2201     assert(Opc == Instruction::And && "Unknown merge op!");
2202     // Codegen X & Y as:
2203     // BB1:
2204     //   jmp_if_X TmpBB
2205     //   jmp FBB
2206     // TmpBB:
2207     //   jmp_if_Y TBB
2208     //   jmp FBB
2209     //
2210     //  This requires creation of TmpBB after CurBB.
2211 
2212     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2213     // The requirement is that
2214     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2215     //     = FalseProb for original BB.
2216     // Assuming the original probabilities are A and B, one choice is to set
2217     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2218     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2219     // TrueProb for BB1 * FalseProb for TmpBB.
2220 
2221     auto NewTrueProb = TProb + FProb / 2;
2222     auto NewFalseProb = FProb / 2;
2223     // Emit the LHS condition.
2224     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2225                          NewTrueProb, NewFalseProb, InvertCond);
2226 
2227     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2228     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2229     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2230     // Emit the RHS condition into TmpBB.
2231     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2232                          Probs[0], Probs[1], InvertCond);
2233   }
2234 }
2235 
2236 /// If the set of cases should be emitted as a series of branches, return true.
2237 /// If we should emit this as a bunch of and/or'd together conditions, return
2238 /// false.
2239 bool
2240 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2241   if (Cases.size() != 2) return true;
2242 
2243   // If this is two comparisons of the same values or'd or and'd together, they
2244   // will get folded into a single comparison, so don't emit two blocks.
2245   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2246        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2247       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2248        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2249     return false;
2250   }
2251 
2252   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2253   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2254   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2255       Cases[0].CC == Cases[1].CC &&
2256       isa<Constant>(Cases[0].CmpRHS) &&
2257       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2258     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2259       return false;
2260     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2261       return false;
2262   }
2263 
2264   return true;
2265 }
2266 
2267 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2268   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2269 
2270   // Update machine-CFG edges.
2271   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2272 
2273   if (I.isUnconditional()) {
2274     // Update machine-CFG edges.
2275     BrMBB->addSuccessor(Succ0MBB);
2276 
2277     // If this is not a fall-through branch or optimizations are switched off,
2278     // emit the branch.
2279     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2280       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2281                               MVT::Other, getControlRoot(),
2282                               DAG.getBasicBlock(Succ0MBB)));
2283 
2284     return;
2285   }
2286 
2287   // If this condition is one of the special cases we handle, do special stuff
2288   // now.
2289   const Value *CondVal = I.getCondition();
2290   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2291 
2292   // If this is a series of conditions that are or'd or and'd together, emit
2293   // this as a sequence of branches instead of setcc's with and/or operations.
2294   // As long as jumps are not expensive, this should improve performance.
2295   // For example, instead of something like:
2296   //     cmp A, B
2297   //     C = seteq
2298   //     cmp D, E
2299   //     F = setle
2300   //     or C, F
2301   //     jnz foo
2302   // Emit:
2303   //     cmp A, B
2304   //     je foo
2305   //     cmp D, E
2306   //     jle foo
2307   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2308     Instruction::BinaryOps Opcode = BOp->getOpcode();
2309     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2310         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2311         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2312       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2313                            Opcode,
2314                            getEdgeProbability(BrMBB, Succ0MBB),
2315                            getEdgeProbability(BrMBB, Succ1MBB),
2316                            /*InvertCond=*/false);
2317       // If the compares in later blocks need to use values not currently
2318       // exported from this block, export them now.  This block should always
2319       // be the first entry.
2320       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2321 
2322       // Allow some cases to be rejected.
2323       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2324         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2325           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2326           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2327         }
2328 
2329         // Emit the branch for this block.
2330         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2331         SL->SwitchCases.erase(SL->SwitchCases.begin());
2332         return;
2333       }
2334 
2335       // Okay, we decided not to do this, remove any inserted MBB's and clear
2336       // SwitchCases.
2337       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2338         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2339 
2340       SL->SwitchCases.clear();
2341     }
2342   }
2343 
2344   // Create a CaseBlock record representing this branch.
2345   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2346                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2347 
2348   // Use visitSwitchCase to actually insert the fast branch sequence for this
2349   // cond branch.
2350   visitSwitchCase(CB, BrMBB);
2351 }
2352 
2353 /// visitSwitchCase - Emits the necessary code to represent a single node in
2354 /// the binary search tree resulting from lowering a switch instruction.
2355 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2356                                           MachineBasicBlock *SwitchBB) {
2357   SDValue Cond;
2358   SDValue CondLHS = getValue(CB.CmpLHS);
2359   SDLoc dl = CB.DL;
2360 
2361   if (CB.CC == ISD::SETTRUE) {
2362     // Branch or fall through to TrueBB.
2363     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2364     SwitchBB->normalizeSuccProbs();
2365     if (CB.TrueBB != NextBlock(SwitchBB)) {
2366       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2367                               DAG.getBasicBlock(CB.TrueBB)));
2368     }
2369     return;
2370   }
2371 
2372   auto &TLI = DAG.getTargetLoweringInfo();
2373   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2374 
2375   // Build the setcc now.
2376   if (!CB.CmpMHS) {
2377     // Fold "(X == true)" to X and "(X == false)" to !X to
2378     // handle common cases produced by branch lowering.
2379     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2380         CB.CC == ISD::SETEQ)
2381       Cond = CondLHS;
2382     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2383              CB.CC == ISD::SETEQ) {
2384       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2385       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2386     } else {
2387       SDValue CondRHS = getValue(CB.CmpRHS);
2388 
2389       // If a pointer's DAG type is larger than its memory type then the DAG
2390       // values are zero-extended. This breaks signed comparisons so truncate
2391       // back to the underlying type before doing the compare.
2392       if (CondLHS.getValueType() != MemVT) {
2393         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2394         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2395       }
2396       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2397     }
2398   } else {
2399     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2400 
2401     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2402     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2403 
2404     SDValue CmpOp = getValue(CB.CmpMHS);
2405     EVT VT = CmpOp.getValueType();
2406 
2407     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2408       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2409                           ISD::SETLE);
2410     } else {
2411       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2412                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2413       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2414                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2415     }
2416   }
2417 
2418   // Update successor info
2419   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2420   // TrueBB and FalseBB are always different unless the incoming IR is
2421   // degenerate. This only happens when running llc on weird IR.
2422   if (CB.TrueBB != CB.FalseBB)
2423     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2424   SwitchBB->normalizeSuccProbs();
2425 
2426   // If the lhs block is the next block, invert the condition so that we can
2427   // fall through to the lhs instead of the rhs block.
2428   if (CB.TrueBB == NextBlock(SwitchBB)) {
2429     std::swap(CB.TrueBB, CB.FalseBB);
2430     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2431     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2432   }
2433 
2434   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2435                                MVT::Other, getControlRoot(), Cond,
2436                                DAG.getBasicBlock(CB.TrueBB));
2437 
2438   // Insert the false branch. Do this even if it's a fall through branch,
2439   // this makes it easier to do DAG optimizations which require inverting
2440   // the branch condition.
2441   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2442                        DAG.getBasicBlock(CB.FalseBB));
2443 
2444   DAG.setRoot(BrCond);
2445 }
2446 
2447 /// visitJumpTable - Emit JumpTable node in the current MBB
2448 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2449   // Emit the code for the jump table
2450   assert(JT.Reg != -1U && "Should lower JT Header first!");
2451   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2452   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2453                                      JT.Reg, PTy);
2454   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2455   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2456                                     MVT::Other, Index.getValue(1),
2457                                     Table, Index);
2458   DAG.setRoot(BrJumpTable);
2459 }
2460 
2461 /// visitJumpTableHeader - This function emits necessary code to produce index
2462 /// in the JumpTable from switch case.
2463 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2464                                                JumpTableHeader &JTH,
2465                                                MachineBasicBlock *SwitchBB) {
2466   SDLoc dl = getCurSDLoc();
2467 
2468   // Subtract the lowest switch case value from the value being switched on.
2469   SDValue SwitchOp = getValue(JTH.SValue);
2470   EVT VT = SwitchOp.getValueType();
2471   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2472                             DAG.getConstant(JTH.First, dl, VT));
2473 
2474   // The SDNode we just created, which holds the value being switched on minus
2475   // the smallest case value, needs to be copied to a virtual register so it
2476   // can be used as an index into the jump table in a subsequent basic block.
2477   // This value may be smaller or larger than the target's pointer type, and
2478   // therefore require extension or truncating.
2479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2480   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2481 
2482   unsigned JumpTableReg =
2483       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2484   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2485                                     JumpTableReg, SwitchOp);
2486   JT.Reg = JumpTableReg;
2487 
2488   if (!JTH.OmitRangeCheck) {
2489     // Emit the range check for the jump table, and branch to the default block
2490     // for the switch statement if the value being switched on exceeds the
2491     // largest case in the switch.
2492     SDValue CMP = DAG.getSetCC(
2493         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2494                                    Sub.getValueType()),
2495         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2496 
2497     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2498                                  MVT::Other, CopyTo, CMP,
2499                                  DAG.getBasicBlock(JT.Default));
2500 
2501     // Avoid emitting unnecessary branches to the next block.
2502     if (JT.MBB != NextBlock(SwitchBB))
2503       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2504                            DAG.getBasicBlock(JT.MBB));
2505 
2506     DAG.setRoot(BrCond);
2507   } else {
2508     // Avoid emitting unnecessary branches to the next block.
2509     if (JT.MBB != NextBlock(SwitchBB))
2510       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2511                               DAG.getBasicBlock(JT.MBB)));
2512     else
2513       DAG.setRoot(CopyTo);
2514   }
2515 }
2516 
2517 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2518 /// variable if there exists one.
2519 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2520                                  SDValue &Chain) {
2521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2522   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2523   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2524   MachineFunction &MF = DAG.getMachineFunction();
2525   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2526   MachineSDNode *Node =
2527       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2528   if (Global) {
2529     MachinePointerInfo MPInfo(Global);
2530     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2531                  MachineMemOperand::MODereferenceable;
2532     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2533         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2534     DAG.setNodeMemRefs(Node, {MemRef});
2535   }
2536   if (PtrTy != PtrMemTy)
2537     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2538   return SDValue(Node, 0);
2539 }
2540 
2541 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2542 /// tail spliced into a stack protector check success bb.
2543 ///
2544 /// For a high level explanation of how this fits into the stack protector
2545 /// generation see the comment on the declaration of class
2546 /// StackProtectorDescriptor.
2547 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2548                                                   MachineBasicBlock *ParentBB) {
2549 
2550   // First create the loads to the guard/stack slot for the comparison.
2551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2552   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2553   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2554 
2555   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2556   int FI = MFI.getStackProtectorIndex();
2557 
2558   SDValue Guard;
2559   SDLoc dl = getCurSDLoc();
2560   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2561   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2562   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2563 
2564   // Generate code to load the content of the guard slot.
2565   SDValue GuardVal = DAG.getLoad(
2566       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2567       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2568       MachineMemOperand::MOVolatile);
2569 
2570   if (TLI.useStackGuardXorFP())
2571     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2572 
2573   // Retrieve guard check function, nullptr if instrumentation is inlined.
2574   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2575     // The target provides a guard check function to validate the guard value.
2576     // Generate a call to that function with the content of the guard slot as
2577     // argument.
2578     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2579     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2580 
2581     TargetLowering::ArgListTy Args;
2582     TargetLowering::ArgListEntry Entry;
2583     Entry.Node = GuardVal;
2584     Entry.Ty = FnTy->getParamType(0);
2585     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2586       Entry.IsInReg = true;
2587     Args.push_back(Entry);
2588 
2589     TargetLowering::CallLoweringInfo CLI(DAG);
2590     CLI.setDebugLoc(getCurSDLoc())
2591         .setChain(DAG.getEntryNode())
2592         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2593                    getValue(GuardCheckFn), std::move(Args));
2594 
2595     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2596     DAG.setRoot(Result.second);
2597     return;
2598   }
2599 
2600   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2601   // Otherwise, emit a volatile load to retrieve the stack guard value.
2602   SDValue Chain = DAG.getEntryNode();
2603   if (TLI.useLoadStackGuardNode()) {
2604     Guard = getLoadStackGuard(DAG, dl, Chain);
2605   } else {
2606     const Value *IRGuard = TLI.getSDagStackGuard(M);
2607     SDValue GuardPtr = getValue(IRGuard);
2608 
2609     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2610                         MachinePointerInfo(IRGuard, 0), Align,
2611                         MachineMemOperand::MOVolatile);
2612   }
2613 
2614   // Perform the comparison via a getsetcc.
2615   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2616                                                         *DAG.getContext(),
2617                                                         Guard.getValueType()),
2618                              Guard, GuardVal, ISD::SETNE);
2619 
2620   // If the guard/stackslot do not equal, branch to failure MBB.
2621   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2622                                MVT::Other, GuardVal.getOperand(0),
2623                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2624   // Otherwise branch to success MBB.
2625   SDValue Br = DAG.getNode(ISD::BR, dl,
2626                            MVT::Other, BrCond,
2627                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2628 
2629   DAG.setRoot(Br);
2630 }
2631 
2632 /// Codegen the failure basic block for a stack protector check.
2633 ///
2634 /// A failure stack protector machine basic block consists simply of a call to
2635 /// __stack_chk_fail().
2636 ///
2637 /// For a high level explanation of how this fits into the stack protector
2638 /// generation see the comment on the declaration of class
2639 /// StackProtectorDescriptor.
2640 void
2641 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2643   TargetLowering::MakeLibCallOptions CallOptions;
2644   CallOptions.setDiscardResult(true);
2645   SDValue Chain =
2646       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2647                       None, CallOptions, getCurSDLoc()).second;
2648   // On PS4, the "return address" must still be within the calling function,
2649   // even if it's at the very end, so emit an explicit TRAP here.
2650   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2651   if (TM.getTargetTriple().isPS4CPU())
2652     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2653 
2654   DAG.setRoot(Chain);
2655 }
2656 
2657 /// visitBitTestHeader - This function emits necessary code to produce value
2658 /// suitable for "bit tests"
2659 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2660                                              MachineBasicBlock *SwitchBB) {
2661   SDLoc dl = getCurSDLoc();
2662 
2663   // Subtract the minimum value.
2664   SDValue SwitchOp = getValue(B.SValue);
2665   EVT VT = SwitchOp.getValueType();
2666   SDValue RangeSub =
2667       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2668 
2669   // Determine the type of the test operands.
2670   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2671   bool UsePtrType = false;
2672   if (!TLI.isTypeLegal(VT)) {
2673     UsePtrType = true;
2674   } else {
2675     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2676       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2677         // Switch table case range are encoded into series of masks.
2678         // Just use pointer type, it's guaranteed to fit.
2679         UsePtrType = true;
2680         break;
2681       }
2682   }
2683   SDValue Sub = RangeSub;
2684   if (UsePtrType) {
2685     VT = TLI.getPointerTy(DAG.getDataLayout());
2686     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2687   }
2688 
2689   B.RegVT = VT.getSimpleVT();
2690   B.Reg = FuncInfo.CreateReg(B.RegVT);
2691   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2692 
2693   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2694 
2695   if (!B.OmitRangeCheck)
2696     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2697   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2698   SwitchBB->normalizeSuccProbs();
2699 
2700   SDValue Root = CopyTo;
2701   if (!B.OmitRangeCheck) {
2702     // Conditional branch to the default block.
2703     SDValue RangeCmp = DAG.getSetCC(dl,
2704         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2705                                RangeSub.getValueType()),
2706         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2707         ISD::SETUGT);
2708 
2709     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2710                        DAG.getBasicBlock(B.Default));
2711   }
2712 
2713   // Avoid emitting unnecessary branches to the next block.
2714   if (MBB != NextBlock(SwitchBB))
2715     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2716 
2717   DAG.setRoot(Root);
2718 }
2719 
2720 /// visitBitTestCase - this function produces one "bit test"
2721 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2722                                            MachineBasicBlock* NextMBB,
2723                                            BranchProbability BranchProbToNext,
2724                                            unsigned Reg,
2725                                            BitTestCase &B,
2726                                            MachineBasicBlock *SwitchBB) {
2727   SDLoc dl = getCurSDLoc();
2728   MVT VT = BB.RegVT;
2729   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2730   SDValue Cmp;
2731   unsigned PopCount = countPopulation(B.Mask);
2732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2733   if (PopCount == 1) {
2734     // Testing for a single bit; just compare the shift count with what it
2735     // would need to be to shift a 1 bit in that position.
2736     Cmp = DAG.getSetCC(
2737         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2738         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2739         ISD::SETEQ);
2740   } else if (PopCount == BB.Range) {
2741     // There is only one zero bit in the range, test for it directly.
2742     Cmp = DAG.getSetCC(
2743         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2744         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2745         ISD::SETNE);
2746   } else {
2747     // Make desired shift
2748     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2749                                     DAG.getConstant(1, dl, VT), ShiftOp);
2750 
2751     // Emit bit tests and jumps
2752     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2753                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2754     Cmp = DAG.getSetCC(
2755         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2756         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2757   }
2758 
2759   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2760   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2761   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2762   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2763   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2764   // one as they are relative probabilities (and thus work more like weights),
2765   // and hence we need to normalize them to let the sum of them become one.
2766   SwitchBB->normalizeSuccProbs();
2767 
2768   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2769                               MVT::Other, getControlRoot(),
2770                               Cmp, DAG.getBasicBlock(B.TargetBB));
2771 
2772   // Avoid emitting unnecessary branches to the next block.
2773   if (NextMBB != NextBlock(SwitchBB))
2774     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2775                         DAG.getBasicBlock(NextMBB));
2776 
2777   DAG.setRoot(BrAnd);
2778 }
2779 
2780 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2781   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2782 
2783   // Retrieve successors. Look through artificial IR level blocks like
2784   // catchswitch for successors.
2785   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2786   const BasicBlock *EHPadBB = I.getSuccessor(1);
2787 
2788   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2789   // have to do anything here to lower funclet bundles.
2790   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2791                                         LLVMContext::OB_gc_transition,
2792                                         LLVMContext::OB_gc_live,
2793                                         LLVMContext::OB_funclet,
2794                                         LLVMContext::OB_cfguardtarget}) &&
2795          "Cannot lower invokes with arbitrary operand bundles yet!");
2796 
2797   const Value *Callee(I.getCalledOperand());
2798   const Function *Fn = dyn_cast<Function>(Callee);
2799   if (isa<InlineAsm>(Callee))
2800     visitInlineAsm(I);
2801   else if (Fn && Fn->isIntrinsic()) {
2802     switch (Fn->getIntrinsicID()) {
2803     default:
2804       llvm_unreachable("Cannot invoke this intrinsic");
2805     case Intrinsic::donothing:
2806       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2807       break;
2808     case Intrinsic::experimental_patchpoint_void:
2809     case Intrinsic::experimental_patchpoint_i64:
2810       visitPatchpoint(I, EHPadBB);
2811       break;
2812     case Intrinsic::experimental_gc_statepoint:
2813       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2814       break;
2815     case Intrinsic::wasm_rethrow_in_catch: {
2816       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2817       // special because it can be invoked, so we manually lower it to a DAG
2818       // node here.
2819       SmallVector<SDValue, 8> Ops;
2820       Ops.push_back(getRoot()); // inchain
2821       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2822       Ops.push_back(
2823           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2824                                 TLI.getPointerTy(DAG.getDataLayout())));
2825       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2826       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2827       break;
2828     }
2829     }
2830   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2831     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2832     // Eventually we will support lowering the @llvm.experimental.deoptimize
2833     // intrinsic, and right now there are no plans to support other intrinsics
2834     // with deopt state.
2835     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2836   } else {
2837     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2838   }
2839 
2840   // If the value of the invoke is used outside of its defining block, make it
2841   // available as a virtual register.
2842   // We already took care of the exported value for the statepoint instruction
2843   // during call to the LowerStatepoint.
2844   if (!isa<GCStatepointInst>(I)) {
2845     CopyToExportRegsIfNeeded(&I);
2846   }
2847 
2848   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2849   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2850   BranchProbability EHPadBBProb =
2851       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2852           : BranchProbability::getZero();
2853   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2854 
2855   // Update successor info.
2856   addSuccessorWithProb(InvokeMBB, Return);
2857   for (auto &UnwindDest : UnwindDests) {
2858     UnwindDest.first->setIsEHPad();
2859     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2860   }
2861   InvokeMBB->normalizeSuccProbs();
2862 
2863   // Drop into normal successor.
2864   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2865                           DAG.getBasicBlock(Return)));
2866 }
2867 
2868 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2869   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2870 
2871   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2872   // have to do anything here to lower funclet bundles.
2873   assert(!I.hasOperandBundlesOtherThan(
2874              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2875          "Cannot lower callbrs with arbitrary operand bundles yet!");
2876 
2877   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2878   visitInlineAsm(I);
2879   CopyToExportRegsIfNeeded(&I);
2880 
2881   // Retrieve successors.
2882   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2883   Return->setInlineAsmBrDefaultTarget();
2884 
2885   // Update successor info.
2886   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2887   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2888     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2889     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2890     CallBrMBB->addInlineAsmBrIndirectTarget(Target);
2891   }
2892   CallBrMBB->normalizeSuccProbs();
2893 
2894   // Drop into default successor.
2895   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2896                           MVT::Other, getControlRoot(),
2897                           DAG.getBasicBlock(Return)));
2898 }
2899 
2900 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2901   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2902 }
2903 
2904 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2905   assert(FuncInfo.MBB->isEHPad() &&
2906          "Call to landingpad not in landing pad!");
2907 
2908   // If there aren't registers to copy the values into (e.g., during SjLj
2909   // exceptions), then don't bother to create these DAG nodes.
2910   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2911   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2912   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2913       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2914     return;
2915 
2916   // If landingpad's return type is token type, we don't create DAG nodes
2917   // for its exception pointer and selector value. The extraction of exception
2918   // pointer or selector value from token type landingpads is not currently
2919   // supported.
2920   if (LP.getType()->isTokenTy())
2921     return;
2922 
2923   SmallVector<EVT, 2> ValueVTs;
2924   SDLoc dl = getCurSDLoc();
2925   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2926   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2927 
2928   // Get the two live-in registers as SDValues. The physregs have already been
2929   // copied into virtual registers.
2930   SDValue Ops[2];
2931   if (FuncInfo.ExceptionPointerVirtReg) {
2932     Ops[0] = DAG.getZExtOrTrunc(
2933         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2934                            FuncInfo.ExceptionPointerVirtReg,
2935                            TLI.getPointerTy(DAG.getDataLayout())),
2936         dl, ValueVTs[0]);
2937   } else {
2938     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2939   }
2940   Ops[1] = DAG.getZExtOrTrunc(
2941       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2942                          FuncInfo.ExceptionSelectorVirtReg,
2943                          TLI.getPointerTy(DAG.getDataLayout())),
2944       dl, ValueVTs[1]);
2945 
2946   // Merge into one.
2947   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2948                             DAG.getVTList(ValueVTs), Ops);
2949   setValue(&LP, Res);
2950 }
2951 
2952 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2953                                            MachineBasicBlock *Last) {
2954   // Update JTCases.
2955   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2956     if (SL->JTCases[i].first.HeaderBB == First)
2957       SL->JTCases[i].first.HeaderBB = Last;
2958 
2959   // Update BitTestCases.
2960   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2961     if (SL->BitTestCases[i].Parent == First)
2962       SL->BitTestCases[i].Parent = Last;
2963 
2964   // SelectionDAGISel::FinishBasicBlock will add PHI operands for the
2965   // successors of the fallthrough block. Here, we add PHI operands for the
2966   // successors of the INLINEASM_BR block itself.
2967   if (First->getFirstTerminator()->getOpcode() == TargetOpcode::INLINEASM_BR)
2968     for (std::pair<MachineInstr *, unsigned> &pair : FuncInfo.PHINodesToUpdate)
2969       if (First->isSuccessor(pair.first->getParent()))
2970         MachineInstrBuilder(*First->getParent(), pair.first)
2971             .addReg(pair.second)
2972             .addMBB(First);
2973 }
2974 
2975 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2976   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2977 
2978   // Update machine-CFG edges with unique successors.
2979   SmallSet<BasicBlock*, 32> Done;
2980   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2981     BasicBlock *BB = I.getSuccessor(i);
2982     bool Inserted = Done.insert(BB).second;
2983     if (!Inserted)
2984         continue;
2985 
2986     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2987     addSuccessorWithProb(IndirectBrMBB, Succ);
2988   }
2989   IndirectBrMBB->normalizeSuccProbs();
2990 
2991   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2992                           MVT::Other, getControlRoot(),
2993                           getValue(I.getAddress())));
2994 }
2995 
2996 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2997   if (!DAG.getTarget().Options.TrapUnreachable)
2998     return;
2999 
3000   // We may be able to ignore unreachable behind a noreturn call.
3001   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3002     const BasicBlock &BB = *I.getParent();
3003     if (&I != &BB.front()) {
3004       BasicBlock::const_iterator PredI =
3005         std::prev(BasicBlock::const_iterator(&I));
3006       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3007         if (Call->doesNotReturn())
3008           return;
3009       }
3010     }
3011   }
3012 
3013   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3014 }
3015 
3016 void SelectionDAGBuilder::visitFSub(const User &I) {
3017   // -0.0 - X --> fneg
3018   Type *Ty = I.getType();
3019   if (isa<Constant>(I.getOperand(0)) &&
3020       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
3021     SDValue Op2 = getValue(I.getOperand(1));
3022     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3023                              Op2.getValueType(), Op2));
3024     return;
3025   }
3026 
3027   visitBinary(I, ISD::FSUB);
3028 }
3029 
3030 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3031   SDNodeFlags Flags;
3032 
3033   SDValue Op = getValue(I.getOperand(0));
3034   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3035                                     Op, Flags);
3036   setValue(&I, UnNodeValue);
3037 }
3038 
3039 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3040   SDNodeFlags Flags;
3041   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3042     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3043     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3044   }
3045   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3046     Flags.setExact(ExactOp->isExact());
3047   }
3048 
3049   SDValue Op1 = getValue(I.getOperand(0));
3050   SDValue Op2 = getValue(I.getOperand(1));
3051   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3052                                      Op1, Op2, Flags);
3053   setValue(&I, BinNodeValue);
3054 }
3055 
3056 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3057   SDValue Op1 = getValue(I.getOperand(0));
3058   SDValue Op2 = getValue(I.getOperand(1));
3059 
3060   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3061       Op1.getValueType(), DAG.getDataLayout());
3062 
3063   // Coerce the shift amount to the right type if we can.
3064   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3065     unsigned ShiftSize = ShiftTy.getSizeInBits();
3066     unsigned Op2Size = Op2.getValueSizeInBits();
3067     SDLoc DL = getCurSDLoc();
3068 
3069     // If the operand is smaller than the shift count type, promote it.
3070     if (ShiftSize > Op2Size)
3071       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3072 
3073     // If the operand is larger than the shift count type but the shift
3074     // count type has enough bits to represent any shift value, truncate
3075     // it now. This is a common case and it exposes the truncate to
3076     // optimization early.
3077     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3078       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3079     // Otherwise we'll need to temporarily settle for some other convenient
3080     // type.  Type legalization will make adjustments once the shiftee is split.
3081     else
3082       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3083   }
3084 
3085   bool nuw = false;
3086   bool nsw = false;
3087   bool exact = false;
3088 
3089   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3090 
3091     if (const OverflowingBinaryOperator *OFBinOp =
3092             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3093       nuw = OFBinOp->hasNoUnsignedWrap();
3094       nsw = OFBinOp->hasNoSignedWrap();
3095     }
3096     if (const PossiblyExactOperator *ExactOp =
3097             dyn_cast<const PossiblyExactOperator>(&I))
3098       exact = ExactOp->isExact();
3099   }
3100   SDNodeFlags Flags;
3101   Flags.setExact(exact);
3102   Flags.setNoSignedWrap(nsw);
3103   Flags.setNoUnsignedWrap(nuw);
3104   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3105                             Flags);
3106   setValue(&I, Res);
3107 }
3108 
3109 void SelectionDAGBuilder::visitSDiv(const User &I) {
3110   SDValue Op1 = getValue(I.getOperand(0));
3111   SDValue Op2 = getValue(I.getOperand(1));
3112 
3113   SDNodeFlags Flags;
3114   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3115                  cast<PossiblyExactOperator>(&I)->isExact());
3116   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3117                            Op2, Flags));
3118 }
3119 
3120 void SelectionDAGBuilder::visitICmp(const User &I) {
3121   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3122   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3123     predicate = IC->getPredicate();
3124   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3125     predicate = ICmpInst::Predicate(IC->getPredicate());
3126   SDValue Op1 = getValue(I.getOperand(0));
3127   SDValue Op2 = getValue(I.getOperand(1));
3128   ISD::CondCode Opcode = getICmpCondCode(predicate);
3129 
3130   auto &TLI = DAG.getTargetLoweringInfo();
3131   EVT MemVT =
3132       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3133 
3134   // If a pointer's DAG type is larger than its memory type then the DAG values
3135   // are zero-extended. This breaks signed comparisons so truncate back to the
3136   // underlying type before doing the compare.
3137   if (Op1.getValueType() != MemVT) {
3138     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3139     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3140   }
3141 
3142   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3143                                                         I.getType());
3144   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3145 }
3146 
3147 void SelectionDAGBuilder::visitFCmp(const User &I) {
3148   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3149   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3150     predicate = FC->getPredicate();
3151   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3152     predicate = FCmpInst::Predicate(FC->getPredicate());
3153   SDValue Op1 = getValue(I.getOperand(0));
3154   SDValue Op2 = getValue(I.getOperand(1));
3155 
3156   ISD::CondCode Condition = getFCmpCondCode(predicate);
3157   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3158   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3159     Condition = getFCmpCodeWithoutNaN(Condition);
3160 
3161   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3162                                                         I.getType());
3163   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3164 }
3165 
3166 // Check if the condition of the select has one use or two users that are both
3167 // selects with the same condition.
3168 static bool hasOnlySelectUsers(const Value *Cond) {
3169   return llvm::all_of(Cond->users(), [](const Value *V) {
3170     return isa<SelectInst>(V);
3171   });
3172 }
3173 
3174 void SelectionDAGBuilder::visitSelect(const User &I) {
3175   SmallVector<EVT, 4> ValueVTs;
3176   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3177                   ValueVTs);
3178   unsigned NumValues = ValueVTs.size();
3179   if (NumValues == 0) return;
3180 
3181   SmallVector<SDValue, 4> Values(NumValues);
3182   SDValue Cond     = getValue(I.getOperand(0));
3183   SDValue LHSVal   = getValue(I.getOperand(1));
3184   SDValue RHSVal   = getValue(I.getOperand(2));
3185   SmallVector<SDValue, 1> BaseOps(1, Cond);
3186   ISD::NodeType OpCode =
3187       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3188 
3189   bool IsUnaryAbs = false;
3190 
3191   // Min/max matching is only viable if all output VTs are the same.
3192   if (is_splat(ValueVTs)) {
3193     EVT VT = ValueVTs[0];
3194     LLVMContext &Ctx = *DAG.getContext();
3195     auto &TLI = DAG.getTargetLoweringInfo();
3196 
3197     // We care about the legality of the operation after it has been type
3198     // legalized.
3199     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3200       VT = TLI.getTypeToTransformTo(Ctx, VT);
3201 
3202     // If the vselect is legal, assume we want to leave this as a vector setcc +
3203     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3204     // min/max is legal on the scalar type.
3205     bool UseScalarMinMax = VT.isVector() &&
3206       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3207 
3208     Value *LHS, *RHS;
3209     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3210     ISD::NodeType Opc = ISD::DELETED_NODE;
3211     switch (SPR.Flavor) {
3212     case SPF_UMAX:    Opc = ISD::UMAX; break;
3213     case SPF_UMIN:    Opc = ISD::UMIN; break;
3214     case SPF_SMAX:    Opc = ISD::SMAX; break;
3215     case SPF_SMIN:    Opc = ISD::SMIN; break;
3216     case SPF_FMINNUM:
3217       switch (SPR.NaNBehavior) {
3218       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3219       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3220       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3221       case SPNB_RETURNS_ANY: {
3222         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3223           Opc = ISD::FMINNUM;
3224         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3225           Opc = ISD::FMINIMUM;
3226         else if (UseScalarMinMax)
3227           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3228             ISD::FMINNUM : ISD::FMINIMUM;
3229         break;
3230       }
3231       }
3232       break;
3233     case SPF_FMAXNUM:
3234       switch (SPR.NaNBehavior) {
3235       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3236       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3237       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3238       case SPNB_RETURNS_ANY:
3239 
3240         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3241           Opc = ISD::FMAXNUM;
3242         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3243           Opc = ISD::FMAXIMUM;
3244         else if (UseScalarMinMax)
3245           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3246             ISD::FMAXNUM : ISD::FMAXIMUM;
3247         break;
3248       }
3249       break;
3250     case SPF_ABS:
3251       IsUnaryAbs = true;
3252       Opc = ISD::ABS;
3253       break;
3254     case SPF_NABS:
3255       // TODO: we need to produce sub(0, abs(X)).
3256     default: break;
3257     }
3258 
3259     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3260         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3261          (UseScalarMinMax &&
3262           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3263         // If the underlying comparison instruction is used by any other
3264         // instruction, the consumed instructions won't be destroyed, so it is
3265         // not profitable to convert to a min/max.
3266         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3267       OpCode = Opc;
3268       LHSVal = getValue(LHS);
3269       RHSVal = getValue(RHS);
3270       BaseOps.clear();
3271     }
3272 
3273     if (IsUnaryAbs) {
3274       OpCode = Opc;
3275       LHSVal = getValue(LHS);
3276       BaseOps.clear();
3277     }
3278   }
3279 
3280   if (IsUnaryAbs) {
3281     for (unsigned i = 0; i != NumValues; ++i) {
3282       Values[i] =
3283           DAG.getNode(OpCode, getCurSDLoc(),
3284                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3285                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3286     }
3287   } else {
3288     for (unsigned i = 0; i != NumValues; ++i) {
3289       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3290       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3291       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3292       Values[i] = DAG.getNode(
3293           OpCode, getCurSDLoc(),
3294           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3295     }
3296   }
3297 
3298   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3299                            DAG.getVTList(ValueVTs), Values));
3300 }
3301 
3302 void SelectionDAGBuilder::visitTrunc(const User &I) {
3303   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3304   SDValue N = getValue(I.getOperand(0));
3305   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3306                                                         I.getType());
3307   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3308 }
3309 
3310 void SelectionDAGBuilder::visitZExt(const User &I) {
3311   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3312   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3313   SDValue N = getValue(I.getOperand(0));
3314   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3315                                                         I.getType());
3316   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3317 }
3318 
3319 void SelectionDAGBuilder::visitSExt(const User &I) {
3320   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3321   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3322   SDValue N = getValue(I.getOperand(0));
3323   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3324                                                         I.getType());
3325   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3326 }
3327 
3328 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3329   // FPTrunc is never a no-op cast, no need to check
3330   SDValue N = getValue(I.getOperand(0));
3331   SDLoc dl = getCurSDLoc();
3332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3333   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3334   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3335                            DAG.getTargetConstant(
3336                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3337 }
3338 
3339 void SelectionDAGBuilder::visitFPExt(const User &I) {
3340   // FPExt is never a no-op cast, no need to check
3341   SDValue N = getValue(I.getOperand(0));
3342   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3343                                                         I.getType());
3344   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3345 }
3346 
3347 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3348   // FPToUI is never a no-op cast, no need to check
3349   SDValue N = getValue(I.getOperand(0));
3350   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3351                                                         I.getType());
3352   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3353 }
3354 
3355 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3356   // FPToSI is never a no-op cast, no need to check
3357   SDValue N = getValue(I.getOperand(0));
3358   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3359                                                         I.getType());
3360   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3361 }
3362 
3363 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3364   // UIToFP is never a no-op cast, no need to check
3365   SDValue N = getValue(I.getOperand(0));
3366   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3367                                                         I.getType());
3368   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3369 }
3370 
3371 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3372   // SIToFP is never a no-op cast, no need to check
3373   SDValue N = getValue(I.getOperand(0));
3374   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3375                                                         I.getType());
3376   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3377 }
3378 
3379 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3380   // What to do depends on the size of the integer and the size of the pointer.
3381   // We can either truncate, zero extend, or no-op, accordingly.
3382   SDValue N = getValue(I.getOperand(0));
3383   auto &TLI = DAG.getTargetLoweringInfo();
3384   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3385                                                         I.getType());
3386   EVT PtrMemVT =
3387       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3388   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3389   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3390   setValue(&I, N);
3391 }
3392 
3393 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3394   // What to do depends on the size of the integer and the size of the pointer.
3395   // We can either truncate, zero extend, or no-op, accordingly.
3396   SDValue N = getValue(I.getOperand(0));
3397   auto &TLI = DAG.getTargetLoweringInfo();
3398   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3399   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3400   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3401   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3402   setValue(&I, N);
3403 }
3404 
3405 void SelectionDAGBuilder::visitBitCast(const User &I) {
3406   SDValue N = getValue(I.getOperand(0));
3407   SDLoc dl = getCurSDLoc();
3408   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3409                                                         I.getType());
3410 
3411   // BitCast assures us that source and destination are the same size so this is
3412   // either a BITCAST or a no-op.
3413   if (DestVT != N.getValueType())
3414     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3415                              DestVT, N)); // convert types.
3416   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3417   // might fold any kind of constant expression to an integer constant and that
3418   // is not what we are looking for. Only recognize a bitcast of a genuine
3419   // constant integer as an opaque constant.
3420   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3421     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3422                                  /*isOpaque*/true));
3423   else
3424     setValue(&I, N);            // noop cast.
3425 }
3426 
3427 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3429   const Value *SV = I.getOperand(0);
3430   SDValue N = getValue(SV);
3431   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3432 
3433   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3434   unsigned DestAS = I.getType()->getPointerAddressSpace();
3435 
3436   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3437     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3438 
3439   setValue(&I, N);
3440 }
3441 
3442 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3444   SDValue InVec = getValue(I.getOperand(0));
3445   SDValue InVal = getValue(I.getOperand(1));
3446   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3447                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3448   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3449                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3450                            InVec, InVal, InIdx));
3451 }
3452 
3453 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3455   SDValue InVec = getValue(I.getOperand(0));
3456   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3457                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3458   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3459                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3460                            InVec, InIdx));
3461 }
3462 
3463 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3464   SDValue Src1 = getValue(I.getOperand(0));
3465   SDValue Src2 = getValue(I.getOperand(1));
3466   ArrayRef<int> Mask;
3467   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3468     Mask = SVI->getShuffleMask();
3469   else
3470     Mask = cast<ConstantExpr>(I).getShuffleMask();
3471   SDLoc DL = getCurSDLoc();
3472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3473   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3474   EVT SrcVT = Src1.getValueType();
3475 
3476   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3477       VT.isScalableVector()) {
3478     // Canonical splat form of first element of first input vector.
3479     SDValue FirstElt =
3480         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3481                     DAG.getVectorIdxConstant(0, DL));
3482     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3483     return;
3484   }
3485 
3486   // For now, we only handle splats for scalable vectors.
3487   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3488   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3489   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3490 
3491   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3492   unsigned MaskNumElts = Mask.size();
3493 
3494   if (SrcNumElts == MaskNumElts) {
3495     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3496     return;
3497   }
3498 
3499   // Normalize the shuffle vector since mask and vector length don't match.
3500   if (SrcNumElts < MaskNumElts) {
3501     // Mask is longer than the source vectors. We can use concatenate vector to
3502     // make the mask and vectors lengths match.
3503 
3504     if (MaskNumElts % SrcNumElts == 0) {
3505       // Mask length is a multiple of the source vector length.
3506       // Check if the shuffle is some kind of concatenation of the input
3507       // vectors.
3508       unsigned NumConcat = MaskNumElts / SrcNumElts;
3509       bool IsConcat = true;
3510       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3511       for (unsigned i = 0; i != MaskNumElts; ++i) {
3512         int Idx = Mask[i];
3513         if (Idx < 0)
3514           continue;
3515         // Ensure the indices in each SrcVT sized piece are sequential and that
3516         // the same source is used for the whole piece.
3517         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3518             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3519              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3520           IsConcat = false;
3521           break;
3522         }
3523         // Remember which source this index came from.
3524         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3525       }
3526 
3527       // The shuffle is concatenating multiple vectors together. Just emit
3528       // a CONCAT_VECTORS operation.
3529       if (IsConcat) {
3530         SmallVector<SDValue, 8> ConcatOps;
3531         for (auto Src : ConcatSrcs) {
3532           if (Src < 0)
3533             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3534           else if (Src == 0)
3535             ConcatOps.push_back(Src1);
3536           else
3537             ConcatOps.push_back(Src2);
3538         }
3539         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3540         return;
3541       }
3542     }
3543 
3544     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3545     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3546     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3547                                     PaddedMaskNumElts);
3548 
3549     // Pad both vectors with undefs to make them the same length as the mask.
3550     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3551 
3552     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3553     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3554     MOps1[0] = Src1;
3555     MOps2[0] = Src2;
3556 
3557     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3558     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3559 
3560     // Readjust mask for new input vector length.
3561     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3562     for (unsigned i = 0; i != MaskNumElts; ++i) {
3563       int Idx = Mask[i];
3564       if (Idx >= (int)SrcNumElts)
3565         Idx -= SrcNumElts - PaddedMaskNumElts;
3566       MappedOps[i] = Idx;
3567     }
3568 
3569     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3570 
3571     // If the concatenated vector was padded, extract a subvector with the
3572     // correct number of elements.
3573     if (MaskNumElts != PaddedMaskNumElts)
3574       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3575                            DAG.getVectorIdxConstant(0, DL));
3576 
3577     setValue(&I, Result);
3578     return;
3579   }
3580 
3581   if (SrcNumElts > MaskNumElts) {
3582     // Analyze the access pattern of the vector to see if we can extract
3583     // two subvectors and do the shuffle.
3584     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3585     bool CanExtract = true;
3586     for (int Idx : Mask) {
3587       unsigned Input = 0;
3588       if (Idx < 0)
3589         continue;
3590 
3591       if (Idx >= (int)SrcNumElts) {
3592         Input = 1;
3593         Idx -= SrcNumElts;
3594       }
3595 
3596       // If all the indices come from the same MaskNumElts sized portion of
3597       // the sources we can use extract. Also make sure the extract wouldn't
3598       // extract past the end of the source.
3599       int NewStartIdx = alignDown(Idx, MaskNumElts);
3600       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3601           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3602         CanExtract = false;
3603       // Make sure we always update StartIdx as we use it to track if all
3604       // elements are undef.
3605       StartIdx[Input] = NewStartIdx;
3606     }
3607 
3608     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3609       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3610       return;
3611     }
3612     if (CanExtract) {
3613       // Extract appropriate subvector and generate a vector shuffle
3614       for (unsigned Input = 0; Input < 2; ++Input) {
3615         SDValue &Src = Input == 0 ? Src1 : Src2;
3616         if (StartIdx[Input] < 0)
3617           Src = DAG.getUNDEF(VT);
3618         else {
3619           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3620                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3621         }
3622       }
3623 
3624       // Calculate new mask.
3625       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3626       for (int &Idx : MappedOps) {
3627         if (Idx >= (int)SrcNumElts)
3628           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3629         else if (Idx >= 0)
3630           Idx -= StartIdx[0];
3631       }
3632 
3633       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3634       return;
3635     }
3636   }
3637 
3638   // We can't use either concat vectors or extract subvectors so fall back to
3639   // replacing the shuffle with extract and build vector.
3640   // to insert and build vector.
3641   EVT EltVT = VT.getVectorElementType();
3642   SmallVector<SDValue,8> Ops;
3643   for (int Idx : Mask) {
3644     SDValue Res;
3645 
3646     if (Idx < 0) {
3647       Res = DAG.getUNDEF(EltVT);
3648     } else {
3649       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3650       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3651 
3652       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3653                         DAG.getVectorIdxConstant(Idx, DL));
3654     }
3655 
3656     Ops.push_back(Res);
3657   }
3658 
3659   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3660 }
3661 
3662 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3663   ArrayRef<unsigned> Indices;
3664   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3665     Indices = IV->getIndices();
3666   else
3667     Indices = cast<ConstantExpr>(&I)->getIndices();
3668 
3669   const Value *Op0 = I.getOperand(0);
3670   const Value *Op1 = I.getOperand(1);
3671   Type *AggTy = I.getType();
3672   Type *ValTy = Op1->getType();
3673   bool IntoUndef = isa<UndefValue>(Op0);
3674   bool FromUndef = isa<UndefValue>(Op1);
3675 
3676   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3677 
3678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3679   SmallVector<EVT, 4> AggValueVTs;
3680   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3681   SmallVector<EVT, 4> ValValueVTs;
3682   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3683 
3684   unsigned NumAggValues = AggValueVTs.size();
3685   unsigned NumValValues = ValValueVTs.size();
3686   SmallVector<SDValue, 4> Values(NumAggValues);
3687 
3688   // Ignore an insertvalue that produces an empty object
3689   if (!NumAggValues) {
3690     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3691     return;
3692   }
3693 
3694   SDValue Agg = getValue(Op0);
3695   unsigned i = 0;
3696   // Copy the beginning value(s) from the original aggregate.
3697   for (; i != LinearIndex; ++i)
3698     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3699                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3700   // Copy values from the inserted value(s).
3701   if (NumValValues) {
3702     SDValue Val = getValue(Op1);
3703     for (; i != LinearIndex + NumValValues; ++i)
3704       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3705                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3706   }
3707   // Copy remaining value(s) from the original aggregate.
3708   for (; i != NumAggValues; ++i)
3709     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3710                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3711 
3712   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3713                            DAG.getVTList(AggValueVTs), Values));
3714 }
3715 
3716 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3717   ArrayRef<unsigned> Indices;
3718   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3719     Indices = EV->getIndices();
3720   else
3721     Indices = cast<ConstantExpr>(&I)->getIndices();
3722 
3723   const Value *Op0 = I.getOperand(0);
3724   Type *AggTy = Op0->getType();
3725   Type *ValTy = I.getType();
3726   bool OutOfUndef = isa<UndefValue>(Op0);
3727 
3728   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3729 
3730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3731   SmallVector<EVT, 4> ValValueVTs;
3732   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3733 
3734   unsigned NumValValues = ValValueVTs.size();
3735 
3736   // Ignore a extractvalue that produces an empty object
3737   if (!NumValValues) {
3738     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3739     return;
3740   }
3741 
3742   SmallVector<SDValue, 4> Values(NumValValues);
3743 
3744   SDValue Agg = getValue(Op0);
3745   // Copy out the selected value(s).
3746   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3747     Values[i - LinearIndex] =
3748       OutOfUndef ?
3749         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3750         SDValue(Agg.getNode(), Agg.getResNo() + i);
3751 
3752   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3753                            DAG.getVTList(ValValueVTs), Values));
3754 }
3755 
3756 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3757   Value *Op0 = I.getOperand(0);
3758   // Note that the pointer operand may be a vector of pointers. Take the scalar
3759   // element which holds a pointer.
3760   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3761   SDValue N = getValue(Op0);
3762   SDLoc dl = getCurSDLoc();
3763   auto &TLI = DAG.getTargetLoweringInfo();
3764   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3765   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3766 
3767   // Normalize Vector GEP - all scalar operands should be converted to the
3768   // splat vector.
3769   bool IsVectorGEP = I.getType()->isVectorTy();
3770   ElementCount VectorElementCount =
3771       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3772                   : ElementCount(0, false);
3773 
3774   if (IsVectorGEP && !N.getValueType().isVector()) {
3775     LLVMContext &Context = *DAG.getContext();
3776     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3777     if (VectorElementCount.Scalable)
3778       N = DAG.getSplatVector(VT, dl, N);
3779     else
3780       N = DAG.getSplatBuildVector(VT, dl, N);
3781   }
3782 
3783   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3784        GTI != E; ++GTI) {
3785     const Value *Idx = GTI.getOperand();
3786     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3787       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3788       if (Field) {
3789         // N = N + Offset
3790         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3791 
3792         // In an inbounds GEP with an offset that is nonnegative even when
3793         // interpreted as signed, assume there is no unsigned overflow.
3794         SDNodeFlags Flags;
3795         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3796           Flags.setNoUnsignedWrap(true);
3797 
3798         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3799                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3800       }
3801     } else {
3802       // IdxSize is the width of the arithmetic according to IR semantics.
3803       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3804       // (and fix up the result later).
3805       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3806       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3807       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3808       // We intentionally mask away the high bits here; ElementSize may not
3809       // fit in IdxTy.
3810       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3811       bool ElementScalable = ElementSize.isScalable();
3812 
3813       // If this is a scalar constant or a splat vector of constants,
3814       // handle it quickly.
3815       const auto *C = dyn_cast<Constant>(Idx);
3816       if (C && isa<VectorType>(C->getType()))
3817         C = C->getSplatValue();
3818 
3819       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3820       if (CI && CI->isZero())
3821         continue;
3822       if (CI && !ElementScalable) {
3823         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3824         LLVMContext &Context = *DAG.getContext();
3825         SDValue OffsVal;
3826         if (IsVectorGEP)
3827           OffsVal = DAG.getConstant(
3828               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3829         else
3830           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3831 
3832         // In an inbounds GEP with an offset that is nonnegative even when
3833         // interpreted as signed, assume there is no unsigned overflow.
3834         SDNodeFlags Flags;
3835         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3836           Flags.setNoUnsignedWrap(true);
3837 
3838         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3839 
3840         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3841         continue;
3842       }
3843 
3844       // N = N + Idx * ElementMul;
3845       SDValue IdxN = getValue(Idx);
3846 
3847       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3848         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3849                                   VectorElementCount);
3850         if (VectorElementCount.Scalable)
3851           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3852         else
3853           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3854       }
3855 
3856       // If the index is smaller or larger than intptr_t, truncate or extend
3857       // it.
3858       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3859 
3860       if (ElementScalable) {
3861         EVT VScaleTy = N.getValueType().getScalarType();
3862         SDValue VScale = DAG.getNode(
3863             ISD::VSCALE, dl, VScaleTy,
3864             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3865         if (IsVectorGEP)
3866           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3867         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3868       } else {
3869         // If this is a multiply by a power of two, turn it into a shl
3870         // immediately.  This is a very common case.
3871         if (ElementMul != 1) {
3872           if (ElementMul.isPowerOf2()) {
3873             unsigned Amt = ElementMul.logBase2();
3874             IdxN = DAG.getNode(ISD::SHL, dl,
3875                                N.getValueType(), IdxN,
3876                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3877           } else {
3878             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3879                                             IdxN.getValueType());
3880             IdxN = DAG.getNode(ISD::MUL, dl,
3881                                N.getValueType(), IdxN, Scale);
3882           }
3883         }
3884       }
3885 
3886       N = DAG.getNode(ISD::ADD, dl,
3887                       N.getValueType(), N, IdxN);
3888     }
3889   }
3890 
3891   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3892     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3893 
3894   setValue(&I, N);
3895 }
3896 
3897 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3898   // If this is a fixed sized alloca in the entry block of the function,
3899   // allocate it statically on the stack.
3900   if (FuncInfo.StaticAllocaMap.count(&I))
3901     return;   // getValue will auto-populate this.
3902 
3903   SDLoc dl = getCurSDLoc();
3904   Type *Ty = I.getAllocatedType();
3905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3906   auto &DL = DAG.getDataLayout();
3907   uint64_t TySize = DL.getTypeAllocSize(Ty);
3908   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3909 
3910   SDValue AllocSize = getValue(I.getArraySize());
3911 
3912   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3913   if (AllocSize.getValueType() != IntPtr)
3914     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3915 
3916   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3917                           AllocSize,
3918                           DAG.getConstant(TySize, dl, IntPtr));
3919 
3920   // Handle alignment.  If the requested alignment is less than or equal to
3921   // the stack alignment, ignore it.  If the size is greater than or equal to
3922   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3923   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3924   if (*Alignment <= StackAlign)
3925     Alignment = None;
3926 
3927   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3928   // Round the size of the allocation up to the stack alignment size
3929   // by add SA-1 to the size. This doesn't overflow because we're computing
3930   // an address inside an alloca.
3931   SDNodeFlags Flags;
3932   Flags.setNoUnsignedWrap(true);
3933   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3934                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3935 
3936   // Mask out the low bits for alignment purposes.
3937   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3938                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3939 
3940   SDValue Ops[] = {
3941       getRoot(), AllocSize,
3942       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3943   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3944   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3945   setValue(&I, DSA);
3946   DAG.setRoot(DSA.getValue(1));
3947 
3948   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3949 }
3950 
3951 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3952   if (I.isAtomic())
3953     return visitAtomicLoad(I);
3954 
3955   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3956   const Value *SV = I.getOperand(0);
3957   if (TLI.supportSwiftError()) {
3958     // Swifterror values can come from either a function parameter with
3959     // swifterror attribute or an alloca with swifterror attribute.
3960     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3961       if (Arg->hasSwiftErrorAttr())
3962         return visitLoadFromSwiftError(I);
3963     }
3964 
3965     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3966       if (Alloca->isSwiftError())
3967         return visitLoadFromSwiftError(I);
3968     }
3969   }
3970 
3971   SDValue Ptr = getValue(SV);
3972 
3973   Type *Ty = I.getType();
3974   Align Alignment = I.getAlign();
3975 
3976   AAMDNodes AAInfo;
3977   I.getAAMetadata(AAInfo);
3978   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3979 
3980   SmallVector<EVT, 4> ValueVTs, MemVTs;
3981   SmallVector<uint64_t, 4> Offsets;
3982   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3983   unsigned NumValues = ValueVTs.size();
3984   if (NumValues == 0)
3985     return;
3986 
3987   bool isVolatile = I.isVolatile();
3988 
3989   SDValue Root;
3990   bool ConstantMemory = false;
3991   if (isVolatile)
3992     // Serialize volatile loads with other side effects.
3993     Root = getRoot();
3994   else if (NumValues > MaxParallelChains)
3995     Root = getMemoryRoot();
3996   else if (AA &&
3997            AA->pointsToConstantMemory(MemoryLocation(
3998                SV,
3999                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4000                AAInfo))) {
4001     // Do not serialize (non-volatile) loads of constant memory with anything.
4002     Root = DAG.getEntryNode();
4003     ConstantMemory = true;
4004   } else {
4005     // Do not serialize non-volatile loads against each other.
4006     Root = DAG.getRoot();
4007   }
4008 
4009   SDLoc dl = getCurSDLoc();
4010 
4011   if (isVolatile)
4012     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4013 
4014   // An aggregate load cannot wrap around the address space, so offsets to its
4015   // parts don't wrap either.
4016   SDNodeFlags Flags;
4017   Flags.setNoUnsignedWrap(true);
4018 
4019   SmallVector<SDValue, 4> Values(NumValues);
4020   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4021   EVT PtrVT = Ptr.getValueType();
4022 
4023   MachineMemOperand::Flags MMOFlags
4024     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4025 
4026   unsigned ChainI = 0;
4027   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4028     // Serializing loads here may result in excessive register pressure, and
4029     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4030     // could recover a bit by hoisting nodes upward in the chain by recognizing
4031     // they are side-effect free or do not alias. The optimizer should really
4032     // avoid this case by converting large object/array copies to llvm.memcpy
4033     // (MaxParallelChains should always remain as failsafe).
4034     if (ChainI == MaxParallelChains) {
4035       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4036       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4037                                   makeArrayRef(Chains.data(), ChainI));
4038       Root = Chain;
4039       ChainI = 0;
4040     }
4041     SDValue A = DAG.getNode(ISD::ADD, dl,
4042                             PtrVT, Ptr,
4043                             DAG.getConstant(Offsets[i], dl, PtrVT),
4044                             Flags);
4045 
4046     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4047                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4048                             MMOFlags, AAInfo, Ranges);
4049     Chains[ChainI] = L.getValue(1);
4050 
4051     if (MemVTs[i] != ValueVTs[i])
4052       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4053 
4054     Values[i] = L;
4055   }
4056 
4057   if (!ConstantMemory) {
4058     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4059                                 makeArrayRef(Chains.data(), ChainI));
4060     if (isVolatile)
4061       DAG.setRoot(Chain);
4062     else
4063       PendingLoads.push_back(Chain);
4064   }
4065 
4066   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4067                            DAG.getVTList(ValueVTs), Values));
4068 }
4069 
4070 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4071   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4072          "call visitStoreToSwiftError when backend supports swifterror");
4073 
4074   SmallVector<EVT, 4> ValueVTs;
4075   SmallVector<uint64_t, 4> Offsets;
4076   const Value *SrcV = I.getOperand(0);
4077   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4078                   SrcV->getType(), ValueVTs, &Offsets);
4079   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4080          "expect a single EVT for swifterror");
4081 
4082   SDValue Src = getValue(SrcV);
4083   // Create a virtual register, then update the virtual register.
4084   Register VReg =
4085       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4086   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4087   // Chain can be getRoot or getControlRoot.
4088   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4089                                       SDValue(Src.getNode(), Src.getResNo()));
4090   DAG.setRoot(CopyNode);
4091 }
4092 
4093 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4094   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4095          "call visitLoadFromSwiftError when backend supports swifterror");
4096 
4097   assert(!I.isVolatile() &&
4098          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4099          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4100          "Support volatile, non temporal, invariant for load_from_swift_error");
4101 
4102   const Value *SV = I.getOperand(0);
4103   Type *Ty = I.getType();
4104   AAMDNodes AAInfo;
4105   I.getAAMetadata(AAInfo);
4106   assert(
4107       (!AA ||
4108        !AA->pointsToConstantMemory(MemoryLocation(
4109            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4110            AAInfo))) &&
4111       "load_from_swift_error should not be constant memory");
4112 
4113   SmallVector<EVT, 4> ValueVTs;
4114   SmallVector<uint64_t, 4> Offsets;
4115   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4116                   ValueVTs, &Offsets);
4117   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4118          "expect a single EVT for swifterror");
4119 
4120   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4121   SDValue L = DAG.getCopyFromReg(
4122       getRoot(), getCurSDLoc(),
4123       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4124 
4125   setValue(&I, L);
4126 }
4127 
4128 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4129   if (I.isAtomic())
4130     return visitAtomicStore(I);
4131 
4132   const Value *SrcV = I.getOperand(0);
4133   const Value *PtrV = I.getOperand(1);
4134 
4135   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4136   if (TLI.supportSwiftError()) {
4137     // Swifterror values can come from either a function parameter with
4138     // swifterror attribute or an alloca with swifterror attribute.
4139     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4140       if (Arg->hasSwiftErrorAttr())
4141         return visitStoreToSwiftError(I);
4142     }
4143 
4144     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4145       if (Alloca->isSwiftError())
4146         return visitStoreToSwiftError(I);
4147     }
4148   }
4149 
4150   SmallVector<EVT, 4> ValueVTs, MemVTs;
4151   SmallVector<uint64_t, 4> Offsets;
4152   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4153                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4154   unsigned NumValues = ValueVTs.size();
4155   if (NumValues == 0)
4156     return;
4157 
4158   // Get the lowered operands. Note that we do this after
4159   // checking if NumResults is zero, because with zero results
4160   // the operands won't have values in the map.
4161   SDValue Src = getValue(SrcV);
4162   SDValue Ptr = getValue(PtrV);
4163 
4164   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4165   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4166   SDLoc dl = getCurSDLoc();
4167   Align Alignment = I.getAlign();
4168   AAMDNodes AAInfo;
4169   I.getAAMetadata(AAInfo);
4170 
4171   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4172 
4173   // An aggregate load cannot wrap around the address space, so offsets to its
4174   // parts don't wrap either.
4175   SDNodeFlags Flags;
4176   Flags.setNoUnsignedWrap(true);
4177 
4178   unsigned ChainI = 0;
4179   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4180     // See visitLoad comments.
4181     if (ChainI == MaxParallelChains) {
4182       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4183                                   makeArrayRef(Chains.data(), ChainI));
4184       Root = Chain;
4185       ChainI = 0;
4186     }
4187     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4188     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4189     if (MemVTs[i] != ValueVTs[i])
4190       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4191     SDValue St =
4192         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4193                      Alignment, MMOFlags, AAInfo);
4194     Chains[ChainI] = St;
4195   }
4196 
4197   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4198                                   makeArrayRef(Chains.data(), ChainI));
4199   DAG.setRoot(StoreNode);
4200 }
4201 
4202 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4203                                            bool IsCompressing) {
4204   SDLoc sdl = getCurSDLoc();
4205 
4206   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4207                                MaybeAlign &Alignment) {
4208     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4209     Src0 = I.getArgOperand(0);
4210     Ptr = I.getArgOperand(1);
4211     Alignment =
4212         MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4213     Mask = I.getArgOperand(3);
4214   };
4215   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4216                                     MaybeAlign &Alignment) {
4217     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4218     Src0 = I.getArgOperand(0);
4219     Ptr = I.getArgOperand(1);
4220     Mask = I.getArgOperand(2);
4221     Alignment = None;
4222   };
4223 
4224   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4225   MaybeAlign Alignment;
4226   if (IsCompressing)
4227     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4228   else
4229     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4230 
4231   SDValue Ptr = getValue(PtrOperand);
4232   SDValue Src0 = getValue(Src0Operand);
4233   SDValue Mask = getValue(MaskOperand);
4234   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4235 
4236   EVT VT = Src0.getValueType();
4237   if (!Alignment)
4238     Alignment = DAG.getEVTAlign(VT);
4239 
4240   AAMDNodes AAInfo;
4241   I.getAAMetadata(AAInfo);
4242 
4243   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4244       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4245       // TODO: Make MachineMemOperands aware of scalable
4246       // vectors.
4247       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4248   SDValue StoreNode =
4249       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4250                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4251   DAG.setRoot(StoreNode);
4252   setValue(&I, StoreNode);
4253 }
4254 
4255 // Get a uniform base for the Gather/Scatter intrinsic.
4256 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4257 // We try to represent it as a base pointer + vector of indices.
4258 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4259 // The first operand of the GEP may be a single pointer or a vector of pointers
4260 // Example:
4261 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4262 //  or
4263 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4264 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4265 //
4266 // When the first GEP operand is a single pointer - it is the uniform base we
4267 // are looking for. If first operand of the GEP is a splat vector - we
4268 // extract the splat value and use it as a uniform base.
4269 // In all other cases the function returns 'false'.
4270 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4271                            ISD::MemIndexType &IndexType, SDValue &Scale,
4272                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4273   SelectionDAG& DAG = SDB->DAG;
4274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4275   const DataLayout &DL = DAG.getDataLayout();
4276 
4277   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4278 
4279   // Handle splat constant pointer.
4280   if (auto *C = dyn_cast<Constant>(Ptr)) {
4281     C = C->getSplatValue();
4282     if (!C)
4283       return false;
4284 
4285     Base = SDB->getValue(C);
4286 
4287     unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements();
4288     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4289     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4290     IndexType = ISD::SIGNED_SCALED;
4291     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4292     return true;
4293   }
4294 
4295   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4296   if (!GEP || GEP->getParent() != CurBB)
4297     return false;
4298 
4299   if (GEP->getNumOperands() != 2)
4300     return false;
4301 
4302   const Value *BasePtr = GEP->getPointerOperand();
4303   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4304 
4305   // Make sure the base is scalar and the index is a vector.
4306   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4307     return false;
4308 
4309   Base = SDB->getValue(BasePtr);
4310   Index = SDB->getValue(IndexVal);
4311   IndexType = ISD::SIGNED_SCALED;
4312   Scale = DAG.getTargetConstant(
4313               DL.getTypeAllocSize(GEP->getResultElementType()),
4314               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4315   return true;
4316 }
4317 
4318 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4319   SDLoc sdl = getCurSDLoc();
4320 
4321   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4322   const Value *Ptr = I.getArgOperand(1);
4323   SDValue Src0 = getValue(I.getArgOperand(0));
4324   SDValue Mask = getValue(I.getArgOperand(3));
4325   EVT VT = Src0.getValueType();
4326   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4327   if (!Alignment)
4328     Alignment = DAG.getEVTAlign(VT);
4329   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4330 
4331   AAMDNodes AAInfo;
4332   I.getAAMetadata(AAInfo);
4333 
4334   SDValue Base;
4335   SDValue Index;
4336   ISD::MemIndexType IndexType;
4337   SDValue Scale;
4338   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4339                                     I.getParent());
4340 
4341   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4342   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4343       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4344       // TODO: Make MachineMemOperands aware of scalable
4345       // vectors.
4346       MemoryLocation::UnknownSize, *Alignment, AAInfo);
4347   if (!UniformBase) {
4348     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4349     Index = getValue(Ptr);
4350     IndexType = ISD::SIGNED_SCALED;
4351     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4352   }
4353   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4354   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4355                                          Ops, MMO, IndexType);
4356   DAG.setRoot(Scatter);
4357   setValue(&I, Scatter);
4358 }
4359 
4360 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4361   SDLoc sdl = getCurSDLoc();
4362 
4363   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4364                               MaybeAlign &Alignment) {
4365     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4366     Ptr = I.getArgOperand(0);
4367     Alignment =
4368         MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4369     Mask = I.getArgOperand(2);
4370     Src0 = I.getArgOperand(3);
4371   };
4372   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4373                                  MaybeAlign &Alignment) {
4374     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4375     Ptr = I.getArgOperand(0);
4376     Alignment = None;
4377     Mask = I.getArgOperand(1);
4378     Src0 = I.getArgOperand(2);
4379   };
4380 
4381   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4382   MaybeAlign Alignment;
4383   if (IsExpanding)
4384     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4385   else
4386     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4387 
4388   SDValue Ptr = getValue(PtrOperand);
4389   SDValue Src0 = getValue(Src0Operand);
4390   SDValue Mask = getValue(MaskOperand);
4391   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4392 
4393   EVT VT = Src0.getValueType();
4394   if (!Alignment)
4395     Alignment = DAG.getEVTAlign(VT);
4396 
4397   AAMDNodes AAInfo;
4398   I.getAAMetadata(AAInfo);
4399   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4400 
4401   // Do not serialize masked loads of constant memory with anything.
4402   MemoryLocation ML;
4403   if (VT.isScalableVector())
4404     ML = MemoryLocation(PtrOperand);
4405   else
4406     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4407                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4408                            AAInfo);
4409   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4410 
4411   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4412 
4413   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4414       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4415       // TODO: Make MachineMemOperands aware of scalable
4416       // vectors.
4417       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4418 
4419   SDValue Load =
4420       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4421                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4422   if (AddToChain)
4423     PendingLoads.push_back(Load.getValue(1));
4424   setValue(&I, Load);
4425 }
4426 
4427 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4428   SDLoc sdl = getCurSDLoc();
4429 
4430   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4431   const Value *Ptr = I.getArgOperand(0);
4432   SDValue Src0 = getValue(I.getArgOperand(3));
4433   SDValue Mask = getValue(I.getArgOperand(2));
4434 
4435   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4436   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4437   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4438   if (!Alignment)
4439     Alignment = DAG.getEVTAlign(VT);
4440 
4441   AAMDNodes AAInfo;
4442   I.getAAMetadata(AAInfo);
4443   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4444 
4445   SDValue Root = DAG.getRoot();
4446   SDValue Base;
4447   SDValue Index;
4448   ISD::MemIndexType IndexType;
4449   SDValue Scale;
4450   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4451                                     I.getParent());
4452   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4453   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4454       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4455       // TODO: Make MachineMemOperands aware of scalable
4456       // vectors.
4457       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4458 
4459   if (!UniformBase) {
4460     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4461     Index = getValue(Ptr);
4462     IndexType = ISD::SIGNED_SCALED;
4463     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4464   }
4465   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4466   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4467                                        Ops, MMO, IndexType);
4468 
4469   PendingLoads.push_back(Gather.getValue(1));
4470   setValue(&I, Gather);
4471 }
4472 
4473 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4474   SDLoc dl = getCurSDLoc();
4475   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4476   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4477   SyncScope::ID SSID = I.getSyncScopeID();
4478 
4479   SDValue InChain = getRoot();
4480 
4481   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4482   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4483 
4484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4485   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4486 
4487   MachineFunction &MF = DAG.getMachineFunction();
4488   MachineMemOperand *MMO = MF.getMachineMemOperand(
4489       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4490       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4491       FailureOrdering);
4492 
4493   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4494                                    dl, MemVT, VTs, InChain,
4495                                    getValue(I.getPointerOperand()),
4496                                    getValue(I.getCompareOperand()),
4497                                    getValue(I.getNewValOperand()), MMO);
4498 
4499   SDValue OutChain = L.getValue(2);
4500 
4501   setValue(&I, L);
4502   DAG.setRoot(OutChain);
4503 }
4504 
4505 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4506   SDLoc dl = getCurSDLoc();
4507   ISD::NodeType NT;
4508   switch (I.getOperation()) {
4509   default: llvm_unreachable("Unknown atomicrmw operation");
4510   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4511   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4512   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4513   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4514   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4515   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4516   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4517   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4518   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4519   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4520   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4521   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4522   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4523   }
4524   AtomicOrdering Ordering = I.getOrdering();
4525   SyncScope::ID SSID = I.getSyncScopeID();
4526 
4527   SDValue InChain = getRoot();
4528 
4529   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4530   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4531   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4532 
4533   MachineFunction &MF = DAG.getMachineFunction();
4534   MachineMemOperand *MMO = MF.getMachineMemOperand(
4535       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4536       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4537 
4538   SDValue L =
4539     DAG.getAtomic(NT, dl, MemVT, InChain,
4540                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4541                   MMO);
4542 
4543   SDValue OutChain = L.getValue(1);
4544 
4545   setValue(&I, L);
4546   DAG.setRoot(OutChain);
4547 }
4548 
4549 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4550   SDLoc dl = getCurSDLoc();
4551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4552   SDValue Ops[3];
4553   Ops[0] = getRoot();
4554   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4555                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4556   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4557                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4558   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4559 }
4560 
4561 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4562   SDLoc dl = getCurSDLoc();
4563   AtomicOrdering Order = I.getOrdering();
4564   SyncScope::ID SSID = I.getSyncScopeID();
4565 
4566   SDValue InChain = getRoot();
4567 
4568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4569   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4570   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4571 
4572   if (!TLI.supportsUnalignedAtomics() &&
4573       I.getAlignment() < MemVT.getSizeInBits() / 8)
4574     report_fatal_error("Cannot generate unaligned atomic load");
4575 
4576   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4577 
4578   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4579       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4580       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4581 
4582   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4583 
4584   SDValue Ptr = getValue(I.getPointerOperand());
4585 
4586   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4587     // TODO: Once this is better exercised by tests, it should be merged with
4588     // the normal path for loads to prevent future divergence.
4589     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4590     if (MemVT != VT)
4591       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4592 
4593     setValue(&I, L);
4594     SDValue OutChain = L.getValue(1);
4595     if (!I.isUnordered())
4596       DAG.setRoot(OutChain);
4597     else
4598       PendingLoads.push_back(OutChain);
4599     return;
4600   }
4601 
4602   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4603                             Ptr, MMO);
4604 
4605   SDValue OutChain = L.getValue(1);
4606   if (MemVT != VT)
4607     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4608 
4609   setValue(&I, L);
4610   DAG.setRoot(OutChain);
4611 }
4612 
4613 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4614   SDLoc dl = getCurSDLoc();
4615 
4616   AtomicOrdering Ordering = I.getOrdering();
4617   SyncScope::ID SSID = I.getSyncScopeID();
4618 
4619   SDValue InChain = getRoot();
4620 
4621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4622   EVT MemVT =
4623       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4624 
4625   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4626     report_fatal_error("Cannot generate unaligned atomic store");
4627 
4628   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4629 
4630   MachineFunction &MF = DAG.getMachineFunction();
4631   MachineMemOperand *MMO = MF.getMachineMemOperand(
4632       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4633       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4634 
4635   SDValue Val = getValue(I.getValueOperand());
4636   if (Val.getValueType() != MemVT)
4637     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4638   SDValue Ptr = getValue(I.getPointerOperand());
4639 
4640   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4641     // TODO: Once this is better exercised by tests, it should be merged with
4642     // the normal path for stores to prevent future divergence.
4643     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4644     DAG.setRoot(S);
4645     return;
4646   }
4647   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4648                                    Ptr, Val, MMO);
4649 
4650 
4651   DAG.setRoot(OutChain);
4652 }
4653 
4654 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4655 /// node.
4656 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4657                                                unsigned Intrinsic) {
4658   // Ignore the callsite's attributes. A specific call site may be marked with
4659   // readnone, but the lowering code will expect the chain based on the
4660   // definition.
4661   const Function *F = I.getCalledFunction();
4662   bool HasChain = !F->doesNotAccessMemory();
4663   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4664 
4665   // Build the operand list.
4666   SmallVector<SDValue, 8> Ops;
4667   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4668     if (OnlyLoad) {
4669       // We don't need to serialize loads against other loads.
4670       Ops.push_back(DAG.getRoot());
4671     } else {
4672       Ops.push_back(getRoot());
4673     }
4674   }
4675 
4676   // Info is set by getTgtMemInstrinsic
4677   TargetLowering::IntrinsicInfo Info;
4678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4679   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4680                                                DAG.getMachineFunction(),
4681                                                Intrinsic);
4682 
4683   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4684   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4685       Info.opc == ISD::INTRINSIC_W_CHAIN)
4686     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4687                                         TLI.getPointerTy(DAG.getDataLayout())));
4688 
4689   // Add all operands of the call to the operand list.
4690   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4691     const Value *Arg = I.getArgOperand(i);
4692     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4693       Ops.push_back(getValue(Arg));
4694       continue;
4695     }
4696 
4697     // Use TargetConstant instead of a regular constant for immarg.
4698     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4699     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4700       assert(CI->getBitWidth() <= 64 &&
4701              "large intrinsic immediates not handled");
4702       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4703     } else {
4704       Ops.push_back(
4705           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4706     }
4707   }
4708 
4709   SmallVector<EVT, 4> ValueVTs;
4710   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4711 
4712   if (HasChain)
4713     ValueVTs.push_back(MVT::Other);
4714 
4715   SDVTList VTs = DAG.getVTList(ValueVTs);
4716 
4717   // Create the node.
4718   SDValue Result;
4719   if (IsTgtIntrinsic) {
4720     // This is target intrinsic that touches memory
4721     AAMDNodes AAInfo;
4722     I.getAAMetadata(AAInfo);
4723     Result =
4724         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4725                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4726                                 Info.align, Info.flags, Info.size, AAInfo);
4727   } else if (!HasChain) {
4728     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4729   } else if (!I.getType()->isVoidTy()) {
4730     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4731   } else {
4732     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4733   }
4734 
4735   if (HasChain) {
4736     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4737     if (OnlyLoad)
4738       PendingLoads.push_back(Chain);
4739     else
4740       DAG.setRoot(Chain);
4741   }
4742 
4743   if (!I.getType()->isVoidTy()) {
4744     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4745       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4746       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4747     } else
4748       Result = lowerRangeToAssertZExt(DAG, I, Result);
4749 
4750     setValue(&I, Result);
4751   }
4752 }
4753 
4754 /// GetSignificand - Get the significand and build it into a floating-point
4755 /// number with exponent of 1:
4756 ///
4757 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4758 ///
4759 /// where Op is the hexadecimal representation of floating point value.
4760 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4761   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4762                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4763   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4764                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4765   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4766 }
4767 
4768 /// GetExponent - Get the exponent:
4769 ///
4770 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4771 ///
4772 /// where Op is the hexadecimal representation of floating point value.
4773 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4774                            const TargetLowering &TLI, const SDLoc &dl) {
4775   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4776                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4777   SDValue t1 = DAG.getNode(
4778       ISD::SRL, dl, MVT::i32, t0,
4779       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4780   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4781                            DAG.getConstant(127, dl, MVT::i32));
4782   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4783 }
4784 
4785 /// getF32Constant - Get 32-bit floating point constant.
4786 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4787                               const SDLoc &dl) {
4788   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4789                            MVT::f32);
4790 }
4791 
4792 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4793                                        SelectionDAG &DAG) {
4794   // TODO: What fast-math-flags should be set on the floating-point nodes?
4795 
4796   //   IntegerPartOfX = ((int32_t)(t0);
4797   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4798 
4799   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4800   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4801   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4802 
4803   //   IntegerPartOfX <<= 23;
4804   IntegerPartOfX = DAG.getNode(
4805       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4806       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4807                                   DAG.getDataLayout())));
4808 
4809   SDValue TwoToFractionalPartOfX;
4810   if (LimitFloatPrecision <= 6) {
4811     // For floating-point precision of 6:
4812     //
4813     //   TwoToFractionalPartOfX =
4814     //     0.997535578f +
4815     //       (0.735607626f + 0.252464424f * x) * x;
4816     //
4817     // error 0.0144103317, which is 6 bits
4818     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4819                              getF32Constant(DAG, 0x3e814304, dl));
4820     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4821                              getF32Constant(DAG, 0x3f3c50c8, dl));
4822     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4823     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4824                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4825   } else if (LimitFloatPrecision <= 12) {
4826     // For floating-point precision of 12:
4827     //
4828     //   TwoToFractionalPartOfX =
4829     //     0.999892986f +
4830     //       (0.696457318f +
4831     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4832     //
4833     // error 0.000107046256, which is 13 to 14 bits
4834     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4835                              getF32Constant(DAG, 0x3da235e3, dl));
4836     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4837                              getF32Constant(DAG, 0x3e65b8f3, dl));
4838     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4839     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4840                              getF32Constant(DAG, 0x3f324b07, dl));
4841     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4842     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4843                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4844   } else { // LimitFloatPrecision <= 18
4845     // For floating-point precision of 18:
4846     //
4847     //   TwoToFractionalPartOfX =
4848     //     0.999999982f +
4849     //       (0.693148872f +
4850     //         (0.240227044f +
4851     //           (0.554906021e-1f +
4852     //             (0.961591928e-2f +
4853     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4854     // error 2.47208000*10^(-7), which is better than 18 bits
4855     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4856                              getF32Constant(DAG, 0x3924b03e, dl));
4857     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4858                              getF32Constant(DAG, 0x3ab24b87, dl));
4859     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4860     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4861                              getF32Constant(DAG, 0x3c1d8c17, dl));
4862     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4863     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4864                              getF32Constant(DAG, 0x3d634a1d, dl));
4865     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4866     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4867                              getF32Constant(DAG, 0x3e75fe14, dl));
4868     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4869     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4870                               getF32Constant(DAG, 0x3f317234, dl));
4871     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4872     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4873                                          getF32Constant(DAG, 0x3f800000, dl));
4874   }
4875 
4876   // Add the exponent into the result in integer domain.
4877   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4878   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4879                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4880 }
4881 
4882 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4883 /// limited-precision mode.
4884 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4885                          const TargetLowering &TLI) {
4886   if (Op.getValueType() == MVT::f32 &&
4887       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4888 
4889     // Put the exponent in the right bit position for later addition to the
4890     // final result:
4891     //
4892     // t0 = Op * log2(e)
4893 
4894     // TODO: What fast-math-flags should be set here?
4895     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4896                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4897     return getLimitedPrecisionExp2(t0, dl, DAG);
4898   }
4899 
4900   // No special expansion.
4901   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4902 }
4903 
4904 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4905 /// limited-precision mode.
4906 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4907                          const TargetLowering &TLI) {
4908   // TODO: What fast-math-flags should be set on the floating-point nodes?
4909 
4910   if (Op.getValueType() == MVT::f32 &&
4911       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4912     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4913 
4914     // Scale the exponent by log(2).
4915     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4916     SDValue LogOfExponent =
4917         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4918                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4919 
4920     // Get the significand and build it into a floating-point number with
4921     // exponent of 1.
4922     SDValue X = GetSignificand(DAG, Op1, dl);
4923 
4924     SDValue LogOfMantissa;
4925     if (LimitFloatPrecision <= 6) {
4926       // For floating-point precision of 6:
4927       //
4928       //   LogofMantissa =
4929       //     -1.1609546f +
4930       //       (1.4034025f - 0.23903021f * x) * x;
4931       //
4932       // error 0.0034276066, which is better than 8 bits
4933       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4934                                getF32Constant(DAG, 0xbe74c456, dl));
4935       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4936                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4937       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4938       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4939                                   getF32Constant(DAG, 0x3f949a29, dl));
4940     } else if (LimitFloatPrecision <= 12) {
4941       // For floating-point precision of 12:
4942       //
4943       //   LogOfMantissa =
4944       //     -1.7417939f +
4945       //       (2.8212026f +
4946       //         (-1.4699568f +
4947       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4948       //
4949       // error 0.000061011436, which is 14 bits
4950       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4951                                getF32Constant(DAG, 0xbd67b6d6, dl));
4952       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4953                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4954       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4955       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4956                                getF32Constant(DAG, 0x3fbc278b, dl));
4957       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4958       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4959                                getF32Constant(DAG, 0x40348e95, dl));
4960       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4961       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4962                                   getF32Constant(DAG, 0x3fdef31a, dl));
4963     } else { // LimitFloatPrecision <= 18
4964       // For floating-point precision of 18:
4965       //
4966       //   LogOfMantissa =
4967       //     -2.1072184f +
4968       //       (4.2372794f +
4969       //         (-3.7029485f +
4970       //           (2.2781945f +
4971       //             (-0.87823314f +
4972       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4973       //
4974       // error 0.0000023660568, which is better than 18 bits
4975       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4976                                getF32Constant(DAG, 0xbc91e5ac, dl));
4977       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4978                                getF32Constant(DAG, 0x3e4350aa, dl));
4979       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4980       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4981                                getF32Constant(DAG, 0x3f60d3e3, dl));
4982       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4983       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4984                                getF32Constant(DAG, 0x4011cdf0, dl));
4985       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4986       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4987                                getF32Constant(DAG, 0x406cfd1c, dl));
4988       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4989       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4990                                getF32Constant(DAG, 0x408797cb, dl));
4991       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4992       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4993                                   getF32Constant(DAG, 0x4006dcab, dl));
4994     }
4995 
4996     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4997   }
4998 
4999   // No special expansion.
5000   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5001 }
5002 
5003 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5004 /// limited-precision mode.
5005 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5006                           const TargetLowering &TLI) {
5007   // TODO: What fast-math-flags should be set on the floating-point nodes?
5008 
5009   if (Op.getValueType() == MVT::f32 &&
5010       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5011     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5012 
5013     // Get the exponent.
5014     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5015 
5016     // Get the significand and build it into a floating-point number with
5017     // exponent of 1.
5018     SDValue X = GetSignificand(DAG, Op1, dl);
5019 
5020     // Different possible minimax approximations of significand in
5021     // floating-point for various degrees of accuracy over [1,2].
5022     SDValue Log2ofMantissa;
5023     if (LimitFloatPrecision <= 6) {
5024       // For floating-point precision of 6:
5025       //
5026       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5027       //
5028       // error 0.0049451742, which is more than 7 bits
5029       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5030                                getF32Constant(DAG, 0xbeb08fe0, dl));
5031       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5032                                getF32Constant(DAG, 0x40019463, dl));
5033       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5034       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5035                                    getF32Constant(DAG, 0x3fd6633d, dl));
5036     } else if (LimitFloatPrecision <= 12) {
5037       // For floating-point precision of 12:
5038       //
5039       //   Log2ofMantissa =
5040       //     -2.51285454f +
5041       //       (4.07009056f +
5042       //         (-2.12067489f +
5043       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5044       //
5045       // error 0.0000876136000, which is better than 13 bits
5046       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5047                                getF32Constant(DAG, 0xbda7262e, dl));
5048       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5049                                getF32Constant(DAG, 0x3f25280b, dl));
5050       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5051       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5052                                getF32Constant(DAG, 0x4007b923, dl));
5053       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5054       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5055                                getF32Constant(DAG, 0x40823e2f, dl));
5056       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5057       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5058                                    getF32Constant(DAG, 0x4020d29c, dl));
5059     } else { // LimitFloatPrecision <= 18
5060       // For floating-point precision of 18:
5061       //
5062       //   Log2ofMantissa =
5063       //     -3.0400495f +
5064       //       (6.1129976f +
5065       //         (-5.3420409f +
5066       //           (3.2865683f +
5067       //             (-1.2669343f +
5068       //               (0.27515199f -
5069       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5070       //
5071       // error 0.0000018516, which is better than 18 bits
5072       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5073                                getF32Constant(DAG, 0xbcd2769e, dl));
5074       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5075                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5076       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5077       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5078                                getF32Constant(DAG, 0x3fa22ae7, dl));
5079       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5080       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5081                                getF32Constant(DAG, 0x40525723, dl));
5082       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5083       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5084                                getF32Constant(DAG, 0x40aaf200, dl));
5085       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5086       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5087                                getF32Constant(DAG, 0x40c39dad, dl));
5088       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5089       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5090                                    getF32Constant(DAG, 0x4042902c, dl));
5091     }
5092 
5093     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5094   }
5095 
5096   // No special expansion.
5097   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5098 }
5099 
5100 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5101 /// limited-precision mode.
5102 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5103                            const TargetLowering &TLI) {
5104   // TODO: What fast-math-flags should be set on the floating-point nodes?
5105 
5106   if (Op.getValueType() == MVT::f32 &&
5107       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5108     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5109 
5110     // Scale the exponent by log10(2) [0.30102999f].
5111     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5112     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5113                                         getF32Constant(DAG, 0x3e9a209a, dl));
5114 
5115     // Get the significand and build it into a floating-point number with
5116     // exponent of 1.
5117     SDValue X = GetSignificand(DAG, Op1, dl);
5118 
5119     SDValue Log10ofMantissa;
5120     if (LimitFloatPrecision <= 6) {
5121       // For floating-point precision of 6:
5122       //
5123       //   Log10ofMantissa =
5124       //     -0.50419619f +
5125       //       (0.60948995f - 0.10380950f * x) * x;
5126       //
5127       // error 0.0014886165, which is 6 bits
5128       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5129                                getF32Constant(DAG, 0xbdd49a13, dl));
5130       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5131                                getF32Constant(DAG, 0x3f1c0789, dl));
5132       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5133       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5134                                     getF32Constant(DAG, 0x3f011300, dl));
5135     } else if (LimitFloatPrecision <= 12) {
5136       // For floating-point precision of 12:
5137       //
5138       //   Log10ofMantissa =
5139       //     -0.64831180f +
5140       //       (0.91751397f +
5141       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5142       //
5143       // error 0.00019228036, which is better than 12 bits
5144       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5145                                getF32Constant(DAG, 0x3d431f31, dl));
5146       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5147                                getF32Constant(DAG, 0x3ea21fb2, dl));
5148       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5149       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5150                                getF32Constant(DAG, 0x3f6ae232, dl));
5151       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5152       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5153                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5154     } else { // LimitFloatPrecision <= 18
5155       // For floating-point precision of 18:
5156       //
5157       //   Log10ofMantissa =
5158       //     -0.84299375f +
5159       //       (1.5327582f +
5160       //         (-1.0688956f +
5161       //           (0.49102474f +
5162       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5163       //
5164       // error 0.0000037995730, which is better than 18 bits
5165       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5166                                getF32Constant(DAG, 0x3c5d51ce, dl));
5167       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5168                                getF32Constant(DAG, 0x3e00685a, dl));
5169       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5170       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5171                                getF32Constant(DAG, 0x3efb6798, dl));
5172       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5173       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5174                                getF32Constant(DAG, 0x3f88d192, dl));
5175       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5176       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5177                                getF32Constant(DAG, 0x3fc4316c, dl));
5178       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5179       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5180                                     getF32Constant(DAG, 0x3f57ce70, dl));
5181     }
5182 
5183     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5184   }
5185 
5186   // No special expansion.
5187   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5188 }
5189 
5190 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5191 /// limited-precision mode.
5192 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5193                           const TargetLowering &TLI) {
5194   if (Op.getValueType() == MVT::f32 &&
5195       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5196     return getLimitedPrecisionExp2(Op, dl, DAG);
5197 
5198   // No special expansion.
5199   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5200 }
5201 
5202 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5203 /// limited-precision mode with x == 10.0f.
5204 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5205                          SelectionDAG &DAG, const TargetLowering &TLI) {
5206   bool IsExp10 = false;
5207   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5208       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5209     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5210       APFloat Ten(10.0f);
5211       IsExp10 = LHSC->isExactlyValue(Ten);
5212     }
5213   }
5214 
5215   // TODO: What fast-math-flags should be set on the FMUL node?
5216   if (IsExp10) {
5217     // Put the exponent in the right bit position for later addition to the
5218     // final result:
5219     //
5220     //   #define LOG2OF10 3.3219281f
5221     //   t0 = Op * LOG2OF10;
5222     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5223                              getF32Constant(DAG, 0x40549a78, dl));
5224     return getLimitedPrecisionExp2(t0, dl, DAG);
5225   }
5226 
5227   // No special expansion.
5228   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5229 }
5230 
5231 /// ExpandPowI - Expand a llvm.powi intrinsic.
5232 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5233                           SelectionDAG &DAG) {
5234   // If RHS is a constant, we can expand this out to a multiplication tree,
5235   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5236   // optimizing for size, we only want to do this if the expansion would produce
5237   // a small number of multiplies, otherwise we do the full expansion.
5238   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5239     // Get the exponent as a positive value.
5240     unsigned Val = RHSC->getSExtValue();
5241     if ((int)Val < 0) Val = -Val;
5242 
5243     // powi(x, 0) -> 1.0
5244     if (Val == 0)
5245       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5246 
5247     bool OptForSize = DAG.shouldOptForSize();
5248     if (!OptForSize ||
5249         // If optimizing for size, don't insert too many multiplies.
5250         // This inserts up to 5 multiplies.
5251         countPopulation(Val) + Log2_32(Val) < 7) {
5252       // We use the simple binary decomposition method to generate the multiply
5253       // sequence.  There are more optimal ways to do this (for example,
5254       // powi(x,15) generates one more multiply than it should), but this has
5255       // the benefit of being both really simple and much better than a libcall.
5256       SDValue Res;  // Logically starts equal to 1.0
5257       SDValue CurSquare = LHS;
5258       // TODO: Intrinsics should have fast-math-flags that propagate to these
5259       // nodes.
5260       while (Val) {
5261         if (Val & 1) {
5262           if (Res.getNode())
5263             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5264           else
5265             Res = CurSquare;  // 1.0*CurSquare.
5266         }
5267 
5268         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5269                                 CurSquare, CurSquare);
5270         Val >>= 1;
5271       }
5272 
5273       // If the original was negative, invert the result, producing 1/(x*x*x).
5274       if (RHSC->getSExtValue() < 0)
5275         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5276                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5277       return Res;
5278     }
5279   }
5280 
5281   // Otherwise, expand to a libcall.
5282   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5283 }
5284 
5285 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5286                             SDValue LHS, SDValue RHS, SDValue Scale,
5287                             SelectionDAG &DAG, const TargetLowering &TLI) {
5288   EVT VT = LHS.getValueType();
5289   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5290   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5291   LLVMContext &Ctx = *DAG.getContext();
5292 
5293   // If the type is legal but the operation isn't, this node might survive all
5294   // the way to operation legalization. If we end up there and we do not have
5295   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5296   // node.
5297 
5298   // Coax the legalizer into expanding the node during type legalization instead
5299   // by bumping the size by one bit. This will force it to Promote, enabling the
5300   // early expansion and avoiding the need to expand later.
5301 
5302   // We don't have to do this if Scale is 0; that can always be expanded, unless
5303   // it's a saturating signed operation. Those can experience true integer
5304   // division overflow, a case which we must avoid.
5305 
5306   // FIXME: We wouldn't have to do this (or any of the early
5307   // expansion/promotion) if it was possible to expand a libcall of an
5308   // illegal type during operation legalization. But it's not, so things
5309   // get a bit hacky.
5310   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5311   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5312       (TLI.isTypeLegal(VT) ||
5313        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5314     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5315         Opcode, VT, ScaleInt);
5316     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5317       EVT PromVT;
5318       if (VT.isScalarInteger())
5319         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5320       else if (VT.isVector()) {
5321         PromVT = VT.getVectorElementType();
5322         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5323         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5324       } else
5325         llvm_unreachable("Wrong VT for DIVFIX?");
5326       if (Signed) {
5327         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5328         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5329       } else {
5330         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5331         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5332       }
5333       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5334       // For saturating operations, we need to shift up the LHS to get the
5335       // proper saturation width, and then shift down again afterwards.
5336       if (Saturating)
5337         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5338                           DAG.getConstant(1, DL, ShiftTy));
5339       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5340       if (Saturating)
5341         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5342                           DAG.getConstant(1, DL, ShiftTy));
5343       return DAG.getZExtOrTrunc(Res, DL, VT);
5344     }
5345   }
5346 
5347   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5348 }
5349 
5350 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5351 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5352 static void
5353 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5354                      const SDValue &N) {
5355   switch (N.getOpcode()) {
5356   case ISD::CopyFromReg: {
5357     SDValue Op = N.getOperand(1);
5358     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5359                       Op.getValueType().getSizeInBits());
5360     return;
5361   }
5362   case ISD::BITCAST:
5363   case ISD::AssertZext:
5364   case ISD::AssertSext:
5365   case ISD::TRUNCATE:
5366     getUnderlyingArgRegs(Regs, N.getOperand(0));
5367     return;
5368   case ISD::BUILD_PAIR:
5369   case ISD::BUILD_VECTOR:
5370   case ISD::CONCAT_VECTORS:
5371     for (SDValue Op : N->op_values())
5372       getUnderlyingArgRegs(Regs, Op);
5373     return;
5374   default:
5375     return;
5376   }
5377 }
5378 
5379 /// If the DbgValueInst is a dbg_value of a function argument, create the
5380 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5381 /// instruction selection, they will be inserted to the entry BB.
5382 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5383     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5384     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5385   const Argument *Arg = dyn_cast<Argument>(V);
5386   if (!Arg)
5387     return false;
5388 
5389   if (!IsDbgDeclare) {
5390     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5391     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5392     // the entry block.
5393     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5394     if (!IsInEntryBlock)
5395       return false;
5396 
5397     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5398     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5399     // variable that also is a param.
5400     //
5401     // Although, if we are at the top of the entry block already, we can still
5402     // emit using ArgDbgValue. This might catch some situations when the
5403     // dbg.value refers to an argument that isn't used in the entry block, so
5404     // any CopyToReg node would be optimized out and the only way to express
5405     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5406     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5407     // we should only emit as ArgDbgValue if the Variable is an argument to the
5408     // current function, and the dbg.value intrinsic is found in the entry
5409     // block.
5410     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5411         !DL->getInlinedAt();
5412     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5413     if (!IsInPrologue && !VariableIsFunctionInputArg)
5414       return false;
5415 
5416     // Here we assume that a function argument on IR level only can be used to
5417     // describe one input parameter on source level. If we for example have
5418     // source code like this
5419     //
5420     //    struct A { long x, y; };
5421     //    void foo(struct A a, long b) {
5422     //      ...
5423     //      b = a.x;
5424     //      ...
5425     //    }
5426     //
5427     // and IR like this
5428     //
5429     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5430     //  entry:
5431     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5432     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5433     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5434     //    ...
5435     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5436     //    ...
5437     //
5438     // then the last dbg.value is describing a parameter "b" using a value that
5439     // is an argument. But since we already has used %a1 to describe a parameter
5440     // we should not handle that last dbg.value here (that would result in an
5441     // incorrect hoisting of the DBG_VALUE to the function entry).
5442     // Notice that we allow one dbg.value per IR level argument, to accommodate
5443     // for the situation with fragments above.
5444     if (VariableIsFunctionInputArg) {
5445       unsigned ArgNo = Arg->getArgNo();
5446       if (ArgNo >= FuncInfo.DescribedArgs.size())
5447         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5448       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5449         return false;
5450       FuncInfo.DescribedArgs.set(ArgNo);
5451     }
5452   }
5453 
5454   MachineFunction &MF = DAG.getMachineFunction();
5455   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5456 
5457   bool IsIndirect = false;
5458   Optional<MachineOperand> Op;
5459   // Some arguments' frame index is recorded during argument lowering.
5460   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5461   if (FI != std::numeric_limits<int>::max())
5462     Op = MachineOperand::CreateFI(FI);
5463 
5464   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5465   if (!Op && N.getNode()) {
5466     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5467     Register Reg;
5468     if (ArgRegsAndSizes.size() == 1)
5469       Reg = ArgRegsAndSizes.front().first;
5470 
5471     if (Reg && Reg.isVirtual()) {
5472       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5473       Register PR = RegInfo.getLiveInPhysReg(Reg);
5474       if (PR)
5475         Reg = PR;
5476     }
5477     if (Reg) {
5478       Op = MachineOperand::CreateReg(Reg, false);
5479       IsIndirect = IsDbgDeclare;
5480     }
5481   }
5482 
5483   if (!Op && N.getNode()) {
5484     // Check if frame index is available.
5485     SDValue LCandidate = peekThroughBitcasts(N);
5486     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5487       if (FrameIndexSDNode *FINode =
5488           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5489         Op = MachineOperand::CreateFI(FINode->getIndex());
5490   }
5491 
5492   if (!Op) {
5493     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5494     auto splitMultiRegDbgValue
5495       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5496       unsigned Offset = 0;
5497       for (auto RegAndSize : SplitRegs) {
5498         // If the expression is already a fragment, the current register
5499         // offset+size might extend beyond the fragment. In this case, only
5500         // the register bits that are inside the fragment are relevant.
5501         int RegFragmentSizeInBits = RegAndSize.second;
5502         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5503           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5504           // The register is entirely outside the expression fragment,
5505           // so is irrelevant for debug info.
5506           if (Offset >= ExprFragmentSizeInBits)
5507             break;
5508           // The register is partially outside the expression fragment, only
5509           // the low bits within the fragment are relevant for debug info.
5510           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5511             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5512           }
5513         }
5514 
5515         auto FragmentExpr = DIExpression::createFragmentExpression(
5516             Expr, Offset, RegFragmentSizeInBits);
5517         Offset += RegAndSize.second;
5518         // If a valid fragment expression cannot be created, the variable's
5519         // correct value cannot be determined and so it is set as Undef.
5520         if (!FragmentExpr) {
5521           SDDbgValue *SDV = DAG.getConstantDbgValue(
5522               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5523           DAG.AddDbgValue(SDV, nullptr, false);
5524           continue;
5525         }
5526         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5527         FuncInfo.ArgDbgValues.push_back(
5528           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5529                   RegAndSize.first, Variable, *FragmentExpr));
5530       }
5531     };
5532 
5533     // Check if ValueMap has reg number.
5534     DenseMap<const Value *, Register>::const_iterator
5535       VMI = FuncInfo.ValueMap.find(V);
5536     if (VMI != FuncInfo.ValueMap.end()) {
5537       const auto &TLI = DAG.getTargetLoweringInfo();
5538       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5539                        V->getType(), getABIRegCopyCC(V));
5540       if (RFV.occupiesMultipleRegs()) {
5541         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5542         return true;
5543       }
5544 
5545       Op = MachineOperand::CreateReg(VMI->second, false);
5546       IsIndirect = IsDbgDeclare;
5547     } else if (ArgRegsAndSizes.size() > 1) {
5548       // This was split due to the calling convention, and no virtual register
5549       // mapping exists for the value.
5550       splitMultiRegDbgValue(ArgRegsAndSizes);
5551       return true;
5552     }
5553   }
5554 
5555   if (!Op)
5556     return false;
5557 
5558   assert(Variable->isValidLocationForIntrinsic(DL) &&
5559          "Expected inlined-at fields to agree");
5560   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5561   FuncInfo.ArgDbgValues.push_back(
5562       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5563               *Op, Variable, Expr));
5564 
5565   return true;
5566 }
5567 
5568 /// Return the appropriate SDDbgValue based on N.
5569 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5570                                              DILocalVariable *Variable,
5571                                              DIExpression *Expr,
5572                                              const DebugLoc &dl,
5573                                              unsigned DbgSDNodeOrder) {
5574   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5575     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5576     // stack slot locations.
5577     //
5578     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5579     // debug values here after optimization:
5580     //
5581     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5582     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5583     //
5584     // Both describe the direct values of their associated variables.
5585     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5586                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5587   }
5588   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5589                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5590 }
5591 
5592 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5593   switch (Intrinsic) {
5594   case Intrinsic::smul_fix:
5595     return ISD::SMULFIX;
5596   case Intrinsic::umul_fix:
5597     return ISD::UMULFIX;
5598   case Intrinsic::smul_fix_sat:
5599     return ISD::SMULFIXSAT;
5600   case Intrinsic::umul_fix_sat:
5601     return ISD::UMULFIXSAT;
5602   case Intrinsic::sdiv_fix:
5603     return ISD::SDIVFIX;
5604   case Intrinsic::udiv_fix:
5605     return ISD::UDIVFIX;
5606   case Intrinsic::sdiv_fix_sat:
5607     return ISD::SDIVFIXSAT;
5608   case Intrinsic::udiv_fix_sat:
5609     return ISD::UDIVFIXSAT;
5610   default:
5611     llvm_unreachable("Unhandled fixed point intrinsic");
5612   }
5613 }
5614 
5615 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5616                                            const char *FunctionName) {
5617   assert(FunctionName && "FunctionName must not be nullptr");
5618   SDValue Callee = DAG.getExternalSymbol(
5619       FunctionName,
5620       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5621   LowerCallTo(I, Callee, I.isTailCall());
5622 }
5623 
5624 /// Given a @llvm.call.preallocated.setup, return the corresponding
5625 /// preallocated call.
5626 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5627   assert(cast<CallBase>(PreallocatedSetup)
5628                  ->getCalledFunction()
5629                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5630          "expected call_preallocated_setup Value");
5631   for (auto *U : PreallocatedSetup->users()) {
5632     auto *UseCall = cast<CallBase>(U);
5633     const Function *Fn = UseCall->getCalledFunction();
5634     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5635       return UseCall;
5636     }
5637   }
5638   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5639 }
5640 
5641 /// Lower the call to the specified intrinsic function.
5642 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5643                                              unsigned Intrinsic) {
5644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5645   SDLoc sdl = getCurSDLoc();
5646   DebugLoc dl = getCurDebugLoc();
5647   SDValue Res;
5648 
5649   switch (Intrinsic) {
5650   default:
5651     // By default, turn this into a target intrinsic node.
5652     visitTargetIntrinsic(I, Intrinsic);
5653     return;
5654   case Intrinsic::vscale: {
5655     match(&I, m_VScale(DAG.getDataLayout()));
5656     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5657     setValue(&I,
5658              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5659     return;
5660   }
5661   case Intrinsic::vastart:  visitVAStart(I); return;
5662   case Intrinsic::vaend:    visitVAEnd(I); return;
5663   case Intrinsic::vacopy:   visitVACopy(I); return;
5664   case Intrinsic::returnaddress:
5665     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5666                              TLI.getPointerTy(DAG.getDataLayout()),
5667                              getValue(I.getArgOperand(0))));
5668     return;
5669   case Intrinsic::addressofreturnaddress:
5670     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5671                              TLI.getPointerTy(DAG.getDataLayout())));
5672     return;
5673   case Intrinsic::sponentry:
5674     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5675                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5676     return;
5677   case Intrinsic::frameaddress:
5678     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5679                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5680                              getValue(I.getArgOperand(0))));
5681     return;
5682   case Intrinsic::read_register: {
5683     Value *Reg = I.getArgOperand(0);
5684     SDValue Chain = getRoot();
5685     SDValue RegName =
5686         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5687     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5688     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5689       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5690     setValue(&I, Res);
5691     DAG.setRoot(Res.getValue(1));
5692     return;
5693   }
5694   case Intrinsic::write_register: {
5695     Value *Reg = I.getArgOperand(0);
5696     Value *RegValue = I.getArgOperand(1);
5697     SDValue Chain = getRoot();
5698     SDValue RegName =
5699         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5700     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5701                             RegName, getValue(RegValue)));
5702     return;
5703   }
5704   case Intrinsic::memcpy: {
5705     const auto &MCI = cast<MemCpyInst>(I);
5706     SDValue Op1 = getValue(I.getArgOperand(0));
5707     SDValue Op2 = getValue(I.getArgOperand(1));
5708     SDValue Op3 = getValue(I.getArgOperand(2));
5709     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5710     Align DstAlign = MCI.getDestAlign().valueOrOne();
5711     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5712     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5713     bool isVol = MCI.isVolatile();
5714     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5715     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5716     // node.
5717     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5718     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5719                                /* AlwaysInline */ false, isTC,
5720                                MachinePointerInfo(I.getArgOperand(0)),
5721                                MachinePointerInfo(I.getArgOperand(1)));
5722     updateDAGForMaybeTailCall(MC);
5723     return;
5724   }
5725   case Intrinsic::memcpy_inline: {
5726     const auto &MCI = cast<MemCpyInlineInst>(I);
5727     SDValue Dst = getValue(I.getArgOperand(0));
5728     SDValue Src = getValue(I.getArgOperand(1));
5729     SDValue Size = getValue(I.getArgOperand(2));
5730     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5731     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5732     Align DstAlign = MCI.getDestAlign().valueOrOne();
5733     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5734     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5735     bool isVol = MCI.isVolatile();
5736     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5737     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5738     // node.
5739     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5740                                /* AlwaysInline */ true, isTC,
5741                                MachinePointerInfo(I.getArgOperand(0)),
5742                                MachinePointerInfo(I.getArgOperand(1)));
5743     updateDAGForMaybeTailCall(MC);
5744     return;
5745   }
5746   case Intrinsic::memset: {
5747     const auto &MSI = cast<MemSetInst>(I);
5748     SDValue Op1 = getValue(I.getArgOperand(0));
5749     SDValue Op2 = getValue(I.getArgOperand(1));
5750     SDValue Op3 = getValue(I.getArgOperand(2));
5751     // @llvm.memset defines 0 and 1 to both mean no alignment.
5752     Align Alignment = MSI.getDestAlign().valueOrOne();
5753     bool isVol = MSI.isVolatile();
5754     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5755     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5756     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5757                                MachinePointerInfo(I.getArgOperand(0)));
5758     updateDAGForMaybeTailCall(MS);
5759     return;
5760   }
5761   case Intrinsic::memmove: {
5762     const auto &MMI = cast<MemMoveInst>(I);
5763     SDValue Op1 = getValue(I.getArgOperand(0));
5764     SDValue Op2 = getValue(I.getArgOperand(1));
5765     SDValue Op3 = getValue(I.getArgOperand(2));
5766     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5767     Align DstAlign = MMI.getDestAlign().valueOrOne();
5768     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5769     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5770     bool isVol = MMI.isVolatile();
5771     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5772     // FIXME: Support passing different dest/src alignments to the memmove DAG
5773     // node.
5774     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5775     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5776                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5777                                 MachinePointerInfo(I.getArgOperand(1)));
5778     updateDAGForMaybeTailCall(MM);
5779     return;
5780   }
5781   case Intrinsic::memcpy_element_unordered_atomic: {
5782     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5783     SDValue Dst = getValue(MI.getRawDest());
5784     SDValue Src = getValue(MI.getRawSource());
5785     SDValue Length = getValue(MI.getLength());
5786 
5787     unsigned DstAlign = MI.getDestAlignment();
5788     unsigned SrcAlign = MI.getSourceAlignment();
5789     Type *LengthTy = MI.getLength()->getType();
5790     unsigned ElemSz = MI.getElementSizeInBytes();
5791     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5792     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5793                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5794                                      MachinePointerInfo(MI.getRawDest()),
5795                                      MachinePointerInfo(MI.getRawSource()));
5796     updateDAGForMaybeTailCall(MC);
5797     return;
5798   }
5799   case Intrinsic::memmove_element_unordered_atomic: {
5800     auto &MI = cast<AtomicMemMoveInst>(I);
5801     SDValue Dst = getValue(MI.getRawDest());
5802     SDValue Src = getValue(MI.getRawSource());
5803     SDValue Length = getValue(MI.getLength());
5804 
5805     unsigned DstAlign = MI.getDestAlignment();
5806     unsigned SrcAlign = MI.getSourceAlignment();
5807     Type *LengthTy = MI.getLength()->getType();
5808     unsigned ElemSz = MI.getElementSizeInBytes();
5809     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5810     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5811                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5812                                       MachinePointerInfo(MI.getRawDest()),
5813                                       MachinePointerInfo(MI.getRawSource()));
5814     updateDAGForMaybeTailCall(MC);
5815     return;
5816   }
5817   case Intrinsic::memset_element_unordered_atomic: {
5818     auto &MI = cast<AtomicMemSetInst>(I);
5819     SDValue Dst = getValue(MI.getRawDest());
5820     SDValue Val = getValue(MI.getValue());
5821     SDValue Length = getValue(MI.getLength());
5822 
5823     unsigned DstAlign = MI.getDestAlignment();
5824     Type *LengthTy = MI.getLength()->getType();
5825     unsigned ElemSz = MI.getElementSizeInBytes();
5826     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5827     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5828                                      LengthTy, ElemSz, isTC,
5829                                      MachinePointerInfo(MI.getRawDest()));
5830     updateDAGForMaybeTailCall(MC);
5831     return;
5832   }
5833   case Intrinsic::call_preallocated_setup: {
5834     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5835     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5836     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5837                               getRoot(), SrcValue);
5838     setValue(&I, Res);
5839     DAG.setRoot(Res);
5840     return;
5841   }
5842   case Intrinsic::call_preallocated_arg: {
5843     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5844     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5845     SDValue Ops[3];
5846     Ops[0] = getRoot();
5847     Ops[1] = SrcValue;
5848     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5849                                    MVT::i32); // arg index
5850     SDValue Res = DAG.getNode(
5851         ISD::PREALLOCATED_ARG, sdl,
5852         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5853     setValue(&I, Res);
5854     DAG.setRoot(Res.getValue(1));
5855     return;
5856   }
5857   case Intrinsic::dbg_addr:
5858   case Intrinsic::dbg_declare: {
5859     const auto &DI = cast<DbgVariableIntrinsic>(I);
5860     DILocalVariable *Variable = DI.getVariable();
5861     DIExpression *Expression = DI.getExpression();
5862     dropDanglingDebugInfo(Variable, Expression);
5863     assert(Variable && "Missing variable");
5864     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5865                       << "\n");
5866     // Check if address has undef value.
5867     const Value *Address = DI.getVariableLocation();
5868     if (!Address || isa<UndefValue>(Address) ||
5869         (Address->use_empty() && !isa<Argument>(Address))) {
5870       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5871                         << " (bad/undef/unused-arg address)\n");
5872       return;
5873     }
5874 
5875     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5876 
5877     // Check if this variable can be described by a frame index, typically
5878     // either as a static alloca or a byval parameter.
5879     int FI = std::numeric_limits<int>::max();
5880     if (const auto *AI =
5881             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5882       if (AI->isStaticAlloca()) {
5883         auto I = FuncInfo.StaticAllocaMap.find(AI);
5884         if (I != FuncInfo.StaticAllocaMap.end())
5885           FI = I->second;
5886       }
5887     } else if (const auto *Arg = dyn_cast<Argument>(
5888                    Address->stripInBoundsConstantOffsets())) {
5889       FI = FuncInfo.getArgumentFrameIndex(Arg);
5890     }
5891 
5892     // llvm.dbg.addr is control dependent and always generates indirect
5893     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5894     // the MachineFunction variable table.
5895     if (FI != std::numeric_limits<int>::max()) {
5896       if (Intrinsic == Intrinsic::dbg_addr) {
5897         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5898             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5899         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5900       } else {
5901         LLVM_DEBUG(dbgs() << "Skipping " << DI
5902                           << " (variable info stashed in MF side table)\n");
5903       }
5904       return;
5905     }
5906 
5907     SDValue &N = NodeMap[Address];
5908     if (!N.getNode() && isa<Argument>(Address))
5909       // Check unused arguments map.
5910       N = UnusedArgNodeMap[Address];
5911     SDDbgValue *SDV;
5912     if (N.getNode()) {
5913       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5914         Address = BCI->getOperand(0);
5915       // Parameters are handled specially.
5916       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5917       if (isParameter && FINode) {
5918         // Byval parameter. We have a frame index at this point.
5919         SDV =
5920             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5921                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5922       } else if (isa<Argument>(Address)) {
5923         // Address is an argument, so try to emit its dbg value using
5924         // virtual register info from the FuncInfo.ValueMap.
5925         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5926         return;
5927       } else {
5928         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5929                               true, dl, SDNodeOrder);
5930       }
5931       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5932     } else {
5933       // If Address is an argument then try to emit its dbg value using
5934       // virtual register info from the FuncInfo.ValueMap.
5935       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5936                                     N)) {
5937         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5938                           << " (could not emit func-arg dbg_value)\n");
5939       }
5940     }
5941     return;
5942   }
5943   case Intrinsic::dbg_label: {
5944     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5945     DILabel *Label = DI.getLabel();
5946     assert(Label && "Missing label");
5947 
5948     SDDbgLabel *SDV;
5949     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5950     DAG.AddDbgLabel(SDV);
5951     return;
5952   }
5953   case Intrinsic::dbg_value: {
5954     const DbgValueInst &DI = cast<DbgValueInst>(I);
5955     assert(DI.getVariable() && "Missing variable");
5956 
5957     DILocalVariable *Variable = DI.getVariable();
5958     DIExpression *Expression = DI.getExpression();
5959     dropDanglingDebugInfo(Variable, Expression);
5960     const Value *V = DI.getValue();
5961     if (!V)
5962       return;
5963 
5964     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5965         SDNodeOrder))
5966       return;
5967 
5968     // TODO: Dangling debug info will eventually either be resolved or produce
5969     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5970     // between the original dbg.value location and its resolved DBG_VALUE, which
5971     // we should ideally fill with an extra Undef DBG_VALUE.
5972 
5973     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5974     return;
5975   }
5976 
5977   case Intrinsic::eh_typeid_for: {
5978     // Find the type id for the given typeinfo.
5979     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5980     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5981     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5982     setValue(&I, Res);
5983     return;
5984   }
5985 
5986   case Intrinsic::eh_return_i32:
5987   case Intrinsic::eh_return_i64:
5988     DAG.getMachineFunction().setCallsEHReturn(true);
5989     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5990                             MVT::Other,
5991                             getControlRoot(),
5992                             getValue(I.getArgOperand(0)),
5993                             getValue(I.getArgOperand(1))));
5994     return;
5995   case Intrinsic::eh_unwind_init:
5996     DAG.getMachineFunction().setCallsUnwindInit(true);
5997     return;
5998   case Intrinsic::eh_dwarf_cfa:
5999     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6000                              TLI.getPointerTy(DAG.getDataLayout()),
6001                              getValue(I.getArgOperand(0))));
6002     return;
6003   case Intrinsic::eh_sjlj_callsite: {
6004     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6005     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6006     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6007     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6008 
6009     MMI.setCurrentCallSite(CI->getZExtValue());
6010     return;
6011   }
6012   case Intrinsic::eh_sjlj_functioncontext: {
6013     // Get and store the index of the function context.
6014     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6015     AllocaInst *FnCtx =
6016       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6017     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6018     MFI.setFunctionContextIndex(FI);
6019     return;
6020   }
6021   case Intrinsic::eh_sjlj_setjmp: {
6022     SDValue Ops[2];
6023     Ops[0] = getRoot();
6024     Ops[1] = getValue(I.getArgOperand(0));
6025     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6026                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6027     setValue(&I, Op.getValue(0));
6028     DAG.setRoot(Op.getValue(1));
6029     return;
6030   }
6031   case Intrinsic::eh_sjlj_longjmp:
6032     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6033                             getRoot(), getValue(I.getArgOperand(0))));
6034     return;
6035   case Intrinsic::eh_sjlj_setup_dispatch:
6036     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6037                             getRoot()));
6038     return;
6039   case Intrinsic::masked_gather:
6040     visitMaskedGather(I);
6041     return;
6042   case Intrinsic::masked_load:
6043     visitMaskedLoad(I);
6044     return;
6045   case Intrinsic::masked_scatter:
6046     visitMaskedScatter(I);
6047     return;
6048   case Intrinsic::masked_store:
6049     visitMaskedStore(I);
6050     return;
6051   case Intrinsic::masked_expandload:
6052     visitMaskedLoad(I, true /* IsExpanding */);
6053     return;
6054   case Intrinsic::masked_compressstore:
6055     visitMaskedStore(I, true /* IsCompressing */);
6056     return;
6057   case Intrinsic::powi:
6058     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6059                             getValue(I.getArgOperand(1)), DAG));
6060     return;
6061   case Intrinsic::log:
6062     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6063     return;
6064   case Intrinsic::log2:
6065     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6066     return;
6067   case Intrinsic::log10:
6068     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6069     return;
6070   case Intrinsic::exp:
6071     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6072     return;
6073   case Intrinsic::exp2:
6074     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6075     return;
6076   case Intrinsic::pow:
6077     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6078                            getValue(I.getArgOperand(1)), DAG, TLI));
6079     return;
6080   case Intrinsic::sqrt:
6081   case Intrinsic::fabs:
6082   case Intrinsic::sin:
6083   case Intrinsic::cos:
6084   case Intrinsic::floor:
6085   case Intrinsic::ceil:
6086   case Intrinsic::trunc:
6087   case Intrinsic::rint:
6088   case Intrinsic::nearbyint:
6089   case Intrinsic::round:
6090   case Intrinsic::roundeven:
6091   case Intrinsic::canonicalize: {
6092     unsigned Opcode;
6093     switch (Intrinsic) {
6094     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6095     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6096     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6097     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6098     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6099     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6100     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6101     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6102     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6103     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6104     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6105     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6106     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6107     }
6108 
6109     setValue(&I, DAG.getNode(Opcode, sdl,
6110                              getValue(I.getArgOperand(0)).getValueType(),
6111                              getValue(I.getArgOperand(0))));
6112     return;
6113   }
6114   case Intrinsic::lround:
6115   case Intrinsic::llround:
6116   case Intrinsic::lrint:
6117   case Intrinsic::llrint: {
6118     unsigned Opcode;
6119     switch (Intrinsic) {
6120     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6121     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6122     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6123     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6124     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6125     }
6126 
6127     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6128     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6129                              getValue(I.getArgOperand(0))));
6130     return;
6131   }
6132   case Intrinsic::minnum:
6133     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6134                              getValue(I.getArgOperand(0)).getValueType(),
6135                              getValue(I.getArgOperand(0)),
6136                              getValue(I.getArgOperand(1))));
6137     return;
6138   case Intrinsic::maxnum:
6139     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6140                              getValue(I.getArgOperand(0)).getValueType(),
6141                              getValue(I.getArgOperand(0)),
6142                              getValue(I.getArgOperand(1))));
6143     return;
6144   case Intrinsic::minimum:
6145     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6146                              getValue(I.getArgOperand(0)).getValueType(),
6147                              getValue(I.getArgOperand(0)),
6148                              getValue(I.getArgOperand(1))));
6149     return;
6150   case Intrinsic::maximum:
6151     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6152                              getValue(I.getArgOperand(0)).getValueType(),
6153                              getValue(I.getArgOperand(0)),
6154                              getValue(I.getArgOperand(1))));
6155     return;
6156   case Intrinsic::copysign:
6157     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6158                              getValue(I.getArgOperand(0)).getValueType(),
6159                              getValue(I.getArgOperand(0)),
6160                              getValue(I.getArgOperand(1))));
6161     return;
6162   case Intrinsic::fma:
6163     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6164                              getValue(I.getArgOperand(0)).getValueType(),
6165                              getValue(I.getArgOperand(0)),
6166                              getValue(I.getArgOperand(1)),
6167                              getValue(I.getArgOperand(2))));
6168     return;
6169 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6170   case Intrinsic::INTRINSIC:
6171 #include "llvm/IR/ConstrainedOps.def"
6172     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6173     return;
6174   case Intrinsic::fmuladd: {
6175     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6176     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6177         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6178       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6179                                getValue(I.getArgOperand(0)).getValueType(),
6180                                getValue(I.getArgOperand(0)),
6181                                getValue(I.getArgOperand(1)),
6182                                getValue(I.getArgOperand(2))));
6183     } else {
6184       // TODO: Intrinsic calls should have fast-math-flags.
6185       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6186                                 getValue(I.getArgOperand(0)).getValueType(),
6187                                 getValue(I.getArgOperand(0)),
6188                                 getValue(I.getArgOperand(1)));
6189       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6190                                 getValue(I.getArgOperand(0)).getValueType(),
6191                                 Mul,
6192                                 getValue(I.getArgOperand(2)));
6193       setValue(&I, Add);
6194     }
6195     return;
6196   }
6197   case Intrinsic::convert_to_fp16:
6198     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6199                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6200                                          getValue(I.getArgOperand(0)),
6201                                          DAG.getTargetConstant(0, sdl,
6202                                                                MVT::i32))));
6203     return;
6204   case Intrinsic::convert_from_fp16:
6205     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6206                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6207                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6208                                          getValue(I.getArgOperand(0)))));
6209     return;
6210   case Intrinsic::pcmarker: {
6211     SDValue Tmp = getValue(I.getArgOperand(0));
6212     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6213     return;
6214   }
6215   case Intrinsic::readcyclecounter: {
6216     SDValue Op = getRoot();
6217     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6218                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6219     setValue(&I, Res);
6220     DAG.setRoot(Res.getValue(1));
6221     return;
6222   }
6223   case Intrinsic::bitreverse:
6224     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6225                              getValue(I.getArgOperand(0)).getValueType(),
6226                              getValue(I.getArgOperand(0))));
6227     return;
6228   case Intrinsic::bswap:
6229     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6230                              getValue(I.getArgOperand(0)).getValueType(),
6231                              getValue(I.getArgOperand(0))));
6232     return;
6233   case Intrinsic::cttz: {
6234     SDValue Arg = getValue(I.getArgOperand(0));
6235     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6236     EVT Ty = Arg.getValueType();
6237     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6238                              sdl, Ty, Arg));
6239     return;
6240   }
6241   case Intrinsic::ctlz: {
6242     SDValue Arg = getValue(I.getArgOperand(0));
6243     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6244     EVT Ty = Arg.getValueType();
6245     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6246                              sdl, Ty, Arg));
6247     return;
6248   }
6249   case Intrinsic::ctpop: {
6250     SDValue Arg = getValue(I.getArgOperand(0));
6251     EVT Ty = Arg.getValueType();
6252     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6253     return;
6254   }
6255   case Intrinsic::fshl:
6256   case Intrinsic::fshr: {
6257     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6258     SDValue X = getValue(I.getArgOperand(0));
6259     SDValue Y = getValue(I.getArgOperand(1));
6260     SDValue Z = getValue(I.getArgOperand(2));
6261     EVT VT = X.getValueType();
6262     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6263     SDValue Zero = DAG.getConstant(0, sdl, VT);
6264     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6265 
6266     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6267     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6268       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6269       return;
6270     }
6271 
6272     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6273     // avoid the select that is necessary in the general case to filter out
6274     // the 0-shift possibility that leads to UB.
6275     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6276       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6277       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6278         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6279         return;
6280       }
6281 
6282       // Some targets only rotate one way. Try the opposite direction.
6283       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6284       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6285         // Negate the shift amount because it is safe to ignore the high bits.
6286         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6287         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6288         return;
6289       }
6290 
6291       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6292       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6293       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6294       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6295       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6296       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6297       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6298       return;
6299     }
6300 
6301     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6302     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6303     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6304     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6305     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6306     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6307 
6308     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6309     // and that is undefined. We must compare and select to avoid UB.
6310     EVT CCVT = MVT::i1;
6311     if (VT.isVector())
6312       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6313 
6314     // For fshl, 0-shift returns the 1st arg (X).
6315     // For fshr, 0-shift returns the 2nd arg (Y).
6316     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6317     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6318     return;
6319   }
6320   case Intrinsic::sadd_sat: {
6321     SDValue Op1 = getValue(I.getArgOperand(0));
6322     SDValue Op2 = getValue(I.getArgOperand(1));
6323     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6324     return;
6325   }
6326   case Intrinsic::uadd_sat: {
6327     SDValue Op1 = getValue(I.getArgOperand(0));
6328     SDValue Op2 = getValue(I.getArgOperand(1));
6329     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6330     return;
6331   }
6332   case Intrinsic::ssub_sat: {
6333     SDValue Op1 = getValue(I.getArgOperand(0));
6334     SDValue Op2 = getValue(I.getArgOperand(1));
6335     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6336     return;
6337   }
6338   case Intrinsic::usub_sat: {
6339     SDValue Op1 = getValue(I.getArgOperand(0));
6340     SDValue Op2 = getValue(I.getArgOperand(1));
6341     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6342     return;
6343   }
6344   case Intrinsic::smul_fix:
6345   case Intrinsic::umul_fix:
6346   case Intrinsic::smul_fix_sat:
6347   case Intrinsic::umul_fix_sat: {
6348     SDValue Op1 = getValue(I.getArgOperand(0));
6349     SDValue Op2 = getValue(I.getArgOperand(1));
6350     SDValue Op3 = getValue(I.getArgOperand(2));
6351     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6352                              Op1.getValueType(), Op1, Op2, Op3));
6353     return;
6354   }
6355   case Intrinsic::sdiv_fix:
6356   case Intrinsic::udiv_fix:
6357   case Intrinsic::sdiv_fix_sat:
6358   case Intrinsic::udiv_fix_sat: {
6359     SDValue Op1 = getValue(I.getArgOperand(0));
6360     SDValue Op2 = getValue(I.getArgOperand(1));
6361     SDValue Op3 = getValue(I.getArgOperand(2));
6362     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6363                               Op1, Op2, Op3, DAG, TLI));
6364     return;
6365   }
6366   case Intrinsic::stacksave: {
6367     SDValue Op = getRoot();
6368     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6369     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6370     setValue(&I, Res);
6371     DAG.setRoot(Res.getValue(1));
6372     return;
6373   }
6374   case Intrinsic::stackrestore:
6375     Res = getValue(I.getArgOperand(0));
6376     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6377     return;
6378   case Intrinsic::get_dynamic_area_offset: {
6379     SDValue Op = getRoot();
6380     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6381     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6382     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6383     // target.
6384     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6385       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6386                          " intrinsic!");
6387     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6388                       Op);
6389     DAG.setRoot(Op);
6390     setValue(&I, Res);
6391     return;
6392   }
6393   case Intrinsic::stackguard: {
6394     MachineFunction &MF = DAG.getMachineFunction();
6395     const Module &M = *MF.getFunction().getParent();
6396     SDValue Chain = getRoot();
6397     if (TLI.useLoadStackGuardNode()) {
6398       Res = getLoadStackGuard(DAG, sdl, Chain);
6399     } else {
6400       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6401       const Value *Global = TLI.getSDagStackGuard(M);
6402       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6403       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6404                         MachinePointerInfo(Global, 0), Align,
6405                         MachineMemOperand::MOVolatile);
6406     }
6407     if (TLI.useStackGuardXorFP())
6408       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6409     DAG.setRoot(Chain);
6410     setValue(&I, Res);
6411     return;
6412   }
6413   case Intrinsic::stackprotector: {
6414     // Emit code into the DAG to store the stack guard onto the stack.
6415     MachineFunction &MF = DAG.getMachineFunction();
6416     MachineFrameInfo &MFI = MF.getFrameInfo();
6417     SDValue Src, Chain = getRoot();
6418 
6419     if (TLI.useLoadStackGuardNode())
6420       Src = getLoadStackGuard(DAG, sdl, Chain);
6421     else
6422       Src = getValue(I.getArgOperand(0));   // The guard's value.
6423 
6424     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6425 
6426     int FI = FuncInfo.StaticAllocaMap[Slot];
6427     MFI.setStackProtectorIndex(FI);
6428     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6429 
6430     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6431 
6432     // Store the stack protector onto the stack.
6433     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6434                                                  DAG.getMachineFunction(), FI),
6435                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6436     setValue(&I, Res);
6437     DAG.setRoot(Res);
6438     return;
6439   }
6440   case Intrinsic::objectsize:
6441     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6442 
6443   case Intrinsic::is_constant:
6444     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6445 
6446   case Intrinsic::annotation:
6447   case Intrinsic::ptr_annotation:
6448   case Intrinsic::launder_invariant_group:
6449   case Intrinsic::strip_invariant_group:
6450     // Drop the intrinsic, but forward the value
6451     setValue(&I, getValue(I.getOperand(0)));
6452     return;
6453   case Intrinsic::assume:
6454   case Intrinsic::var_annotation:
6455   case Intrinsic::sideeffect:
6456     // Discard annotate attributes, assumptions, and artificial side-effects.
6457     return;
6458 
6459   case Intrinsic::codeview_annotation: {
6460     // Emit a label associated with this metadata.
6461     MachineFunction &MF = DAG.getMachineFunction();
6462     MCSymbol *Label =
6463         MF.getMMI().getContext().createTempSymbol("annotation", true);
6464     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6465     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6466     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6467     DAG.setRoot(Res);
6468     return;
6469   }
6470 
6471   case Intrinsic::init_trampoline: {
6472     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6473 
6474     SDValue Ops[6];
6475     Ops[0] = getRoot();
6476     Ops[1] = getValue(I.getArgOperand(0));
6477     Ops[2] = getValue(I.getArgOperand(1));
6478     Ops[3] = getValue(I.getArgOperand(2));
6479     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6480     Ops[5] = DAG.getSrcValue(F);
6481 
6482     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6483 
6484     DAG.setRoot(Res);
6485     return;
6486   }
6487   case Intrinsic::adjust_trampoline:
6488     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6489                              TLI.getPointerTy(DAG.getDataLayout()),
6490                              getValue(I.getArgOperand(0))));
6491     return;
6492   case Intrinsic::gcroot: {
6493     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6494            "only valid in functions with gc specified, enforced by Verifier");
6495     assert(GFI && "implied by previous");
6496     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6497     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6498 
6499     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6500     GFI->addStackRoot(FI->getIndex(), TypeMap);
6501     return;
6502   }
6503   case Intrinsic::gcread:
6504   case Intrinsic::gcwrite:
6505     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6506   case Intrinsic::flt_rounds:
6507     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6508     setValue(&I, Res);
6509     DAG.setRoot(Res.getValue(1));
6510     return;
6511 
6512   case Intrinsic::expect:
6513     // Just replace __builtin_expect(exp, c) with EXP.
6514     setValue(&I, getValue(I.getArgOperand(0)));
6515     return;
6516 
6517   case Intrinsic::debugtrap:
6518   case Intrinsic::trap: {
6519     StringRef TrapFuncName =
6520         I.getAttributes()
6521             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6522             .getValueAsString();
6523     if (TrapFuncName.empty()) {
6524       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6525         ISD::TRAP : ISD::DEBUGTRAP;
6526       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6527       return;
6528     }
6529     TargetLowering::ArgListTy Args;
6530 
6531     TargetLowering::CallLoweringInfo CLI(DAG);
6532     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6533         CallingConv::C, I.getType(),
6534         DAG.getExternalSymbol(TrapFuncName.data(),
6535                               TLI.getPointerTy(DAG.getDataLayout())),
6536         std::move(Args));
6537 
6538     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6539     DAG.setRoot(Result.second);
6540     return;
6541   }
6542 
6543   case Intrinsic::uadd_with_overflow:
6544   case Intrinsic::sadd_with_overflow:
6545   case Intrinsic::usub_with_overflow:
6546   case Intrinsic::ssub_with_overflow:
6547   case Intrinsic::umul_with_overflow:
6548   case Intrinsic::smul_with_overflow: {
6549     ISD::NodeType Op;
6550     switch (Intrinsic) {
6551     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6552     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6553     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6554     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6555     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6556     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6557     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6558     }
6559     SDValue Op1 = getValue(I.getArgOperand(0));
6560     SDValue Op2 = getValue(I.getArgOperand(1));
6561 
6562     EVT ResultVT = Op1.getValueType();
6563     EVT OverflowVT = MVT::i1;
6564     if (ResultVT.isVector())
6565       OverflowVT = EVT::getVectorVT(
6566           *Context, OverflowVT, ResultVT.getVectorNumElements());
6567 
6568     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6569     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6570     return;
6571   }
6572   case Intrinsic::prefetch: {
6573     SDValue Ops[5];
6574     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6575     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6576     Ops[0] = DAG.getRoot();
6577     Ops[1] = getValue(I.getArgOperand(0));
6578     Ops[2] = getValue(I.getArgOperand(1));
6579     Ops[3] = getValue(I.getArgOperand(2));
6580     Ops[4] = getValue(I.getArgOperand(3));
6581     SDValue Result = DAG.getMemIntrinsicNode(
6582         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6583         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6584         /* align */ None, Flags);
6585 
6586     // Chain the prefetch in parallell with any pending loads, to stay out of
6587     // the way of later optimizations.
6588     PendingLoads.push_back(Result);
6589     Result = getRoot();
6590     DAG.setRoot(Result);
6591     return;
6592   }
6593   case Intrinsic::lifetime_start:
6594   case Intrinsic::lifetime_end: {
6595     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6596     // Stack coloring is not enabled in O0, discard region information.
6597     if (TM.getOptLevel() == CodeGenOpt::None)
6598       return;
6599 
6600     const int64_t ObjectSize =
6601         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6602     Value *const ObjectPtr = I.getArgOperand(1);
6603     SmallVector<const Value *, 4> Allocas;
6604     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6605 
6606     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6607            E = Allocas.end(); Object != E; ++Object) {
6608       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6609 
6610       // Could not find an Alloca.
6611       if (!LifetimeObject)
6612         continue;
6613 
6614       // First check that the Alloca is static, otherwise it won't have a
6615       // valid frame index.
6616       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6617       if (SI == FuncInfo.StaticAllocaMap.end())
6618         return;
6619 
6620       const int FrameIndex = SI->second;
6621       int64_t Offset;
6622       if (GetPointerBaseWithConstantOffset(
6623               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6624         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6625       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6626                                 Offset);
6627       DAG.setRoot(Res);
6628     }
6629     return;
6630   }
6631   case Intrinsic::invariant_start:
6632     // Discard region information.
6633     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6634     return;
6635   case Intrinsic::invariant_end:
6636     // Discard region information.
6637     return;
6638   case Intrinsic::clear_cache:
6639     /// FunctionName may be null.
6640     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6641       lowerCallToExternalSymbol(I, FunctionName);
6642     return;
6643   case Intrinsic::donothing:
6644     // ignore
6645     return;
6646   case Intrinsic::experimental_stackmap:
6647     visitStackmap(I);
6648     return;
6649   case Intrinsic::experimental_patchpoint_void:
6650   case Intrinsic::experimental_patchpoint_i64:
6651     visitPatchpoint(I);
6652     return;
6653   case Intrinsic::experimental_gc_statepoint:
6654     LowerStatepoint(cast<GCStatepointInst>(I));
6655     return;
6656   case Intrinsic::experimental_gc_result:
6657     visitGCResult(cast<GCResultInst>(I));
6658     return;
6659   case Intrinsic::experimental_gc_relocate:
6660     visitGCRelocate(cast<GCRelocateInst>(I));
6661     return;
6662   case Intrinsic::instrprof_increment:
6663     llvm_unreachable("instrprof failed to lower an increment");
6664   case Intrinsic::instrprof_value_profile:
6665     llvm_unreachable("instrprof failed to lower a value profiling call");
6666   case Intrinsic::localescape: {
6667     MachineFunction &MF = DAG.getMachineFunction();
6668     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6669 
6670     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6671     // is the same on all targets.
6672     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6673       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6674       if (isa<ConstantPointerNull>(Arg))
6675         continue; // Skip null pointers. They represent a hole in index space.
6676       AllocaInst *Slot = cast<AllocaInst>(Arg);
6677       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6678              "can only escape static allocas");
6679       int FI = FuncInfo.StaticAllocaMap[Slot];
6680       MCSymbol *FrameAllocSym =
6681           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6682               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6683       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6684               TII->get(TargetOpcode::LOCAL_ESCAPE))
6685           .addSym(FrameAllocSym)
6686           .addFrameIndex(FI);
6687     }
6688 
6689     return;
6690   }
6691 
6692   case Intrinsic::localrecover: {
6693     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6694     MachineFunction &MF = DAG.getMachineFunction();
6695 
6696     // Get the symbol that defines the frame offset.
6697     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6698     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6699     unsigned IdxVal =
6700         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6701     MCSymbol *FrameAllocSym =
6702         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6703             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6704 
6705     Value *FP = I.getArgOperand(1);
6706     SDValue FPVal = getValue(FP);
6707     EVT PtrVT = FPVal.getValueType();
6708 
6709     // Create a MCSymbol for the label to avoid any target lowering
6710     // that would make this PC relative.
6711     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6712     SDValue OffsetVal =
6713         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6714 
6715     // Add the offset to the FP.
6716     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6717     setValue(&I, Add);
6718 
6719     return;
6720   }
6721 
6722   case Intrinsic::eh_exceptionpointer:
6723   case Intrinsic::eh_exceptioncode: {
6724     // Get the exception pointer vreg, copy from it, and resize it to fit.
6725     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6726     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6727     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6728     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6729     SDValue N =
6730         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6731     if (Intrinsic == Intrinsic::eh_exceptioncode)
6732       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6733     setValue(&I, N);
6734     return;
6735   }
6736   case Intrinsic::xray_customevent: {
6737     // Here we want to make sure that the intrinsic behaves as if it has a
6738     // specific calling convention, and only for x86_64.
6739     // FIXME: Support other platforms later.
6740     const auto &Triple = DAG.getTarget().getTargetTriple();
6741     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6742       return;
6743 
6744     SDLoc DL = getCurSDLoc();
6745     SmallVector<SDValue, 8> Ops;
6746 
6747     // We want to say that we always want the arguments in registers.
6748     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6749     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6750     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6751     SDValue Chain = getRoot();
6752     Ops.push_back(LogEntryVal);
6753     Ops.push_back(StrSizeVal);
6754     Ops.push_back(Chain);
6755 
6756     // We need to enforce the calling convention for the callsite, so that
6757     // argument ordering is enforced correctly, and that register allocation can
6758     // see that some registers may be assumed clobbered and have to preserve
6759     // them across calls to the intrinsic.
6760     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6761                                            DL, NodeTys, Ops);
6762     SDValue patchableNode = SDValue(MN, 0);
6763     DAG.setRoot(patchableNode);
6764     setValue(&I, patchableNode);
6765     return;
6766   }
6767   case Intrinsic::xray_typedevent: {
6768     // Here we want to make sure that the intrinsic behaves as if it has a
6769     // specific calling convention, and only for x86_64.
6770     // FIXME: Support other platforms later.
6771     const auto &Triple = DAG.getTarget().getTargetTriple();
6772     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6773       return;
6774 
6775     SDLoc DL = getCurSDLoc();
6776     SmallVector<SDValue, 8> Ops;
6777 
6778     // We want to say that we always want the arguments in registers.
6779     // It's unclear to me how manipulating the selection DAG here forces callers
6780     // to provide arguments in registers instead of on the stack.
6781     SDValue LogTypeId = getValue(I.getArgOperand(0));
6782     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6783     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6784     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6785     SDValue Chain = getRoot();
6786     Ops.push_back(LogTypeId);
6787     Ops.push_back(LogEntryVal);
6788     Ops.push_back(StrSizeVal);
6789     Ops.push_back(Chain);
6790 
6791     // We need to enforce the calling convention for the callsite, so that
6792     // argument ordering is enforced correctly, and that register allocation can
6793     // see that some registers may be assumed clobbered and have to preserve
6794     // them across calls to the intrinsic.
6795     MachineSDNode *MN = DAG.getMachineNode(
6796         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6797     SDValue patchableNode = SDValue(MN, 0);
6798     DAG.setRoot(patchableNode);
6799     setValue(&I, patchableNode);
6800     return;
6801   }
6802   case Intrinsic::experimental_deoptimize:
6803     LowerDeoptimizeCall(&I);
6804     return;
6805 
6806   case Intrinsic::experimental_vector_reduce_v2_fadd:
6807   case Intrinsic::experimental_vector_reduce_v2_fmul:
6808   case Intrinsic::experimental_vector_reduce_add:
6809   case Intrinsic::experimental_vector_reduce_mul:
6810   case Intrinsic::experimental_vector_reduce_and:
6811   case Intrinsic::experimental_vector_reduce_or:
6812   case Intrinsic::experimental_vector_reduce_xor:
6813   case Intrinsic::experimental_vector_reduce_smax:
6814   case Intrinsic::experimental_vector_reduce_smin:
6815   case Intrinsic::experimental_vector_reduce_umax:
6816   case Intrinsic::experimental_vector_reduce_umin:
6817   case Intrinsic::experimental_vector_reduce_fmax:
6818   case Intrinsic::experimental_vector_reduce_fmin:
6819     visitVectorReduce(I, Intrinsic);
6820     return;
6821 
6822   case Intrinsic::icall_branch_funnel: {
6823     SmallVector<SDValue, 16> Ops;
6824     Ops.push_back(getValue(I.getArgOperand(0)));
6825 
6826     int64_t Offset;
6827     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6828         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6829     if (!Base)
6830       report_fatal_error(
6831           "llvm.icall.branch.funnel operand must be a GlobalValue");
6832     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6833 
6834     struct BranchFunnelTarget {
6835       int64_t Offset;
6836       SDValue Target;
6837     };
6838     SmallVector<BranchFunnelTarget, 8> Targets;
6839 
6840     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6841       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6842           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6843       if (ElemBase != Base)
6844         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6845                            "to the same GlobalValue");
6846 
6847       SDValue Val = getValue(I.getArgOperand(Op + 1));
6848       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6849       if (!GA)
6850         report_fatal_error(
6851             "llvm.icall.branch.funnel operand must be a GlobalValue");
6852       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6853                                      GA->getGlobal(), getCurSDLoc(),
6854                                      Val.getValueType(), GA->getOffset())});
6855     }
6856     llvm::sort(Targets,
6857                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6858                  return T1.Offset < T2.Offset;
6859                });
6860 
6861     for (auto &T : Targets) {
6862       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6863       Ops.push_back(T.Target);
6864     }
6865 
6866     Ops.push_back(DAG.getRoot()); // Chain
6867     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6868                                  getCurSDLoc(), MVT::Other, Ops),
6869               0);
6870     DAG.setRoot(N);
6871     setValue(&I, N);
6872     HasTailCall = true;
6873     return;
6874   }
6875 
6876   case Intrinsic::wasm_landingpad_index:
6877     // Information this intrinsic contained has been transferred to
6878     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6879     // delete it now.
6880     return;
6881 
6882   case Intrinsic::aarch64_settag:
6883   case Intrinsic::aarch64_settag_zero: {
6884     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6885     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6886     SDValue Val = TSI.EmitTargetCodeForSetTag(
6887         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6888         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6889         ZeroMemory);
6890     DAG.setRoot(Val);
6891     setValue(&I, Val);
6892     return;
6893   }
6894   case Intrinsic::ptrmask: {
6895     SDValue Ptr = getValue(I.getOperand(0));
6896     SDValue Const = getValue(I.getOperand(1));
6897 
6898     EVT PtrVT = Ptr.getValueType();
6899     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6900                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6901     return;
6902   }
6903   }
6904 }
6905 
6906 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6907     const ConstrainedFPIntrinsic &FPI) {
6908   SDLoc sdl = getCurSDLoc();
6909 
6910   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6911   SmallVector<EVT, 4> ValueVTs;
6912   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6913   ValueVTs.push_back(MVT::Other); // Out chain
6914 
6915   // We do not need to serialize constrained FP intrinsics against
6916   // each other or against (nonvolatile) loads, so they can be
6917   // chained like loads.
6918   SDValue Chain = DAG.getRoot();
6919   SmallVector<SDValue, 4> Opers;
6920   Opers.push_back(Chain);
6921   if (FPI.isUnaryOp()) {
6922     Opers.push_back(getValue(FPI.getArgOperand(0)));
6923   } else if (FPI.isTernaryOp()) {
6924     Opers.push_back(getValue(FPI.getArgOperand(0)));
6925     Opers.push_back(getValue(FPI.getArgOperand(1)));
6926     Opers.push_back(getValue(FPI.getArgOperand(2)));
6927   } else {
6928     Opers.push_back(getValue(FPI.getArgOperand(0)));
6929     Opers.push_back(getValue(FPI.getArgOperand(1)));
6930   }
6931 
6932   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6933     assert(Result.getNode()->getNumValues() == 2);
6934 
6935     // Push node to the appropriate list so that future instructions can be
6936     // chained up correctly.
6937     SDValue OutChain = Result.getValue(1);
6938     switch (EB) {
6939     case fp::ExceptionBehavior::ebIgnore:
6940       // The only reason why ebIgnore nodes still need to be chained is that
6941       // they might depend on the current rounding mode, and therefore must
6942       // not be moved across instruction that may change that mode.
6943       LLVM_FALLTHROUGH;
6944     case fp::ExceptionBehavior::ebMayTrap:
6945       // These must not be moved across calls or instructions that may change
6946       // floating-point exception masks.
6947       PendingConstrainedFP.push_back(OutChain);
6948       break;
6949     case fp::ExceptionBehavior::ebStrict:
6950       // These must not be moved across calls or instructions that may change
6951       // floating-point exception masks or read floating-point exception flags.
6952       // In addition, they cannot be optimized out even if unused.
6953       PendingConstrainedFPStrict.push_back(OutChain);
6954       break;
6955     }
6956   };
6957 
6958   SDVTList VTs = DAG.getVTList(ValueVTs);
6959   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
6960 
6961   SDNodeFlags Flags;
6962   if (EB == fp::ExceptionBehavior::ebIgnore)
6963     Flags.setNoFPExcept(true);
6964 
6965   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
6966     Flags.copyFMF(*FPOp);
6967 
6968   unsigned Opcode;
6969   switch (FPI.getIntrinsicID()) {
6970   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6971 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
6972   case Intrinsic::INTRINSIC:                                                   \
6973     Opcode = ISD::STRICT_##DAGN;                                               \
6974     break;
6975 #include "llvm/IR/ConstrainedOps.def"
6976   case Intrinsic::experimental_constrained_fmuladd: {
6977     Opcode = ISD::STRICT_FMA;
6978     // Break fmuladd into fmul and fadd.
6979     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
6980         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
6981                                         ValueVTs[0])) {
6982       Opers.pop_back();
6983       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
6984       pushOutChain(Mul, EB);
6985       Opcode = ISD::STRICT_FADD;
6986       Opers.clear();
6987       Opers.push_back(Mul.getValue(1));
6988       Opers.push_back(Mul.getValue(0));
6989       Opers.push_back(getValue(FPI.getArgOperand(2)));
6990     }
6991     break;
6992   }
6993   }
6994 
6995   // A few strict DAG nodes carry additional operands that are not
6996   // set up by the default code above.
6997   switch (Opcode) {
6998   default: break;
6999   case ISD::STRICT_FP_ROUND:
7000     Opers.push_back(
7001         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7002     break;
7003   case ISD::STRICT_FSETCC:
7004   case ISD::STRICT_FSETCCS: {
7005     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7006     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7007     break;
7008   }
7009   }
7010 
7011   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7012   pushOutChain(Result, EB);
7013 
7014   SDValue FPResult = Result.getValue(0);
7015   setValue(&FPI, FPResult);
7016 }
7017 
7018 std::pair<SDValue, SDValue>
7019 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7020                                     const BasicBlock *EHPadBB) {
7021   MachineFunction &MF = DAG.getMachineFunction();
7022   MachineModuleInfo &MMI = MF.getMMI();
7023   MCSymbol *BeginLabel = nullptr;
7024 
7025   if (EHPadBB) {
7026     // Insert a label before the invoke call to mark the try range.  This can be
7027     // used to detect deletion of the invoke via the MachineModuleInfo.
7028     BeginLabel = MMI.getContext().createTempSymbol();
7029 
7030     // For SjLj, keep track of which landing pads go with which invokes
7031     // so as to maintain the ordering of pads in the LSDA.
7032     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7033     if (CallSiteIndex) {
7034       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7035       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7036 
7037       // Now that the call site is handled, stop tracking it.
7038       MMI.setCurrentCallSite(0);
7039     }
7040 
7041     // Both PendingLoads and PendingExports must be flushed here;
7042     // this call might not return.
7043     (void)getRoot();
7044     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7045 
7046     CLI.setChain(getRoot());
7047   }
7048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7049   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7050 
7051   assert((CLI.IsTailCall || Result.second.getNode()) &&
7052          "Non-null chain expected with non-tail call!");
7053   assert((Result.second.getNode() || !Result.first.getNode()) &&
7054          "Null value expected with tail call!");
7055 
7056   if (!Result.second.getNode()) {
7057     // As a special case, a null chain means that a tail call has been emitted
7058     // and the DAG root is already updated.
7059     HasTailCall = true;
7060 
7061     // Since there's no actual continuation from this block, nothing can be
7062     // relying on us setting vregs for them.
7063     PendingExports.clear();
7064   } else {
7065     DAG.setRoot(Result.second);
7066   }
7067 
7068   if (EHPadBB) {
7069     // Insert a label at the end of the invoke call to mark the try range.  This
7070     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7071     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7072     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7073 
7074     // Inform MachineModuleInfo of range.
7075     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7076     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7077     // actually use outlined funclets and their LSDA info style.
7078     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7079       assert(CLI.CB);
7080       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7081       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7082     } else if (!isScopedEHPersonality(Pers)) {
7083       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7084     }
7085   }
7086 
7087   return Result;
7088 }
7089 
7090 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7091                                       bool isTailCall,
7092                                       const BasicBlock *EHPadBB) {
7093   auto &DL = DAG.getDataLayout();
7094   FunctionType *FTy = CB.getFunctionType();
7095   Type *RetTy = CB.getType();
7096 
7097   TargetLowering::ArgListTy Args;
7098   Args.reserve(CB.arg_size());
7099 
7100   const Value *SwiftErrorVal = nullptr;
7101   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7102 
7103   if (isTailCall) {
7104     // Avoid emitting tail calls in functions with the disable-tail-calls
7105     // attribute.
7106     auto *Caller = CB.getParent()->getParent();
7107     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7108         "true")
7109       isTailCall = false;
7110 
7111     // We can't tail call inside a function with a swifterror argument. Lowering
7112     // does not support this yet. It would have to move into the swifterror
7113     // register before the call.
7114     if (TLI.supportSwiftError() &&
7115         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7116       isTailCall = false;
7117   }
7118 
7119   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7120     TargetLowering::ArgListEntry Entry;
7121     const Value *V = *I;
7122 
7123     // Skip empty types
7124     if (V->getType()->isEmptyTy())
7125       continue;
7126 
7127     SDValue ArgNode = getValue(V);
7128     Entry.Node = ArgNode; Entry.Ty = V->getType();
7129 
7130     Entry.setAttributes(&CB, I - CB.arg_begin());
7131 
7132     // Use swifterror virtual register as input to the call.
7133     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7134       SwiftErrorVal = V;
7135       // We find the virtual register for the actual swifterror argument.
7136       // Instead of using the Value, we use the virtual register instead.
7137       Entry.Node =
7138           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7139                           EVT(TLI.getPointerTy(DL)));
7140     }
7141 
7142     Args.push_back(Entry);
7143 
7144     // If we have an explicit sret argument that is an Instruction, (i.e., it
7145     // might point to function-local memory), we can't meaningfully tail-call.
7146     if (Entry.IsSRet && isa<Instruction>(V))
7147       isTailCall = false;
7148   }
7149 
7150   // If call site has a cfguardtarget operand bundle, create and add an
7151   // additional ArgListEntry.
7152   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7153     TargetLowering::ArgListEntry Entry;
7154     Value *V = Bundle->Inputs[0];
7155     SDValue ArgNode = getValue(V);
7156     Entry.Node = ArgNode;
7157     Entry.Ty = V->getType();
7158     Entry.IsCFGuardTarget = true;
7159     Args.push_back(Entry);
7160   }
7161 
7162   // Check if target-independent constraints permit a tail call here.
7163   // Target-dependent constraints are checked within TLI->LowerCallTo.
7164   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7165     isTailCall = false;
7166 
7167   // Disable tail calls if there is an swifterror argument. Targets have not
7168   // been updated to support tail calls.
7169   if (TLI.supportSwiftError() && SwiftErrorVal)
7170     isTailCall = false;
7171 
7172   TargetLowering::CallLoweringInfo CLI(DAG);
7173   CLI.setDebugLoc(getCurSDLoc())
7174       .setChain(getRoot())
7175       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7176       .setTailCall(isTailCall)
7177       .setConvergent(CB.isConvergent())
7178       .setIsPreallocated(
7179           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7180   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7181 
7182   if (Result.first.getNode()) {
7183     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7184     setValue(&CB, Result.first);
7185   }
7186 
7187   // The last element of CLI.InVals has the SDValue for swifterror return.
7188   // Here we copy it to a virtual register and update SwiftErrorMap for
7189   // book-keeping.
7190   if (SwiftErrorVal && TLI.supportSwiftError()) {
7191     // Get the last element of InVals.
7192     SDValue Src = CLI.InVals.back();
7193     Register VReg =
7194         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7195     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7196     DAG.setRoot(CopyNode);
7197   }
7198 }
7199 
7200 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7201                              SelectionDAGBuilder &Builder) {
7202   // Check to see if this load can be trivially constant folded, e.g. if the
7203   // input is from a string literal.
7204   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7205     // Cast pointer to the type we really want to load.
7206     Type *LoadTy =
7207         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7208     if (LoadVT.isVector())
7209       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7210 
7211     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7212                                          PointerType::getUnqual(LoadTy));
7213 
7214     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7215             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7216       return Builder.getValue(LoadCst);
7217   }
7218 
7219   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7220   // still constant memory, the input chain can be the entry node.
7221   SDValue Root;
7222   bool ConstantMemory = false;
7223 
7224   // Do not serialize (non-volatile) loads of constant memory with anything.
7225   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7226     Root = Builder.DAG.getEntryNode();
7227     ConstantMemory = true;
7228   } else {
7229     // Do not serialize non-volatile loads against each other.
7230     Root = Builder.DAG.getRoot();
7231   }
7232 
7233   SDValue Ptr = Builder.getValue(PtrVal);
7234   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7235                                         Ptr, MachinePointerInfo(PtrVal),
7236                                         /* Alignment = */ 1);
7237 
7238   if (!ConstantMemory)
7239     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7240   return LoadVal;
7241 }
7242 
7243 /// Record the value for an instruction that produces an integer result,
7244 /// converting the type where necessary.
7245 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7246                                                   SDValue Value,
7247                                                   bool IsSigned) {
7248   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7249                                                     I.getType(), true);
7250   if (IsSigned)
7251     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7252   else
7253     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7254   setValue(&I, Value);
7255 }
7256 
7257 /// See if we can lower a memcmp call into an optimized form. If so, return
7258 /// true and lower it. Otherwise return false, and it will be lowered like a
7259 /// normal call.
7260 /// The caller already checked that \p I calls the appropriate LibFunc with a
7261 /// correct prototype.
7262 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7263   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7264   const Value *Size = I.getArgOperand(2);
7265   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7266   if (CSize && CSize->getZExtValue() == 0) {
7267     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7268                                                           I.getType(), true);
7269     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7270     return true;
7271   }
7272 
7273   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7274   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7275       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7276       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7277   if (Res.first.getNode()) {
7278     processIntegerCallValue(I, Res.first, true);
7279     PendingLoads.push_back(Res.second);
7280     return true;
7281   }
7282 
7283   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7284   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7285   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7286     return false;
7287 
7288   // If the target has a fast compare for the given size, it will return a
7289   // preferred load type for that size. Require that the load VT is legal and
7290   // that the target supports unaligned loads of that type. Otherwise, return
7291   // INVALID.
7292   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7293     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7294     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7295     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7296       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7297       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7298       // TODO: Check alignment of src and dest ptrs.
7299       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7300       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7301       if (!TLI.isTypeLegal(LVT) ||
7302           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7303           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7304         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7305     }
7306 
7307     return LVT;
7308   };
7309 
7310   // This turns into unaligned loads. We only do this if the target natively
7311   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7312   // we'll only produce a small number of byte loads.
7313   MVT LoadVT;
7314   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7315   switch (NumBitsToCompare) {
7316   default:
7317     return false;
7318   case 16:
7319     LoadVT = MVT::i16;
7320     break;
7321   case 32:
7322     LoadVT = MVT::i32;
7323     break;
7324   case 64:
7325   case 128:
7326   case 256:
7327     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7328     break;
7329   }
7330 
7331   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7332     return false;
7333 
7334   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7335   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7336 
7337   // Bitcast to a wide integer type if the loads are vectors.
7338   if (LoadVT.isVector()) {
7339     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7340     LoadL = DAG.getBitcast(CmpVT, LoadL);
7341     LoadR = DAG.getBitcast(CmpVT, LoadR);
7342   }
7343 
7344   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7345   processIntegerCallValue(I, Cmp, false);
7346   return true;
7347 }
7348 
7349 /// See if we can lower a memchr call into an optimized form. If so, return
7350 /// true and lower it. Otherwise return false, and it will be lowered like a
7351 /// normal call.
7352 /// The caller already checked that \p I calls the appropriate LibFunc with a
7353 /// correct prototype.
7354 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7355   const Value *Src = I.getArgOperand(0);
7356   const Value *Char = I.getArgOperand(1);
7357   const Value *Length = I.getArgOperand(2);
7358 
7359   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7360   std::pair<SDValue, SDValue> Res =
7361     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7362                                 getValue(Src), getValue(Char), getValue(Length),
7363                                 MachinePointerInfo(Src));
7364   if (Res.first.getNode()) {
7365     setValue(&I, Res.first);
7366     PendingLoads.push_back(Res.second);
7367     return true;
7368   }
7369 
7370   return false;
7371 }
7372 
7373 /// See if we can lower a mempcpy call into an optimized form. If so, return
7374 /// true and lower it. Otherwise return false, and it will be lowered like a
7375 /// normal call.
7376 /// The caller already checked that \p I calls the appropriate LibFunc with a
7377 /// correct prototype.
7378 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7379   SDValue Dst = getValue(I.getArgOperand(0));
7380   SDValue Src = getValue(I.getArgOperand(1));
7381   SDValue Size = getValue(I.getArgOperand(2));
7382 
7383   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7384   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7385   // DAG::getMemcpy needs Alignment to be defined.
7386   Align Alignment = std::min(DstAlign, SrcAlign);
7387 
7388   bool isVol = false;
7389   SDLoc sdl = getCurSDLoc();
7390 
7391   // In the mempcpy context we need to pass in a false value for isTailCall
7392   // because the return pointer needs to be adjusted by the size of
7393   // the copied memory.
7394   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7395   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7396                              /*isTailCall=*/false,
7397                              MachinePointerInfo(I.getArgOperand(0)),
7398                              MachinePointerInfo(I.getArgOperand(1)));
7399   assert(MC.getNode() != nullptr &&
7400          "** memcpy should not be lowered as TailCall in mempcpy context **");
7401   DAG.setRoot(MC);
7402 
7403   // Check if Size needs to be truncated or extended.
7404   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7405 
7406   // Adjust return pointer to point just past the last dst byte.
7407   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7408                                     Dst, Size);
7409   setValue(&I, DstPlusSize);
7410   return true;
7411 }
7412 
7413 /// See if we can lower a strcpy call into an optimized form.  If so, return
7414 /// true and lower it, otherwise return false and it will be lowered like a
7415 /// normal call.
7416 /// The caller already checked that \p I calls the appropriate LibFunc with a
7417 /// correct prototype.
7418 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7419   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7420 
7421   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7422   std::pair<SDValue, SDValue> Res =
7423     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7424                                 getValue(Arg0), getValue(Arg1),
7425                                 MachinePointerInfo(Arg0),
7426                                 MachinePointerInfo(Arg1), isStpcpy);
7427   if (Res.first.getNode()) {
7428     setValue(&I, Res.first);
7429     DAG.setRoot(Res.second);
7430     return true;
7431   }
7432 
7433   return false;
7434 }
7435 
7436 /// See if we can lower a strcmp call into an optimized form.  If so, return
7437 /// true and lower it, otherwise return false and it will be lowered like a
7438 /// normal call.
7439 /// The caller already checked that \p I calls the appropriate LibFunc with a
7440 /// correct prototype.
7441 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7442   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7443 
7444   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7445   std::pair<SDValue, SDValue> Res =
7446     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7447                                 getValue(Arg0), getValue(Arg1),
7448                                 MachinePointerInfo(Arg0),
7449                                 MachinePointerInfo(Arg1));
7450   if (Res.first.getNode()) {
7451     processIntegerCallValue(I, Res.first, true);
7452     PendingLoads.push_back(Res.second);
7453     return true;
7454   }
7455 
7456   return false;
7457 }
7458 
7459 /// See if we can lower a strlen call into an optimized form.  If so, return
7460 /// true and lower it, otherwise return false and it will be lowered like a
7461 /// normal call.
7462 /// The caller already checked that \p I calls the appropriate LibFunc with a
7463 /// correct prototype.
7464 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7465   const Value *Arg0 = I.getArgOperand(0);
7466 
7467   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7468   std::pair<SDValue, SDValue> Res =
7469     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7470                                 getValue(Arg0), MachinePointerInfo(Arg0));
7471   if (Res.first.getNode()) {
7472     processIntegerCallValue(I, Res.first, false);
7473     PendingLoads.push_back(Res.second);
7474     return true;
7475   }
7476 
7477   return false;
7478 }
7479 
7480 /// See if we can lower a strnlen call into an optimized form.  If so, return
7481 /// true and lower it, otherwise return false and it will be lowered like a
7482 /// normal call.
7483 /// The caller already checked that \p I calls the appropriate LibFunc with a
7484 /// correct prototype.
7485 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7486   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7487 
7488   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7489   std::pair<SDValue, SDValue> Res =
7490     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7491                                  getValue(Arg0), getValue(Arg1),
7492                                  MachinePointerInfo(Arg0));
7493   if (Res.first.getNode()) {
7494     processIntegerCallValue(I, Res.first, false);
7495     PendingLoads.push_back(Res.second);
7496     return true;
7497   }
7498 
7499   return false;
7500 }
7501 
7502 /// See if we can lower a unary floating-point operation into an SDNode with
7503 /// the specified Opcode.  If so, return true and lower it, otherwise return
7504 /// false and it will be lowered like a normal call.
7505 /// The caller already checked that \p I calls the appropriate LibFunc with a
7506 /// correct prototype.
7507 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7508                                               unsigned Opcode) {
7509   // We already checked this call's prototype; verify it doesn't modify errno.
7510   if (!I.onlyReadsMemory())
7511     return false;
7512 
7513   SDValue Tmp = getValue(I.getArgOperand(0));
7514   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7515   return true;
7516 }
7517 
7518 /// See if we can lower a binary floating-point operation into an SDNode with
7519 /// the specified Opcode. If so, return true and lower it. Otherwise return
7520 /// false, and it will be lowered like a normal call.
7521 /// The caller already checked that \p I calls the appropriate LibFunc with a
7522 /// correct prototype.
7523 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7524                                                unsigned Opcode) {
7525   // We already checked this call's prototype; verify it doesn't modify errno.
7526   if (!I.onlyReadsMemory())
7527     return false;
7528 
7529   SDValue Tmp0 = getValue(I.getArgOperand(0));
7530   SDValue Tmp1 = getValue(I.getArgOperand(1));
7531   EVT VT = Tmp0.getValueType();
7532   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7533   return true;
7534 }
7535 
7536 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7537   // Handle inline assembly differently.
7538   if (I.isInlineAsm()) {
7539     visitInlineAsm(I);
7540     return;
7541   }
7542 
7543   if (Function *F = I.getCalledFunction()) {
7544     if (F->isDeclaration()) {
7545       // Is this an LLVM intrinsic or a target-specific intrinsic?
7546       unsigned IID = F->getIntrinsicID();
7547       if (!IID)
7548         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7549           IID = II->getIntrinsicID(F);
7550 
7551       if (IID) {
7552         visitIntrinsicCall(I, IID);
7553         return;
7554       }
7555     }
7556 
7557     // Check for well-known libc/libm calls.  If the function is internal, it
7558     // can't be a library call.  Don't do the check if marked as nobuiltin for
7559     // some reason or the call site requires strict floating point semantics.
7560     LibFunc Func;
7561     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7562         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7563         LibInfo->hasOptimizedCodeGen(Func)) {
7564       switch (Func) {
7565       default: break;
7566       case LibFunc_copysign:
7567       case LibFunc_copysignf:
7568       case LibFunc_copysignl:
7569         // We already checked this call's prototype; verify it doesn't modify
7570         // errno.
7571         if (I.onlyReadsMemory()) {
7572           SDValue LHS = getValue(I.getArgOperand(0));
7573           SDValue RHS = getValue(I.getArgOperand(1));
7574           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7575                                    LHS.getValueType(), LHS, RHS));
7576           return;
7577         }
7578         break;
7579       case LibFunc_fabs:
7580       case LibFunc_fabsf:
7581       case LibFunc_fabsl:
7582         if (visitUnaryFloatCall(I, ISD::FABS))
7583           return;
7584         break;
7585       case LibFunc_fmin:
7586       case LibFunc_fminf:
7587       case LibFunc_fminl:
7588         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7589           return;
7590         break;
7591       case LibFunc_fmax:
7592       case LibFunc_fmaxf:
7593       case LibFunc_fmaxl:
7594         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7595           return;
7596         break;
7597       case LibFunc_sin:
7598       case LibFunc_sinf:
7599       case LibFunc_sinl:
7600         if (visitUnaryFloatCall(I, ISD::FSIN))
7601           return;
7602         break;
7603       case LibFunc_cos:
7604       case LibFunc_cosf:
7605       case LibFunc_cosl:
7606         if (visitUnaryFloatCall(I, ISD::FCOS))
7607           return;
7608         break;
7609       case LibFunc_sqrt:
7610       case LibFunc_sqrtf:
7611       case LibFunc_sqrtl:
7612       case LibFunc_sqrt_finite:
7613       case LibFunc_sqrtf_finite:
7614       case LibFunc_sqrtl_finite:
7615         if (visitUnaryFloatCall(I, ISD::FSQRT))
7616           return;
7617         break;
7618       case LibFunc_floor:
7619       case LibFunc_floorf:
7620       case LibFunc_floorl:
7621         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7622           return;
7623         break;
7624       case LibFunc_nearbyint:
7625       case LibFunc_nearbyintf:
7626       case LibFunc_nearbyintl:
7627         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7628           return;
7629         break;
7630       case LibFunc_ceil:
7631       case LibFunc_ceilf:
7632       case LibFunc_ceill:
7633         if (visitUnaryFloatCall(I, ISD::FCEIL))
7634           return;
7635         break;
7636       case LibFunc_rint:
7637       case LibFunc_rintf:
7638       case LibFunc_rintl:
7639         if (visitUnaryFloatCall(I, ISD::FRINT))
7640           return;
7641         break;
7642       case LibFunc_round:
7643       case LibFunc_roundf:
7644       case LibFunc_roundl:
7645         if (visitUnaryFloatCall(I, ISD::FROUND))
7646           return;
7647         break;
7648       case LibFunc_trunc:
7649       case LibFunc_truncf:
7650       case LibFunc_truncl:
7651         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7652           return;
7653         break;
7654       case LibFunc_log2:
7655       case LibFunc_log2f:
7656       case LibFunc_log2l:
7657         if (visitUnaryFloatCall(I, ISD::FLOG2))
7658           return;
7659         break;
7660       case LibFunc_exp2:
7661       case LibFunc_exp2f:
7662       case LibFunc_exp2l:
7663         if (visitUnaryFloatCall(I, ISD::FEXP2))
7664           return;
7665         break;
7666       case LibFunc_memcmp:
7667         if (visitMemCmpCall(I))
7668           return;
7669         break;
7670       case LibFunc_mempcpy:
7671         if (visitMemPCpyCall(I))
7672           return;
7673         break;
7674       case LibFunc_memchr:
7675         if (visitMemChrCall(I))
7676           return;
7677         break;
7678       case LibFunc_strcpy:
7679         if (visitStrCpyCall(I, false))
7680           return;
7681         break;
7682       case LibFunc_stpcpy:
7683         if (visitStrCpyCall(I, true))
7684           return;
7685         break;
7686       case LibFunc_strcmp:
7687         if (visitStrCmpCall(I))
7688           return;
7689         break;
7690       case LibFunc_strlen:
7691         if (visitStrLenCall(I))
7692           return;
7693         break;
7694       case LibFunc_strnlen:
7695         if (visitStrNLenCall(I))
7696           return;
7697         break;
7698       }
7699     }
7700   }
7701 
7702   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7703   // have to do anything here to lower funclet bundles.
7704   // CFGuardTarget bundles are lowered in LowerCallTo.
7705   assert(!I.hasOperandBundlesOtherThan(
7706              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7707               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) &&
7708          "Cannot lower calls with arbitrary operand bundles!");
7709 
7710   SDValue Callee = getValue(I.getCalledOperand());
7711 
7712   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7713     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7714   else
7715     // Check if we can potentially perform a tail call. More detailed checking
7716     // is be done within LowerCallTo, after more information about the call is
7717     // known.
7718     LowerCallTo(I, Callee, I.isTailCall());
7719 }
7720 
7721 namespace {
7722 
7723 /// AsmOperandInfo - This contains information for each constraint that we are
7724 /// lowering.
7725 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7726 public:
7727   /// CallOperand - If this is the result output operand or a clobber
7728   /// this is null, otherwise it is the incoming operand to the CallInst.
7729   /// This gets modified as the asm is processed.
7730   SDValue CallOperand;
7731 
7732   /// AssignedRegs - If this is a register or register class operand, this
7733   /// contains the set of register corresponding to the operand.
7734   RegsForValue AssignedRegs;
7735 
7736   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7737     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7738   }
7739 
7740   /// Whether or not this operand accesses memory
7741   bool hasMemory(const TargetLowering &TLI) const {
7742     // Indirect operand accesses access memory.
7743     if (isIndirect)
7744       return true;
7745 
7746     for (const auto &Code : Codes)
7747       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7748         return true;
7749 
7750     return false;
7751   }
7752 
7753   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7754   /// corresponds to.  If there is no Value* for this operand, it returns
7755   /// MVT::Other.
7756   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7757                            const DataLayout &DL) const {
7758     if (!CallOperandVal) return MVT::Other;
7759 
7760     if (isa<BasicBlock>(CallOperandVal))
7761       return TLI.getProgramPointerTy(DL);
7762 
7763     llvm::Type *OpTy = CallOperandVal->getType();
7764 
7765     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7766     // If this is an indirect operand, the operand is a pointer to the
7767     // accessed type.
7768     if (isIndirect) {
7769       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7770       if (!PtrTy)
7771         report_fatal_error("Indirect operand for inline asm not a pointer!");
7772       OpTy = PtrTy->getElementType();
7773     }
7774 
7775     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7776     if (StructType *STy = dyn_cast<StructType>(OpTy))
7777       if (STy->getNumElements() == 1)
7778         OpTy = STy->getElementType(0);
7779 
7780     // If OpTy is not a single value, it may be a struct/union that we
7781     // can tile with integers.
7782     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7783       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7784       switch (BitSize) {
7785       default: break;
7786       case 1:
7787       case 8:
7788       case 16:
7789       case 32:
7790       case 64:
7791       case 128:
7792         OpTy = IntegerType::get(Context, BitSize);
7793         break;
7794       }
7795     }
7796 
7797     return TLI.getValueType(DL, OpTy, true);
7798   }
7799 };
7800 
7801 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7802 
7803 } // end anonymous namespace
7804 
7805 /// Make sure that the output operand \p OpInfo and its corresponding input
7806 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7807 /// out).
7808 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7809                                SDISelAsmOperandInfo &MatchingOpInfo,
7810                                SelectionDAG &DAG) {
7811   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7812     return;
7813 
7814   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7815   const auto &TLI = DAG.getTargetLoweringInfo();
7816 
7817   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7818       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7819                                        OpInfo.ConstraintVT);
7820   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7821       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7822                                        MatchingOpInfo.ConstraintVT);
7823   if ((OpInfo.ConstraintVT.isInteger() !=
7824        MatchingOpInfo.ConstraintVT.isInteger()) ||
7825       (MatchRC.second != InputRC.second)) {
7826     // FIXME: error out in a more elegant fashion
7827     report_fatal_error("Unsupported asm: input constraint"
7828                        " with a matching output constraint of"
7829                        " incompatible type!");
7830   }
7831   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7832 }
7833 
7834 /// Get a direct memory input to behave well as an indirect operand.
7835 /// This may introduce stores, hence the need for a \p Chain.
7836 /// \return The (possibly updated) chain.
7837 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7838                                         SDISelAsmOperandInfo &OpInfo,
7839                                         SelectionDAG &DAG) {
7840   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7841 
7842   // If we don't have an indirect input, put it in the constpool if we can,
7843   // otherwise spill it to a stack slot.
7844   // TODO: This isn't quite right. We need to handle these according to
7845   // the addressing mode that the constraint wants. Also, this may take
7846   // an additional register for the computation and we don't want that
7847   // either.
7848 
7849   // If the operand is a float, integer, or vector constant, spill to a
7850   // constant pool entry to get its address.
7851   const Value *OpVal = OpInfo.CallOperandVal;
7852   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7853       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7854     OpInfo.CallOperand = DAG.getConstantPool(
7855         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7856     return Chain;
7857   }
7858 
7859   // Otherwise, create a stack slot and emit a store to it before the asm.
7860   Type *Ty = OpVal->getType();
7861   auto &DL = DAG.getDataLayout();
7862   uint64_t TySize = DL.getTypeAllocSize(Ty);
7863   unsigned Align = DL.getPrefTypeAlignment(Ty);
7864   MachineFunction &MF = DAG.getMachineFunction();
7865   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7866   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7867   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7868                             MachinePointerInfo::getFixedStack(MF, SSFI),
7869                             TLI.getMemValueType(DL, Ty));
7870   OpInfo.CallOperand = StackSlot;
7871 
7872   return Chain;
7873 }
7874 
7875 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7876 /// specified operand.  We prefer to assign virtual registers, to allow the
7877 /// register allocator to handle the assignment process.  However, if the asm
7878 /// uses features that we can't model on machineinstrs, we have SDISel do the
7879 /// allocation.  This produces generally horrible, but correct, code.
7880 ///
7881 ///   OpInfo describes the operand
7882 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7883 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7884                                  SDISelAsmOperandInfo &OpInfo,
7885                                  SDISelAsmOperandInfo &RefOpInfo) {
7886   LLVMContext &Context = *DAG.getContext();
7887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7888 
7889   MachineFunction &MF = DAG.getMachineFunction();
7890   SmallVector<unsigned, 4> Regs;
7891   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7892 
7893   // No work to do for memory operations.
7894   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7895     return;
7896 
7897   // If this is a constraint for a single physreg, or a constraint for a
7898   // register class, find it.
7899   unsigned AssignedReg;
7900   const TargetRegisterClass *RC;
7901   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7902       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7903   // RC is unset only on failure. Return immediately.
7904   if (!RC)
7905     return;
7906 
7907   // Get the actual register value type.  This is important, because the user
7908   // may have asked for (e.g.) the AX register in i32 type.  We need to
7909   // remember that AX is actually i16 to get the right extension.
7910   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7911 
7912   if (OpInfo.ConstraintVT != MVT::Other) {
7913     // If this is an FP operand in an integer register (or visa versa), or more
7914     // generally if the operand value disagrees with the register class we plan
7915     // to stick it in, fix the operand type.
7916     //
7917     // If this is an input value, the bitcast to the new type is done now.
7918     // Bitcast for output value is done at the end of visitInlineAsm().
7919     if ((OpInfo.Type == InlineAsm::isOutput ||
7920          OpInfo.Type == InlineAsm::isInput) &&
7921         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7922       // Try to convert to the first EVT that the reg class contains.  If the
7923       // types are identical size, use a bitcast to convert (e.g. two differing
7924       // vector types).  Note: output bitcast is done at the end of
7925       // visitInlineAsm().
7926       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7927         // Exclude indirect inputs while they are unsupported because the code
7928         // to perform the load is missing and thus OpInfo.CallOperand still
7929         // refers to the input address rather than the pointed-to value.
7930         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7931           OpInfo.CallOperand =
7932               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7933         OpInfo.ConstraintVT = RegVT;
7934         // If the operand is an FP value and we want it in integer registers,
7935         // use the corresponding integer type. This turns an f64 value into
7936         // i64, which can be passed with two i32 values on a 32-bit machine.
7937       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7938         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7939         if (OpInfo.Type == InlineAsm::isInput)
7940           OpInfo.CallOperand =
7941               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7942         OpInfo.ConstraintVT = VT;
7943       }
7944     }
7945   }
7946 
7947   // No need to allocate a matching input constraint since the constraint it's
7948   // matching to has already been allocated.
7949   if (OpInfo.isMatchingInputConstraint())
7950     return;
7951 
7952   EVT ValueVT = OpInfo.ConstraintVT;
7953   if (OpInfo.ConstraintVT == MVT::Other)
7954     ValueVT = RegVT;
7955 
7956   // Initialize NumRegs.
7957   unsigned NumRegs = 1;
7958   if (OpInfo.ConstraintVT != MVT::Other)
7959     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7960 
7961   // If this is a constraint for a specific physical register, like {r17},
7962   // assign it now.
7963 
7964   // If this associated to a specific register, initialize iterator to correct
7965   // place. If virtual, make sure we have enough registers
7966 
7967   // Initialize iterator if necessary
7968   TargetRegisterClass::iterator I = RC->begin();
7969   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7970 
7971   // Do not check for single registers.
7972   if (AssignedReg) {
7973       for (; *I != AssignedReg; ++I)
7974         assert(I != RC->end() && "AssignedReg should be member of RC");
7975   }
7976 
7977   for (; NumRegs; --NumRegs, ++I) {
7978     assert(I != RC->end() && "Ran out of registers to allocate!");
7979     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7980     Regs.push_back(R);
7981   }
7982 
7983   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7984 }
7985 
7986 static unsigned
7987 findMatchingInlineAsmOperand(unsigned OperandNo,
7988                              const std::vector<SDValue> &AsmNodeOperands) {
7989   // Scan until we find the definition we already emitted of this operand.
7990   unsigned CurOp = InlineAsm::Op_FirstOperand;
7991   for (; OperandNo; --OperandNo) {
7992     // Advance to the next operand.
7993     unsigned OpFlag =
7994         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7995     assert((InlineAsm::isRegDefKind(OpFlag) ||
7996             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7997             InlineAsm::isMemKind(OpFlag)) &&
7998            "Skipped past definitions?");
7999     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8000   }
8001   return CurOp;
8002 }
8003 
8004 namespace {
8005 
8006 class ExtraFlags {
8007   unsigned Flags = 0;
8008 
8009 public:
8010   explicit ExtraFlags(const CallBase &Call) {
8011     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8012     if (IA->hasSideEffects())
8013       Flags |= InlineAsm::Extra_HasSideEffects;
8014     if (IA->isAlignStack())
8015       Flags |= InlineAsm::Extra_IsAlignStack;
8016     if (Call.isConvergent())
8017       Flags |= InlineAsm::Extra_IsConvergent;
8018     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8019   }
8020 
8021   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8022     // Ideally, we would only check against memory constraints.  However, the
8023     // meaning of an Other constraint can be target-specific and we can't easily
8024     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8025     // for Other constraints as well.
8026     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8027         OpInfo.ConstraintType == TargetLowering::C_Other) {
8028       if (OpInfo.Type == InlineAsm::isInput)
8029         Flags |= InlineAsm::Extra_MayLoad;
8030       else if (OpInfo.Type == InlineAsm::isOutput)
8031         Flags |= InlineAsm::Extra_MayStore;
8032       else if (OpInfo.Type == InlineAsm::isClobber)
8033         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8034     }
8035   }
8036 
8037   unsigned get() const { return Flags; }
8038 };
8039 
8040 } // end anonymous namespace
8041 
8042 /// visitInlineAsm - Handle a call to an InlineAsm object.
8043 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8044   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8045 
8046   /// ConstraintOperands - Information about all of the constraints.
8047   SDISelAsmOperandInfoVector ConstraintOperands;
8048 
8049   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8050   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8051       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8052 
8053   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8054   // AsmDialect, MayLoad, MayStore).
8055   bool HasSideEffect = IA->hasSideEffects();
8056   ExtraFlags ExtraInfo(Call);
8057 
8058   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8059   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8060   unsigned NumMatchingOps = 0;
8061   for (auto &T : TargetConstraints) {
8062     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8063     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8064 
8065     // Compute the value type for each operand.
8066     if (OpInfo.Type == InlineAsm::isInput ||
8067         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8068       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8069 
8070       // Process the call argument. BasicBlocks are labels, currently appearing
8071       // only in asm's.
8072       if (isa<CallBrInst>(Call) &&
8073           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8074                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8075                         NumMatchingOps) &&
8076           (NumMatchingOps == 0 ||
8077            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8078                         NumMatchingOps))) {
8079         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8080         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8081         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8082       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8083         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8084       } else {
8085         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8086       }
8087 
8088       OpInfo.ConstraintVT =
8089           OpInfo
8090               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8091               .getSimpleVT();
8092     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8093       // The return value of the call is this value.  As such, there is no
8094       // corresponding argument.
8095       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8096       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8097         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8098             DAG.getDataLayout(), STy->getElementType(ResNo));
8099       } else {
8100         assert(ResNo == 0 && "Asm only has one result!");
8101         OpInfo.ConstraintVT =
8102             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8103       }
8104       ++ResNo;
8105     } else {
8106       OpInfo.ConstraintVT = MVT::Other;
8107     }
8108 
8109     if (OpInfo.hasMatchingInput())
8110       ++NumMatchingOps;
8111 
8112     if (!HasSideEffect)
8113       HasSideEffect = OpInfo.hasMemory(TLI);
8114 
8115     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8116     // FIXME: Could we compute this on OpInfo rather than T?
8117 
8118     // Compute the constraint code and ConstraintType to use.
8119     TLI.ComputeConstraintToUse(T, SDValue());
8120 
8121     if (T.ConstraintType == TargetLowering::C_Immediate &&
8122         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8123       // We've delayed emitting a diagnostic like the "n" constraint because
8124       // inlining could cause an integer showing up.
8125       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8126                                           "' expects an integer constant "
8127                                           "expression");
8128 
8129     ExtraInfo.update(T);
8130   }
8131 
8132 
8133   // We won't need to flush pending loads if this asm doesn't touch
8134   // memory and is nonvolatile.
8135   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8136 
8137   bool IsCallBr = isa<CallBrInst>(Call);
8138   if (IsCallBr) {
8139     // If this is a callbr we need to flush pending exports since inlineasm_br
8140     // is a terminator. We need to do this before nodes are glued to
8141     // the inlineasm_br node.
8142     Chain = getControlRoot();
8143   }
8144 
8145   // Second pass over the constraints: compute which constraint option to use.
8146   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8147     // If this is an output operand with a matching input operand, look up the
8148     // matching input. If their types mismatch, e.g. one is an integer, the
8149     // other is floating point, or their sizes are different, flag it as an
8150     // error.
8151     if (OpInfo.hasMatchingInput()) {
8152       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8153       patchMatchingInput(OpInfo, Input, DAG);
8154     }
8155 
8156     // Compute the constraint code and ConstraintType to use.
8157     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8158 
8159     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8160         OpInfo.Type == InlineAsm::isClobber)
8161       continue;
8162 
8163     // If this is a memory input, and if the operand is not indirect, do what we
8164     // need to provide an address for the memory input.
8165     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8166         !OpInfo.isIndirect) {
8167       assert((OpInfo.isMultipleAlternative ||
8168               (OpInfo.Type == InlineAsm::isInput)) &&
8169              "Can only indirectify direct input operands!");
8170 
8171       // Memory operands really want the address of the value.
8172       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8173 
8174       // There is no longer a Value* corresponding to this operand.
8175       OpInfo.CallOperandVal = nullptr;
8176 
8177       // It is now an indirect operand.
8178       OpInfo.isIndirect = true;
8179     }
8180 
8181   }
8182 
8183   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8184   std::vector<SDValue> AsmNodeOperands;
8185   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8186   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8187       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8188 
8189   // If we have a !srcloc metadata node associated with it, we want to attach
8190   // this to the ultimately generated inline asm machineinstr.  To do this, we
8191   // pass in the third operand as this (potentially null) inline asm MDNode.
8192   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8193   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8194 
8195   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8196   // bits as operand 3.
8197   AsmNodeOperands.push_back(DAG.getTargetConstant(
8198       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8199 
8200   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8201   // this, assign virtual and physical registers for inputs and otput.
8202   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8203     // Assign Registers.
8204     SDISelAsmOperandInfo &RefOpInfo =
8205         OpInfo.isMatchingInputConstraint()
8206             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8207             : OpInfo;
8208     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8209 
8210     auto DetectWriteToReservedRegister = [&]() {
8211       const MachineFunction &MF = DAG.getMachineFunction();
8212       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8213       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8214         if (Register::isPhysicalRegister(Reg) &&
8215             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8216           const char *RegName = TRI.getName(Reg);
8217           emitInlineAsmError(Call, "write to reserved register '" +
8218                                        Twine(RegName) + "'");
8219           return true;
8220         }
8221       }
8222       return false;
8223     };
8224 
8225     switch (OpInfo.Type) {
8226     case InlineAsm::isOutput:
8227       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8228         unsigned ConstraintID =
8229             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8230         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8231                "Failed to convert memory constraint code to constraint id.");
8232 
8233         // Add information to the INLINEASM node to know about this output.
8234         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8235         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8236         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8237                                                         MVT::i32));
8238         AsmNodeOperands.push_back(OpInfo.CallOperand);
8239       } else {
8240         // Otherwise, this outputs to a register (directly for C_Register /
8241         // C_RegisterClass, and a target-defined fashion for
8242         // C_Immediate/C_Other). Find a register that we can use.
8243         if (OpInfo.AssignedRegs.Regs.empty()) {
8244           emitInlineAsmError(
8245               Call, "couldn't allocate output register for constraint '" +
8246                         Twine(OpInfo.ConstraintCode) + "'");
8247           return;
8248         }
8249 
8250         if (DetectWriteToReservedRegister())
8251           return;
8252 
8253         // Add information to the INLINEASM node to know that this register is
8254         // set.
8255         OpInfo.AssignedRegs.AddInlineAsmOperands(
8256             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8257                                   : InlineAsm::Kind_RegDef,
8258             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8259       }
8260       break;
8261 
8262     case InlineAsm::isInput: {
8263       SDValue InOperandVal = OpInfo.CallOperand;
8264 
8265       if (OpInfo.isMatchingInputConstraint()) {
8266         // If this is required to match an output register we have already set,
8267         // just use its register.
8268         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8269                                                   AsmNodeOperands);
8270         unsigned OpFlag =
8271           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8272         if (InlineAsm::isRegDefKind(OpFlag) ||
8273             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8274           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8275           if (OpInfo.isIndirect) {
8276             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8277             emitInlineAsmError(Call, "inline asm not supported yet: "
8278                                      "don't know how to handle tied "
8279                                      "indirect register inputs");
8280             return;
8281           }
8282 
8283           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8284           SmallVector<unsigned, 4> Regs;
8285 
8286           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8287             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8288             MachineRegisterInfo &RegInfo =
8289                 DAG.getMachineFunction().getRegInfo();
8290             for (unsigned i = 0; i != NumRegs; ++i)
8291               Regs.push_back(RegInfo.createVirtualRegister(RC));
8292           } else {
8293             emitInlineAsmError(Call,
8294                                "inline asm error: This value type register "
8295                                "class is not natively supported!");
8296             return;
8297           }
8298 
8299           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8300 
8301           SDLoc dl = getCurSDLoc();
8302           // Use the produced MatchedRegs object to
8303           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8304           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8305                                            true, OpInfo.getMatchedOperand(), dl,
8306                                            DAG, AsmNodeOperands);
8307           break;
8308         }
8309 
8310         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8311         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8312                "Unexpected number of operands");
8313         // Add information to the INLINEASM node to know about this input.
8314         // See InlineAsm.h isUseOperandTiedToDef.
8315         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8316         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8317                                                     OpInfo.getMatchedOperand());
8318         AsmNodeOperands.push_back(DAG.getTargetConstant(
8319             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8320         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8321         break;
8322       }
8323 
8324       // Treat indirect 'X' constraint as memory.
8325       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8326           OpInfo.isIndirect)
8327         OpInfo.ConstraintType = TargetLowering::C_Memory;
8328 
8329       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8330           OpInfo.ConstraintType == TargetLowering::C_Other) {
8331         std::vector<SDValue> Ops;
8332         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8333                                           Ops, DAG);
8334         if (Ops.empty()) {
8335           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8336             if (isa<ConstantSDNode>(InOperandVal)) {
8337               emitInlineAsmError(Call, "value out of range for constraint '" +
8338                                            Twine(OpInfo.ConstraintCode) + "'");
8339               return;
8340             }
8341 
8342           emitInlineAsmError(Call,
8343                              "invalid operand for inline asm constraint '" +
8344                                  Twine(OpInfo.ConstraintCode) + "'");
8345           return;
8346         }
8347 
8348         // Add information to the INLINEASM node to know about this input.
8349         unsigned ResOpType =
8350           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8351         AsmNodeOperands.push_back(DAG.getTargetConstant(
8352             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8353         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8354         break;
8355       }
8356 
8357       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8358         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8359         assert(InOperandVal.getValueType() ==
8360                    TLI.getPointerTy(DAG.getDataLayout()) &&
8361                "Memory operands expect pointer values");
8362 
8363         unsigned ConstraintID =
8364             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8365         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8366                "Failed to convert memory constraint code to constraint id.");
8367 
8368         // Add information to the INLINEASM node to know about this input.
8369         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8370         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8371         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8372                                                         getCurSDLoc(),
8373                                                         MVT::i32));
8374         AsmNodeOperands.push_back(InOperandVal);
8375         break;
8376       }
8377 
8378       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8379               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8380              "Unknown constraint type!");
8381 
8382       // TODO: Support this.
8383       if (OpInfo.isIndirect) {
8384         emitInlineAsmError(
8385             Call, "Don't know how to handle indirect register inputs yet "
8386                   "for constraint '" +
8387                       Twine(OpInfo.ConstraintCode) + "'");
8388         return;
8389       }
8390 
8391       // Copy the input into the appropriate registers.
8392       if (OpInfo.AssignedRegs.Regs.empty()) {
8393         emitInlineAsmError(Call,
8394                            "couldn't allocate input reg for constraint '" +
8395                                Twine(OpInfo.ConstraintCode) + "'");
8396         return;
8397       }
8398 
8399       if (DetectWriteToReservedRegister())
8400         return;
8401 
8402       SDLoc dl = getCurSDLoc();
8403 
8404       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8405                                         &Call);
8406 
8407       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8408                                                dl, DAG, AsmNodeOperands);
8409       break;
8410     }
8411     case InlineAsm::isClobber:
8412       // Add the clobbered value to the operand list, so that the register
8413       // allocator is aware that the physreg got clobbered.
8414       if (!OpInfo.AssignedRegs.Regs.empty())
8415         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8416                                                  false, 0, getCurSDLoc(), DAG,
8417                                                  AsmNodeOperands);
8418       break;
8419     }
8420   }
8421 
8422   // Finish up input operands.  Set the input chain and add the flag last.
8423   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8424   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8425 
8426   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8427   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8428                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8429   Flag = Chain.getValue(1);
8430 
8431   // Do additional work to generate outputs.
8432 
8433   SmallVector<EVT, 1> ResultVTs;
8434   SmallVector<SDValue, 1> ResultValues;
8435   SmallVector<SDValue, 8> OutChains;
8436 
8437   llvm::Type *CallResultType = Call.getType();
8438   ArrayRef<Type *> ResultTypes;
8439   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8440     ResultTypes = StructResult->elements();
8441   else if (!CallResultType->isVoidTy())
8442     ResultTypes = makeArrayRef(CallResultType);
8443 
8444   auto CurResultType = ResultTypes.begin();
8445   auto handleRegAssign = [&](SDValue V) {
8446     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8447     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8448     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8449     ++CurResultType;
8450     // If the type of the inline asm call site return value is different but has
8451     // same size as the type of the asm output bitcast it.  One example of this
8452     // is for vectors with different width / number of elements.  This can
8453     // happen for register classes that can contain multiple different value
8454     // types.  The preg or vreg allocated may not have the same VT as was
8455     // expected.
8456     //
8457     // This can also happen for a return value that disagrees with the register
8458     // class it is put in, eg. a double in a general-purpose register on a
8459     // 32-bit machine.
8460     if (ResultVT != V.getValueType() &&
8461         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8462       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8463     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8464              V.getValueType().isInteger()) {
8465       // If a result value was tied to an input value, the computed result
8466       // may have a wider width than the expected result.  Extract the
8467       // relevant portion.
8468       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8469     }
8470     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8471     ResultVTs.push_back(ResultVT);
8472     ResultValues.push_back(V);
8473   };
8474 
8475   // Deal with output operands.
8476   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8477     if (OpInfo.Type == InlineAsm::isOutput) {
8478       SDValue Val;
8479       // Skip trivial output operands.
8480       if (OpInfo.AssignedRegs.Regs.empty())
8481         continue;
8482 
8483       switch (OpInfo.ConstraintType) {
8484       case TargetLowering::C_Register:
8485       case TargetLowering::C_RegisterClass:
8486         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8487                                                   Chain, &Flag, &Call);
8488         break;
8489       case TargetLowering::C_Immediate:
8490       case TargetLowering::C_Other:
8491         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8492                                               OpInfo, DAG);
8493         break;
8494       case TargetLowering::C_Memory:
8495         break; // Already handled.
8496       case TargetLowering::C_Unknown:
8497         assert(false && "Unexpected unknown constraint");
8498       }
8499 
8500       // Indirect output manifest as stores. Record output chains.
8501       if (OpInfo.isIndirect) {
8502         const Value *Ptr = OpInfo.CallOperandVal;
8503         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8504         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8505                                      MachinePointerInfo(Ptr));
8506         OutChains.push_back(Store);
8507       } else {
8508         // generate CopyFromRegs to associated registers.
8509         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8510         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8511           for (const SDValue &V : Val->op_values())
8512             handleRegAssign(V);
8513         } else
8514           handleRegAssign(Val);
8515       }
8516     }
8517   }
8518 
8519   // Set results.
8520   if (!ResultValues.empty()) {
8521     assert(CurResultType == ResultTypes.end() &&
8522            "Mismatch in number of ResultTypes");
8523     assert(ResultValues.size() == ResultTypes.size() &&
8524            "Mismatch in number of output operands in asm result");
8525 
8526     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8527                             DAG.getVTList(ResultVTs), ResultValues);
8528     setValue(&Call, V);
8529   }
8530 
8531   // Collect store chains.
8532   if (!OutChains.empty())
8533     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8534 
8535   // Only Update Root if inline assembly has a memory effect.
8536   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8537     DAG.setRoot(Chain);
8538 }
8539 
8540 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8541                                              const Twine &Message) {
8542   LLVMContext &Ctx = *DAG.getContext();
8543   Ctx.emitError(&Call, Message);
8544 
8545   // Make sure we leave the DAG in a valid state
8546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8547   SmallVector<EVT, 1> ValueVTs;
8548   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8549 
8550   if (ValueVTs.empty())
8551     return;
8552 
8553   SmallVector<SDValue, 1> Ops;
8554   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8555     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8556 
8557   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8558 }
8559 
8560 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8561   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8562                           MVT::Other, getRoot(),
8563                           getValue(I.getArgOperand(0)),
8564                           DAG.getSrcValue(I.getArgOperand(0))));
8565 }
8566 
8567 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8569   const DataLayout &DL = DAG.getDataLayout();
8570   SDValue V = DAG.getVAArg(
8571       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8572       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8573       DL.getABITypeAlignment(I.getType()));
8574   DAG.setRoot(V.getValue(1));
8575 
8576   if (I.getType()->isPointerTy())
8577     V = DAG.getPtrExtOrTrunc(
8578         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8579   setValue(&I, V);
8580 }
8581 
8582 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8583   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8584                           MVT::Other, getRoot(),
8585                           getValue(I.getArgOperand(0)),
8586                           DAG.getSrcValue(I.getArgOperand(0))));
8587 }
8588 
8589 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8590   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8591                           MVT::Other, getRoot(),
8592                           getValue(I.getArgOperand(0)),
8593                           getValue(I.getArgOperand(1)),
8594                           DAG.getSrcValue(I.getArgOperand(0)),
8595                           DAG.getSrcValue(I.getArgOperand(1))));
8596 }
8597 
8598 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8599                                                     const Instruction &I,
8600                                                     SDValue Op) {
8601   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8602   if (!Range)
8603     return Op;
8604 
8605   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8606   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8607     return Op;
8608 
8609   APInt Lo = CR.getUnsignedMin();
8610   if (!Lo.isMinValue())
8611     return Op;
8612 
8613   APInt Hi = CR.getUnsignedMax();
8614   unsigned Bits = std::max(Hi.getActiveBits(),
8615                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8616 
8617   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8618 
8619   SDLoc SL = getCurSDLoc();
8620 
8621   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8622                              DAG.getValueType(SmallVT));
8623   unsigned NumVals = Op.getNode()->getNumValues();
8624   if (NumVals == 1)
8625     return ZExt;
8626 
8627   SmallVector<SDValue, 4> Ops;
8628 
8629   Ops.push_back(ZExt);
8630   for (unsigned I = 1; I != NumVals; ++I)
8631     Ops.push_back(Op.getValue(I));
8632 
8633   return DAG.getMergeValues(Ops, SL);
8634 }
8635 
8636 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8637 /// the call being lowered.
8638 ///
8639 /// This is a helper for lowering intrinsics that follow a target calling
8640 /// convention or require stack pointer adjustment. Only a subset of the
8641 /// intrinsic's operands need to participate in the calling convention.
8642 void SelectionDAGBuilder::populateCallLoweringInfo(
8643     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8644     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8645     bool IsPatchPoint) {
8646   TargetLowering::ArgListTy Args;
8647   Args.reserve(NumArgs);
8648 
8649   // Populate the argument list.
8650   // Attributes for args start at offset 1, after the return attribute.
8651   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8652        ArgI != ArgE; ++ArgI) {
8653     const Value *V = Call->getOperand(ArgI);
8654 
8655     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8656 
8657     TargetLowering::ArgListEntry Entry;
8658     Entry.Node = getValue(V);
8659     Entry.Ty = V->getType();
8660     Entry.setAttributes(Call, ArgI);
8661     Args.push_back(Entry);
8662   }
8663 
8664   CLI.setDebugLoc(getCurSDLoc())
8665       .setChain(getRoot())
8666       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8667       .setDiscardResult(Call->use_empty())
8668       .setIsPatchPoint(IsPatchPoint)
8669       .setIsPreallocated(
8670           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8671 }
8672 
8673 /// Add a stack map intrinsic call's live variable operands to a stackmap
8674 /// or patchpoint target node's operand list.
8675 ///
8676 /// Constants are converted to TargetConstants purely as an optimization to
8677 /// avoid constant materialization and register allocation.
8678 ///
8679 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8680 /// generate addess computation nodes, and so FinalizeISel can convert the
8681 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8682 /// address materialization and register allocation, but may also be required
8683 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8684 /// alloca in the entry block, then the runtime may assume that the alloca's
8685 /// StackMap location can be read immediately after compilation and that the
8686 /// location is valid at any point during execution (this is similar to the
8687 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8688 /// only available in a register, then the runtime would need to trap when
8689 /// execution reaches the StackMap in order to read the alloca's location.
8690 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8691                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8692                                 SelectionDAGBuilder &Builder) {
8693   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8694     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8696       Ops.push_back(
8697         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8698       Ops.push_back(
8699         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8700     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8701       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8702       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8703           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8704     } else
8705       Ops.push_back(OpVal);
8706   }
8707 }
8708 
8709 /// Lower llvm.experimental.stackmap directly to its target opcode.
8710 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8711   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8712   //                                  [live variables...])
8713 
8714   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8715 
8716   SDValue Chain, InFlag, Callee, NullPtr;
8717   SmallVector<SDValue, 32> Ops;
8718 
8719   SDLoc DL = getCurSDLoc();
8720   Callee = getValue(CI.getCalledOperand());
8721   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8722 
8723   // The stackmap intrinsic only records the live variables (the arguments
8724   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8725   // intrinsic, this won't be lowered to a function call. This means we don't
8726   // have to worry about calling conventions and target specific lowering code.
8727   // Instead we perform the call lowering right here.
8728   //
8729   // chain, flag = CALLSEQ_START(chain, 0, 0)
8730   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8731   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8732   //
8733   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8734   InFlag = Chain.getValue(1);
8735 
8736   // Add the <id> and <numBytes> constants.
8737   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8738   Ops.push_back(DAG.getTargetConstant(
8739                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8740   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8741   Ops.push_back(DAG.getTargetConstant(
8742                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8743                   MVT::i32));
8744 
8745   // Push live variables for the stack map.
8746   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8747 
8748   // We are not pushing any register mask info here on the operands list,
8749   // because the stackmap doesn't clobber anything.
8750 
8751   // Push the chain and the glue flag.
8752   Ops.push_back(Chain);
8753   Ops.push_back(InFlag);
8754 
8755   // Create the STACKMAP node.
8756   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8757   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8758   Chain = SDValue(SM, 0);
8759   InFlag = Chain.getValue(1);
8760 
8761   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8762 
8763   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8764 
8765   // Set the root to the target-lowered call chain.
8766   DAG.setRoot(Chain);
8767 
8768   // Inform the Frame Information that we have a stackmap in this function.
8769   FuncInfo.MF->getFrameInfo().setHasStackMap();
8770 }
8771 
8772 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8773 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8774                                           const BasicBlock *EHPadBB) {
8775   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8776   //                                                 i32 <numBytes>,
8777   //                                                 i8* <target>,
8778   //                                                 i32 <numArgs>,
8779   //                                                 [Args...],
8780   //                                                 [live variables...])
8781 
8782   CallingConv::ID CC = CB.getCallingConv();
8783   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8784   bool HasDef = !CB.getType()->isVoidTy();
8785   SDLoc dl = getCurSDLoc();
8786   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8787 
8788   // Handle immediate and symbolic callees.
8789   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8790     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8791                                    /*isTarget=*/true);
8792   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8793     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8794                                          SDLoc(SymbolicCallee),
8795                                          SymbolicCallee->getValueType(0));
8796 
8797   // Get the real number of arguments participating in the call <numArgs>
8798   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8799   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8800 
8801   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8802   // Intrinsics include all meta-operands up to but not including CC.
8803   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8804   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8805          "Not enough arguments provided to the patchpoint intrinsic");
8806 
8807   // For AnyRegCC the arguments are lowered later on manually.
8808   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8809   Type *ReturnTy =
8810       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8811 
8812   TargetLowering::CallLoweringInfo CLI(DAG);
8813   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8814                            ReturnTy, true);
8815   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8816 
8817   SDNode *CallEnd = Result.second.getNode();
8818   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8819     CallEnd = CallEnd->getOperand(0).getNode();
8820 
8821   /// Get a call instruction from the call sequence chain.
8822   /// Tail calls are not allowed.
8823   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8824          "Expected a callseq node.");
8825   SDNode *Call = CallEnd->getOperand(0).getNode();
8826   bool HasGlue = Call->getGluedNode();
8827 
8828   // Replace the target specific call node with the patchable intrinsic.
8829   SmallVector<SDValue, 8> Ops;
8830 
8831   // Add the <id> and <numBytes> constants.
8832   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8833   Ops.push_back(DAG.getTargetConstant(
8834                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8835   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8836   Ops.push_back(DAG.getTargetConstant(
8837                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8838                   MVT::i32));
8839 
8840   // Add the callee.
8841   Ops.push_back(Callee);
8842 
8843   // Adjust <numArgs> to account for any arguments that have been passed on the
8844   // stack instead.
8845   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8846   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8847   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8848   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8849 
8850   // Add the calling convention
8851   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8852 
8853   // Add the arguments we omitted previously. The register allocator should
8854   // place these in any free register.
8855   if (IsAnyRegCC)
8856     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8857       Ops.push_back(getValue(CB.getArgOperand(i)));
8858 
8859   // Push the arguments from the call instruction up to the register mask.
8860   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8861   Ops.append(Call->op_begin() + 2, e);
8862 
8863   // Push live variables for the stack map.
8864   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8865 
8866   // Push the register mask info.
8867   if (HasGlue)
8868     Ops.push_back(*(Call->op_end()-2));
8869   else
8870     Ops.push_back(*(Call->op_end()-1));
8871 
8872   // Push the chain (this is originally the first operand of the call, but
8873   // becomes now the last or second to last operand).
8874   Ops.push_back(*(Call->op_begin()));
8875 
8876   // Push the glue flag (last operand).
8877   if (HasGlue)
8878     Ops.push_back(*(Call->op_end()-1));
8879 
8880   SDVTList NodeTys;
8881   if (IsAnyRegCC && HasDef) {
8882     // Create the return types based on the intrinsic definition
8883     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8884     SmallVector<EVT, 3> ValueVTs;
8885     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8886     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8887 
8888     // There is always a chain and a glue type at the end
8889     ValueVTs.push_back(MVT::Other);
8890     ValueVTs.push_back(MVT::Glue);
8891     NodeTys = DAG.getVTList(ValueVTs);
8892   } else
8893     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8894 
8895   // Replace the target specific call node with a PATCHPOINT node.
8896   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8897                                          dl, NodeTys, Ops);
8898 
8899   // Update the NodeMap.
8900   if (HasDef) {
8901     if (IsAnyRegCC)
8902       setValue(&CB, SDValue(MN, 0));
8903     else
8904       setValue(&CB, Result.first);
8905   }
8906 
8907   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8908   // call sequence. Furthermore the location of the chain and glue can change
8909   // when the AnyReg calling convention is used and the intrinsic returns a
8910   // value.
8911   if (IsAnyRegCC && HasDef) {
8912     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8913     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8914     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8915   } else
8916     DAG.ReplaceAllUsesWith(Call, MN);
8917   DAG.DeleteNode(Call);
8918 
8919   // Inform the Frame Information that we have a patchpoint in this function.
8920   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8921 }
8922 
8923 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8924                                             unsigned Intrinsic) {
8925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8926   SDValue Op1 = getValue(I.getArgOperand(0));
8927   SDValue Op2;
8928   if (I.getNumArgOperands() > 1)
8929     Op2 = getValue(I.getArgOperand(1));
8930   SDLoc dl = getCurSDLoc();
8931   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8932   SDValue Res;
8933   FastMathFlags FMF;
8934   if (isa<FPMathOperator>(I))
8935     FMF = I.getFastMathFlags();
8936 
8937   switch (Intrinsic) {
8938   case Intrinsic::experimental_vector_reduce_v2_fadd:
8939     if (FMF.allowReassoc())
8940       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8941                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8942     else
8943       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8944     break;
8945   case Intrinsic::experimental_vector_reduce_v2_fmul:
8946     if (FMF.allowReassoc())
8947       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8948                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8949     else
8950       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8951     break;
8952   case Intrinsic::experimental_vector_reduce_add:
8953     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8954     break;
8955   case Intrinsic::experimental_vector_reduce_mul:
8956     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8957     break;
8958   case Intrinsic::experimental_vector_reduce_and:
8959     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8960     break;
8961   case Intrinsic::experimental_vector_reduce_or:
8962     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8963     break;
8964   case Intrinsic::experimental_vector_reduce_xor:
8965     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8966     break;
8967   case Intrinsic::experimental_vector_reduce_smax:
8968     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8969     break;
8970   case Intrinsic::experimental_vector_reduce_smin:
8971     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8972     break;
8973   case Intrinsic::experimental_vector_reduce_umax:
8974     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8975     break;
8976   case Intrinsic::experimental_vector_reduce_umin:
8977     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8978     break;
8979   case Intrinsic::experimental_vector_reduce_fmax:
8980     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8981     break;
8982   case Intrinsic::experimental_vector_reduce_fmin:
8983     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8984     break;
8985   default:
8986     llvm_unreachable("Unhandled vector reduce intrinsic");
8987   }
8988   setValue(&I, Res);
8989 }
8990 
8991 /// Returns an AttributeList representing the attributes applied to the return
8992 /// value of the given call.
8993 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8994   SmallVector<Attribute::AttrKind, 2> Attrs;
8995   if (CLI.RetSExt)
8996     Attrs.push_back(Attribute::SExt);
8997   if (CLI.RetZExt)
8998     Attrs.push_back(Attribute::ZExt);
8999   if (CLI.IsInReg)
9000     Attrs.push_back(Attribute::InReg);
9001 
9002   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9003                             Attrs);
9004 }
9005 
9006 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9007 /// implementation, which just calls LowerCall.
9008 /// FIXME: When all targets are
9009 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9010 std::pair<SDValue, SDValue>
9011 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9012   // Handle the incoming return values from the call.
9013   CLI.Ins.clear();
9014   Type *OrigRetTy = CLI.RetTy;
9015   SmallVector<EVT, 4> RetTys;
9016   SmallVector<uint64_t, 4> Offsets;
9017   auto &DL = CLI.DAG.getDataLayout();
9018   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9019 
9020   if (CLI.IsPostTypeLegalization) {
9021     // If we are lowering a libcall after legalization, split the return type.
9022     SmallVector<EVT, 4> OldRetTys;
9023     SmallVector<uint64_t, 4> OldOffsets;
9024     RetTys.swap(OldRetTys);
9025     Offsets.swap(OldOffsets);
9026 
9027     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9028       EVT RetVT = OldRetTys[i];
9029       uint64_t Offset = OldOffsets[i];
9030       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9031       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9032       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9033       RetTys.append(NumRegs, RegisterVT);
9034       for (unsigned j = 0; j != NumRegs; ++j)
9035         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9036     }
9037   }
9038 
9039   SmallVector<ISD::OutputArg, 4> Outs;
9040   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9041 
9042   bool CanLowerReturn =
9043       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9044                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9045 
9046   SDValue DemoteStackSlot;
9047   int DemoteStackIdx = -100;
9048   if (!CanLowerReturn) {
9049     // FIXME: equivalent assert?
9050     // assert(!CS.hasInAllocaArgument() &&
9051     //        "sret demotion is incompatible with inalloca");
9052     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9053     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9054     MachineFunction &MF = CLI.DAG.getMachineFunction();
9055     DemoteStackIdx =
9056         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9057     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9058                                               DL.getAllocaAddrSpace());
9059 
9060     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9061     ArgListEntry Entry;
9062     Entry.Node = DemoteStackSlot;
9063     Entry.Ty = StackSlotPtrType;
9064     Entry.IsSExt = false;
9065     Entry.IsZExt = false;
9066     Entry.IsInReg = false;
9067     Entry.IsSRet = true;
9068     Entry.IsNest = false;
9069     Entry.IsByVal = false;
9070     Entry.IsReturned = false;
9071     Entry.IsSwiftSelf = false;
9072     Entry.IsSwiftError = false;
9073     Entry.IsCFGuardTarget = false;
9074     Entry.Alignment = Alignment;
9075     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9076     CLI.NumFixedArgs += 1;
9077     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9078 
9079     // sret demotion isn't compatible with tail-calls, since the sret argument
9080     // points into the callers stack frame.
9081     CLI.IsTailCall = false;
9082   } else {
9083     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9084         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9085     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9086       ISD::ArgFlagsTy Flags;
9087       if (NeedsRegBlock) {
9088         Flags.setInConsecutiveRegs();
9089         if (I == RetTys.size() - 1)
9090           Flags.setInConsecutiveRegsLast();
9091       }
9092       EVT VT = RetTys[I];
9093       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9094                                                      CLI.CallConv, VT);
9095       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9096                                                        CLI.CallConv, VT);
9097       for (unsigned i = 0; i != NumRegs; ++i) {
9098         ISD::InputArg MyFlags;
9099         MyFlags.Flags = Flags;
9100         MyFlags.VT = RegisterVT;
9101         MyFlags.ArgVT = VT;
9102         MyFlags.Used = CLI.IsReturnValueUsed;
9103         if (CLI.RetTy->isPointerTy()) {
9104           MyFlags.Flags.setPointer();
9105           MyFlags.Flags.setPointerAddrSpace(
9106               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9107         }
9108         if (CLI.RetSExt)
9109           MyFlags.Flags.setSExt();
9110         if (CLI.RetZExt)
9111           MyFlags.Flags.setZExt();
9112         if (CLI.IsInReg)
9113           MyFlags.Flags.setInReg();
9114         CLI.Ins.push_back(MyFlags);
9115       }
9116     }
9117   }
9118 
9119   // We push in swifterror return as the last element of CLI.Ins.
9120   ArgListTy &Args = CLI.getArgs();
9121   if (supportSwiftError()) {
9122     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9123       if (Args[i].IsSwiftError) {
9124         ISD::InputArg MyFlags;
9125         MyFlags.VT = getPointerTy(DL);
9126         MyFlags.ArgVT = EVT(getPointerTy(DL));
9127         MyFlags.Flags.setSwiftError();
9128         CLI.Ins.push_back(MyFlags);
9129       }
9130     }
9131   }
9132 
9133   // Handle all of the outgoing arguments.
9134   CLI.Outs.clear();
9135   CLI.OutVals.clear();
9136   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9137     SmallVector<EVT, 4> ValueVTs;
9138     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9139     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9140     Type *FinalType = Args[i].Ty;
9141     if (Args[i].IsByVal)
9142       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9143     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9144         FinalType, CLI.CallConv, CLI.IsVarArg);
9145     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9146          ++Value) {
9147       EVT VT = ValueVTs[Value];
9148       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9149       SDValue Op = SDValue(Args[i].Node.getNode(),
9150                            Args[i].Node.getResNo() + Value);
9151       ISD::ArgFlagsTy Flags;
9152 
9153       // Certain targets (such as MIPS), may have a different ABI alignment
9154       // for a type depending on the context. Give the target a chance to
9155       // specify the alignment it wants.
9156       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9157 
9158       if (Args[i].Ty->isPointerTy()) {
9159         Flags.setPointer();
9160         Flags.setPointerAddrSpace(
9161             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9162       }
9163       if (Args[i].IsZExt)
9164         Flags.setZExt();
9165       if (Args[i].IsSExt)
9166         Flags.setSExt();
9167       if (Args[i].IsInReg) {
9168         // If we are using vectorcall calling convention, a structure that is
9169         // passed InReg - is surely an HVA
9170         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9171             isa<StructType>(FinalType)) {
9172           // The first value of a structure is marked
9173           if (0 == Value)
9174             Flags.setHvaStart();
9175           Flags.setHva();
9176         }
9177         // Set InReg Flag
9178         Flags.setInReg();
9179       }
9180       if (Args[i].IsSRet)
9181         Flags.setSRet();
9182       if (Args[i].IsSwiftSelf)
9183         Flags.setSwiftSelf();
9184       if (Args[i].IsSwiftError)
9185         Flags.setSwiftError();
9186       if (Args[i].IsCFGuardTarget)
9187         Flags.setCFGuardTarget();
9188       if (Args[i].IsByVal)
9189         Flags.setByVal();
9190       if (Args[i].IsPreallocated) {
9191         Flags.setPreallocated();
9192         // Set the byval flag for CCAssignFn callbacks that don't know about
9193         // preallocated.  This way we can know how many bytes we should've
9194         // allocated and how many bytes a callee cleanup function will pop.  If
9195         // we port preallocated to more targets, we'll have to add custom
9196         // preallocated handling in the various CC lowering callbacks.
9197         Flags.setByVal();
9198       }
9199       if (Args[i].IsInAlloca) {
9200         Flags.setInAlloca();
9201         // Set the byval flag for CCAssignFn callbacks that don't know about
9202         // inalloca.  This way we can know how many bytes we should've allocated
9203         // and how many bytes a callee cleanup function will pop.  If we port
9204         // inalloca to more targets, we'll have to add custom inalloca handling
9205         // in the various CC lowering callbacks.
9206         Flags.setByVal();
9207       }
9208       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9209         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9210         Type *ElementTy = Ty->getElementType();
9211 
9212         unsigned FrameSize = DL.getTypeAllocSize(
9213             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9214         Flags.setByValSize(FrameSize);
9215 
9216         // info is not there but there are cases it cannot get right.
9217         Align FrameAlign;
9218         if (auto MA = Args[i].Alignment)
9219           FrameAlign = *MA;
9220         else
9221           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9222         Flags.setByValAlign(FrameAlign);
9223       }
9224       if (Args[i].IsNest)
9225         Flags.setNest();
9226       if (NeedsRegBlock)
9227         Flags.setInConsecutiveRegs();
9228       Flags.setOrigAlign(OriginalAlignment);
9229 
9230       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9231                                                  CLI.CallConv, VT);
9232       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9233                                                         CLI.CallConv, VT);
9234       SmallVector<SDValue, 4> Parts(NumParts);
9235       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9236 
9237       if (Args[i].IsSExt)
9238         ExtendKind = ISD::SIGN_EXTEND;
9239       else if (Args[i].IsZExt)
9240         ExtendKind = ISD::ZERO_EXTEND;
9241 
9242       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9243       // for now.
9244       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9245           CanLowerReturn) {
9246         assert((CLI.RetTy == Args[i].Ty ||
9247                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9248                  CLI.RetTy->getPointerAddressSpace() ==
9249                      Args[i].Ty->getPointerAddressSpace())) &&
9250                RetTys.size() == NumValues && "unexpected use of 'returned'");
9251         // Before passing 'returned' to the target lowering code, ensure that
9252         // either the register MVT and the actual EVT are the same size or that
9253         // the return value and argument are extended in the same way; in these
9254         // cases it's safe to pass the argument register value unchanged as the
9255         // return register value (although it's at the target's option whether
9256         // to do so)
9257         // TODO: allow code generation to take advantage of partially preserved
9258         // registers rather than clobbering the entire register when the
9259         // parameter extension method is not compatible with the return
9260         // extension method
9261         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9262             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9263              CLI.RetZExt == Args[i].IsZExt))
9264           Flags.setReturned();
9265       }
9266 
9267       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9268                      CLI.CallConv, ExtendKind);
9269 
9270       for (unsigned j = 0; j != NumParts; ++j) {
9271         // if it isn't first piece, alignment must be 1
9272         // For scalable vectors the scalable part is currently handled
9273         // by individual targets, so we just use the known minimum size here.
9274         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9275                     i < CLI.NumFixedArgs, i,
9276                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9277         if (NumParts > 1 && j == 0)
9278           MyFlags.Flags.setSplit();
9279         else if (j != 0) {
9280           MyFlags.Flags.setOrigAlign(Align(1));
9281           if (j == NumParts - 1)
9282             MyFlags.Flags.setSplitEnd();
9283         }
9284 
9285         CLI.Outs.push_back(MyFlags);
9286         CLI.OutVals.push_back(Parts[j]);
9287       }
9288 
9289       if (NeedsRegBlock && Value == NumValues - 1)
9290         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9291     }
9292   }
9293 
9294   SmallVector<SDValue, 4> InVals;
9295   CLI.Chain = LowerCall(CLI, InVals);
9296 
9297   // Update CLI.InVals to use outside of this function.
9298   CLI.InVals = InVals;
9299 
9300   // Verify that the target's LowerCall behaved as expected.
9301   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9302          "LowerCall didn't return a valid chain!");
9303   assert((!CLI.IsTailCall || InVals.empty()) &&
9304          "LowerCall emitted a return value for a tail call!");
9305   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9306          "LowerCall didn't emit the correct number of values!");
9307 
9308   // For a tail call, the return value is merely live-out and there aren't
9309   // any nodes in the DAG representing it. Return a special value to
9310   // indicate that a tail call has been emitted and no more Instructions
9311   // should be processed in the current block.
9312   if (CLI.IsTailCall) {
9313     CLI.DAG.setRoot(CLI.Chain);
9314     return std::make_pair(SDValue(), SDValue());
9315   }
9316 
9317 #ifndef NDEBUG
9318   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9319     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9320     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9321            "LowerCall emitted a value with the wrong type!");
9322   }
9323 #endif
9324 
9325   SmallVector<SDValue, 4> ReturnValues;
9326   if (!CanLowerReturn) {
9327     // The instruction result is the result of loading from the
9328     // hidden sret parameter.
9329     SmallVector<EVT, 1> PVTs;
9330     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9331 
9332     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9333     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9334     EVT PtrVT = PVTs[0];
9335 
9336     unsigned NumValues = RetTys.size();
9337     ReturnValues.resize(NumValues);
9338     SmallVector<SDValue, 4> Chains(NumValues);
9339 
9340     // An aggregate return value cannot wrap around the address space, so
9341     // offsets to its parts don't wrap either.
9342     SDNodeFlags Flags;
9343     Flags.setNoUnsignedWrap(true);
9344 
9345     MachineFunction &MF = CLI.DAG.getMachineFunction();
9346     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9347     for (unsigned i = 0; i < NumValues; ++i) {
9348       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9349                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9350                                                         PtrVT), Flags);
9351       SDValue L = CLI.DAG.getLoad(
9352           RetTys[i], CLI.DL, CLI.Chain, Add,
9353           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9354                                             DemoteStackIdx, Offsets[i]),
9355           HiddenSRetAlign);
9356       ReturnValues[i] = L;
9357       Chains[i] = L.getValue(1);
9358     }
9359 
9360     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9361   } else {
9362     // Collect the legal value parts into potentially illegal values
9363     // that correspond to the original function's return values.
9364     Optional<ISD::NodeType> AssertOp;
9365     if (CLI.RetSExt)
9366       AssertOp = ISD::AssertSext;
9367     else if (CLI.RetZExt)
9368       AssertOp = ISD::AssertZext;
9369     unsigned CurReg = 0;
9370     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9371       EVT VT = RetTys[I];
9372       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9373                                                      CLI.CallConv, VT);
9374       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9375                                                        CLI.CallConv, VT);
9376 
9377       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9378                                               NumRegs, RegisterVT, VT, nullptr,
9379                                               CLI.CallConv, AssertOp));
9380       CurReg += NumRegs;
9381     }
9382 
9383     // For a function returning void, there is no return value. We can't create
9384     // such a node, so we just return a null return value in that case. In
9385     // that case, nothing will actually look at the value.
9386     if (ReturnValues.empty())
9387       return std::make_pair(SDValue(), CLI.Chain);
9388   }
9389 
9390   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9391                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9392   return std::make_pair(Res, CLI.Chain);
9393 }
9394 
9395 void TargetLowering::LowerOperationWrapper(SDNode *N,
9396                                            SmallVectorImpl<SDValue> &Results,
9397                                            SelectionDAG &DAG) const {
9398   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9399     Results.push_back(Res);
9400 }
9401 
9402 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9403   llvm_unreachable("LowerOperation not implemented for this target!");
9404 }
9405 
9406 void
9407 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9408   SDValue Op = getNonRegisterValue(V);
9409   assert((Op.getOpcode() != ISD::CopyFromReg ||
9410           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9411          "Copy from a reg to the same reg!");
9412   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9413 
9414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9415   // If this is an InlineAsm we have to match the registers required, not the
9416   // notional registers required by the type.
9417 
9418   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9419                    None); // This is not an ABI copy.
9420   SDValue Chain = DAG.getEntryNode();
9421 
9422   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9423                               FuncInfo.PreferredExtendType.end())
9424                                  ? ISD::ANY_EXTEND
9425                                  : FuncInfo.PreferredExtendType[V];
9426   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9427   PendingExports.push_back(Chain);
9428 }
9429 
9430 #include "llvm/CodeGen/SelectionDAGISel.h"
9431 
9432 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9433 /// entry block, return true.  This includes arguments used by switches, since
9434 /// the switch may expand into multiple basic blocks.
9435 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9436   // With FastISel active, we may be splitting blocks, so force creation
9437   // of virtual registers for all non-dead arguments.
9438   if (FastISel)
9439     return A->use_empty();
9440 
9441   const BasicBlock &Entry = A->getParent()->front();
9442   for (const User *U : A->users())
9443     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9444       return false;  // Use not in entry block.
9445 
9446   return true;
9447 }
9448 
9449 using ArgCopyElisionMapTy =
9450     DenseMap<const Argument *,
9451              std::pair<const AllocaInst *, const StoreInst *>>;
9452 
9453 /// Scan the entry block of the function in FuncInfo for arguments that look
9454 /// like copies into a local alloca. Record any copied arguments in
9455 /// ArgCopyElisionCandidates.
9456 static void
9457 findArgumentCopyElisionCandidates(const DataLayout &DL,
9458                                   FunctionLoweringInfo *FuncInfo,
9459                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9460   // Record the state of every static alloca used in the entry block. Argument
9461   // allocas are all used in the entry block, so we need approximately as many
9462   // entries as we have arguments.
9463   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9464   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9465   unsigned NumArgs = FuncInfo->Fn->arg_size();
9466   StaticAllocas.reserve(NumArgs * 2);
9467 
9468   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9469     if (!V)
9470       return nullptr;
9471     V = V->stripPointerCasts();
9472     const auto *AI = dyn_cast<AllocaInst>(V);
9473     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9474       return nullptr;
9475     auto Iter = StaticAllocas.insert({AI, Unknown});
9476     return &Iter.first->second;
9477   };
9478 
9479   // Look for stores of arguments to static allocas. Look through bitcasts and
9480   // GEPs to handle type coercions, as long as the alloca is fully initialized
9481   // by the store. Any non-store use of an alloca escapes it and any subsequent
9482   // unanalyzed store might write it.
9483   // FIXME: Handle structs initialized with multiple stores.
9484   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9485     // Look for stores, and handle non-store uses conservatively.
9486     const auto *SI = dyn_cast<StoreInst>(&I);
9487     if (!SI) {
9488       // We will look through cast uses, so ignore them completely.
9489       if (I.isCast())
9490         continue;
9491       // Ignore debug info intrinsics, they don't escape or store to allocas.
9492       if (isa<DbgInfoIntrinsic>(I))
9493         continue;
9494       // This is an unknown instruction. Assume it escapes or writes to all
9495       // static alloca operands.
9496       for (const Use &U : I.operands()) {
9497         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9498           *Info = StaticAllocaInfo::Clobbered;
9499       }
9500       continue;
9501     }
9502 
9503     // If the stored value is a static alloca, mark it as escaped.
9504     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9505       *Info = StaticAllocaInfo::Clobbered;
9506 
9507     // Check if the destination is a static alloca.
9508     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9509     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9510     if (!Info)
9511       continue;
9512     const AllocaInst *AI = cast<AllocaInst>(Dst);
9513 
9514     // Skip allocas that have been initialized or clobbered.
9515     if (*Info != StaticAllocaInfo::Unknown)
9516       continue;
9517 
9518     // Check if the stored value is an argument, and that this store fully
9519     // initializes the alloca. Don't elide copies from the same argument twice.
9520     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9521     const auto *Arg = dyn_cast<Argument>(Val);
9522     if (!Arg || Arg->hasPassPointeeByValueAttr() ||
9523         Arg->getType()->isEmptyTy() ||
9524         DL.getTypeStoreSize(Arg->getType()) !=
9525             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9526         ArgCopyElisionCandidates.count(Arg)) {
9527       *Info = StaticAllocaInfo::Clobbered;
9528       continue;
9529     }
9530 
9531     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9532                       << '\n');
9533 
9534     // Mark this alloca and store for argument copy elision.
9535     *Info = StaticAllocaInfo::Elidable;
9536     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9537 
9538     // Stop scanning if we've seen all arguments. This will happen early in -O0
9539     // builds, which is useful, because -O0 builds have large entry blocks and
9540     // many allocas.
9541     if (ArgCopyElisionCandidates.size() == NumArgs)
9542       break;
9543   }
9544 }
9545 
9546 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9547 /// ArgVal is a load from a suitable fixed stack object.
9548 static void tryToElideArgumentCopy(
9549     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9550     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9551     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9552     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9553     SDValue ArgVal, bool &ArgHasUses) {
9554   // Check if this is a load from a fixed stack object.
9555   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9556   if (!LNode)
9557     return;
9558   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9559   if (!FINode)
9560     return;
9561 
9562   // Check that the fixed stack object is the right size and alignment.
9563   // Look at the alignment that the user wrote on the alloca instead of looking
9564   // at the stack object.
9565   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9566   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9567   const AllocaInst *AI = ArgCopyIter->second.first;
9568   int FixedIndex = FINode->getIndex();
9569   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9570   int OldIndex = AllocaIndex;
9571   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9572   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9573     LLVM_DEBUG(
9574         dbgs() << "  argument copy elision failed due to bad fixed stack "
9575                   "object size\n");
9576     return;
9577   }
9578   Align RequiredAlignment = AI->getAlign();
9579   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9580     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9581                          "greater than stack argument alignment ("
9582                       << DebugStr(RequiredAlignment) << " vs "
9583                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9584     return;
9585   }
9586 
9587   // Perform the elision. Delete the old stack object and replace its only use
9588   // in the variable info map. Mark the stack object as mutable.
9589   LLVM_DEBUG({
9590     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9591            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9592            << '\n';
9593   });
9594   MFI.RemoveStackObject(OldIndex);
9595   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9596   AllocaIndex = FixedIndex;
9597   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9598   Chains.push_back(ArgVal.getValue(1));
9599 
9600   // Avoid emitting code for the store implementing the copy.
9601   const StoreInst *SI = ArgCopyIter->second.second;
9602   ElidedArgCopyInstrs.insert(SI);
9603 
9604   // Check for uses of the argument again so that we can avoid exporting ArgVal
9605   // if it is't used by anything other than the store.
9606   for (const Value *U : Arg.users()) {
9607     if (U != SI) {
9608       ArgHasUses = true;
9609       break;
9610     }
9611   }
9612 }
9613 
9614 void SelectionDAGISel::LowerArguments(const Function &F) {
9615   SelectionDAG &DAG = SDB->DAG;
9616   SDLoc dl = SDB->getCurSDLoc();
9617   const DataLayout &DL = DAG.getDataLayout();
9618   SmallVector<ISD::InputArg, 16> Ins;
9619 
9620   // In Naked functions we aren't going to save any registers.
9621   if (F.hasFnAttribute(Attribute::Naked))
9622     return;
9623 
9624   if (!FuncInfo->CanLowerReturn) {
9625     // Put in an sret pointer parameter before all the other parameters.
9626     SmallVector<EVT, 1> ValueVTs;
9627     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9628                     F.getReturnType()->getPointerTo(
9629                         DAG.getDataLayout().getAllocaAddrSpace()),
9630                     ValueVTs);
9631 
9632     // NOTE: Assuming that a pointer will never break down to more than one VT
9633     // or one register.
9634     ISD::ArgFlagsTy Flags;
9635     Flags.setSRet();
9636     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9637     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9638                          ISD::InputArg::NoArgIndex, 0);
9639     Ins.push_back(RetArg);
9640   }
9641 
9642   // Look for stores of arguments to static allocas. Mark such arguments with a
9643   // flag to ask the target to give us the memory location of that argument if
9644   // available.
9645   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9646   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9647                                     ArgCopyElisionCandidates);
9648 
9649   // Set up the incoming argument description vector.
9650   for (const Argument &Arg : F.args()) {
9651     unsigned ArgNo = Arg.getArgNo();
9652     SmallVector<EVT, 4> ValueVTs;
9653     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9654     bool isArgValueUsed = !Arg.use_empty();
9655     unsigned PartBase = 0;
9656     Type *FinalType = Arg.getType();
9657     if (Arg.hasAttribute(Attribute::ByVal))
9658       FinalType = Arg.getParamByValType();
9659     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9660         FinalType, F.getCallingConv(), F.isVarArg());
9661     for (unsigned Value = 0, NumValues = ValueVTs.size();
9662          Value != NumValues; ++Value) {
9663       EVT VT = ValueVTs[Value];
9664       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9665       ISD::ArgFlagsTy Flags;
9666 
9667       // Certain targets (such as MIPS), may have a different ABI alignment
9668       // for a type depending on the context. Give the target a chance to
9669       // specify the alignment it wants.
9670       const Align OriginalAlignment(
9671           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9672 
9673       if (Arg.getType()->isPointerTy()) {
9674         Flags.setPointer();
9675         Flags.setPointerAddrSpace(
9676             cast<PointerType>(Arg.getType())->getAddressSpace());
9677       }
9678       if (Arg.hasAttribute(Attribute::ZExt))
9679         Flags.setZExt();
9680       if (Arg.hasAttribute(Attribute::SExt))
9681         Flags.setSExt();
9682       if (Arg.hasAttribute(Attribute::InReg)) {
9683         // If we are using vectorcall calling convention, a structure that is
9684         // passed InReg - is surely an HVA
9685         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9686             isa<StructType>(Arg.getType())) {
9687           // The first value of a structure is marked
9688           if (0 == Value)
9689             Flags.setHvaStart();
9690           Flags.setHva();
9691         }
9692         // Set InReg Flag
9693         Flags.setInReg();
9694       }
9695       if (Arg.hasAttribute(Attribute::StructRet))
9696         Flags.setSRet();
9697       if (Arg.hasAttribute(Attribute::SwiftSelf))
9698         Flags.setSwiftSelf();
9699       if (Arg.hasAttribute(Attribute::SwiftError))
9700         Flags.setSwiftError();
9701       if (Arg.hasAttribute(Attribute::ByVal))
9702         Flags.setByVal();
9703       if (Arg.hasAttribute(Attribute::InAlloca)) {
9704         Flags.setInAlloca();
9705         // Set the byval flag for CCAssignFn callbacks that don't know about
9706         // inalloca.  This way we can know how many bytes we should've allocated
9707         // and how many bytes a callee cleanup function will pop.  If we port
9708         // inalloca to more targets, we'll have to add custom inalloca handling
9709         // in the various CC lowering callbacks.
9710         Flags.setByVal();
9711       }
9712       if (Arg.hasAttribute(Attribute::Preallocated)) {
9713         Flags.setPreallocated();
9714         // Set the byval flag for CCAssignFn callbacks that don't know about
9715         // preallocated.  This way we can know how many bytes we should've
9716         // allocated and how many bytes a callee cleanup function will pop.  If
9717         // we port preallocated to more targets, we'll have to add custom
9718         // preallocated handling in the various CC lowering callbacks.
9719         Flags.setByVal();
9720       }
9721       if (F.getCallingConv() == CallingConv::X86_INTR) {
9722         // IA Interrupt passes frame (1st parameter) by value in the stack.
9723         if (ArgNo == 0)
9724           Flags.setByVal();
9725       }
9726       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) {
9727         Type *ElementTy = Arg.getParamByValType();
9728 
9729         // For ByVal, size and alignment should be passed from FE.  BE will
9730         // guess if this info is not there but there are cases it cannot get
9731         // right.
9732         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9733         Flags.setByValSize(FrameSize);
9734 
9735         unsigned FrameAlign;
9736         if (Arg.getParamAlignment())
9737           FrameAlign = Arg.getParamAlignment();
9738         else
9739           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9740         Flags.setByValAlign(Align(FrameAlign));
9741       }
9742       if (Arg.hasAttribute(Attribute::Nest))
9743         Flags.setNest();
9744       if (NeedsRegBlock)
9745         Flags.setInConsecutiveRegs();
9746       Flags.setOrigAlign(OriginalAlignment);
9747       if (ArgCopyElisionCandidates.count(&Arg))
9748         Flags.setCopyElisionCandidate();
9749       if (Arg.hasAttribute(Attribute::Returned))
9750         Flags.setReturned();
9751 
9752       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9753           *CurDAG->getContext(), F.getCallingConv(), VT);
9754       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9755           *CurDAG->getContext(), F.getCallingConv(), VT);
9756       for (unsigned i = 0; i != NumRegs; ++i) {
9757         // For scalable vectors, use the minimum size; individual targets
9758         // are responsible for handling scalable vector arguments and
9759         // return values.
9760         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9761                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9762         if (NumRegs > 1 && i == 0)
9763           MyFlags.Flags.setSplit();
9764         // if it isn't first piece, alignment must be 1
9765         else if (i > 0) {
9766           MyFlags.Flags.setOrigAlign(Align(1));
9767           if (i == NumRegs - 1)
9768             MyFlags.Flags.setSplitEnd();
9769         }
9770         Ins.push_back(MyFlags);
9771       }
9772       if (NeedsRegBlock && Value == NumValues - 1)
9773         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9774       PartBase += VT.getStoreSize().getKnownMinSize();
9775     }
9776   }
9777 
9778   // Call the target to set up the argument values.
9779   SmallVector<SDValue, 8> InVals;
9780   SDValue NewRoot = TLI->LowerFormalArguments(
9781       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9782 
9783   // Verify that the target's LowerFormalArguments behaved as expected.
9784   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9785          "LowerFormalArguments didn't return a valid chain!");
9786   assert(InVals.size() == Ins.size() &&
9787          "LowerFormalArguments didn't emit the correct number of values!");
9788   LLVM_DEBUG({
9789     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9790       assert(InVals[i].getNode() &&
9791              "LowerFormalArguments emitted a null value!");
9792       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9793              "LowerFormalArguments emitted a value with the wrong type!");
9794     }
9795   });
9796 
9797   // Update the DAG with the new chain value resulting from argument lowering.
9798   DAG.setRoot(NewRoot);
9799 
9800   // Set up the argument values.
9801   unsigned i = 0;
9802   if (!FuncInfo->CanLowerReturn) {
9803     // Create a virtual register for the sret pointer, and put in a copy
9804     // from the sret argument into it.
9805     SmallVector<EVT, 1> ValueVTs;
9806     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9807                     F.getReturnType()->getPointerTo(
9808                         DAG.getDataLayout().getAllocaAddrSpace()),
9809                     ValueVTs);
9810     MVT VT = ValueVTs[0].getSimpleVT();
9811     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9812     Optional<ISD::NodeType> AssertOp = None;
9813     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9814                                         nullptr, F.getCallingConv(), AssertOp);
9815 
9816     MachineFunction& MF = SDB->DAG.getMachineFunction();
9817     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9818     Register SRetReg =
9819         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9820     FuncInfo->DemoteRegister = SRetReg;
9821     NewRoot =
9822         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9823     DAG.setRoot(NewRoot);
9824 
9825     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9826     ++i;
9827   }
9828 
9829   SmallVector<SDValue, 4> Chains;
9830   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9831   for (const Argument &Arg : F.args()) {
9832     SmallVector<SDValue, 4> ArgValues;
9833     SmallVector<EVT, 4> ValueVTs;
9834     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9835     unsigned NumValues = ValueVTs.size();
9836     if (NumValues == 0)
9837       continue;
9838 
9839     bool ArgHasUses = !Arg.use_empty();
9840 
9841     // Elide the copying store if the target loaded this argument from a
9842     // suitable fixed stack object.
9843     if (Ins[i].Flags.isCopyElisionCandidate()) {
9844       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9845                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9846                              InVals[i], ArgHasUses);
9847     }
9848 
9849     // If this argument is unused then remember its value. It is used to generate
9850     // debugging information.
9851     bool isSwiftErrorArg =
9852         TLI->supportSwiftError() &&
9853         Arg.hasAttribute(Attribute::SwiftError);
9854     if (!ArgHasUses && !isSwiftErrorArg) {
9855       SDB->setUnusedArgValue(&Arg, InVals[i]);
9856 
9857       // Also remember any frame index for use in FastISel.
9858       if (FrameIndexSDNode *FI =
9859           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9860         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9861     }
9862 
9863     for (unsigned Val = 0; Val != NumValues; ++Val) {
9864       EVT VT = ValueVTs[Val];
9865       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9866                                                       F.getCallingConv(), VT);
9867       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9868           *CurDAG->getContext(), F.getCallingConv(), VT);
9869 
9870       // Even an apparent 'unused' swifterror argument needs to be returned. So
9871       // we do generate a copy for it that can be used on return from the
9872       // function.
9873       if (ArgHasUses || isSwiftErrorArg) {
9874         Optional<ISD::NodeType> AssertOp;
9875         if (Arg.hasAttribute(Attribute::SExt))
9876           AssertOp = ISD::AssertSext;
9877         else if (Arg.hasAttribute(Attribute::ZExt))
9878           AssertOp = ISD::AssertZext;
9879 
9880         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9881                                              PartVT, VT, nullptr,
9882                                              F.getCallingConv(), AssertOp));
9883       }
9884 
9885       i += NumParts;
9886     }
9887 
9888     // We don't need to do anything else for unused arguments.
9889     if (ArgValues.empty())
9890       continue;
9891 
9892     // Note down frame index.
9893     if (FrameIndexSDNode *FI =
9894         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9895       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9896 
9897     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9898                                      SDB->getCurSDLoc());
9899 
9900     SDB->setValue(&Arg, Res);
9901     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9902       // We want to associate the argument with the frame index, among
9903       // involved operands, that correspond to the lowest address. The
9904       // getCopyFromParts function, called earlier, is swapping the order of
9905       // the operands to BUILD_PAIR depending on endianness. The result of
9906       // that swapping is that the least significant bits of the argument will
9907       // be in the first operand of the BUILD_PAIR node, and the most
9908       // significant bits will be in the second operand.
9909       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9910       if (LoadSDNode *LNode =
9911           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9912         if (FrameIndexSDNode *FI =
9913             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9914           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9915     }
9916 
9917     // Analyses past this point are naive and don't expect an assertion.
9918     if (Res.getOpcode() == ISD::AssertZext)
9919       Res = Res.getOperand(0);
9920 
9921     // Update the SwiftErrorVRegDefMap.
9922     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9923       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9924       if (Register::isVirtualRegister(Reg))
9925         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9926                                    Reg);
9927     }
9928 
9929     // If this argument is live outside of the entry block, insert a copy from
9930     // wherever we got it to the vreg that other BB's will reference it as.
9931     if (Res.getOpcode() == ISD::CopyFromReg) {
9932       // If we can, though, try to skip creating an unnecessary vreg.
9933       // FIXME: This isn't very clean... it would be nice to make this more
9934       // general.
9935       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9936       if (Register::isVirtualRegister(Reg)) {
9937         FuncInfo->ValueMap[&Arg] = Reg;
9938         continue;
9939       }
9940     }
9941     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9942       FuncInfo->InitializeRegForValue(&Arg);
9943       SDB->CopyToExportRegsIfNeeded(&Arg);
9944     }
9945   }
9946 
9947   if (!Chains.empty()) {
9948     Chains.push_back(NewRoot);
9949     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9950   }
9951 
9952   DAG.setRoot(NewRoot);
9953 
9954   assert(i == InVals.size() && "Argument register count mismatch!");
9955 
9956   // If any argument copy elisions occurred and we have debug info, update the
9957   // stale frame indices used in the dbg.declare variable info table.
9958   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9959   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9960     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9961       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9962       if (I != ArgCopyElisionFrameIndexMap.end())
9963         VI.Slot = I->second;
9964     }
9965   }
9966 
9967   // Finally, if the target has anything special to do, allow it to do so.
9968   emitFunctionEntryCode();
9969 }
9970 
9971 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9972 /// ensure constants are generated when needed.  Remember the virtual registers
9973 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9974 /// directly add them, because expansion might result in multiple MBB's for one
9975 /// BB.  As such, the start of the BB might correspond to a different MBB than
9976 /// the end.
9977 void
9978 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9979   const Instruction *TI = LLVMBB->getTerminator();
9980 
9981   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9982 
9983   // Check PHI nodes in successors that expect a value to be available from this
9984   // block.
9985   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9986     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9987     if (!isa<PHINode>(SuccBB->begin())) continue;
9988     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9989 
9990     // If this terminator has multiple identical successors (common for
9991     // switches), only handle each succ once.
9992     if (!SuccsHandled.insert(SuccMBB).second)
9993       continue;
9994 
9995     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9996 
9997     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9998     // nodes and Machine PHI nodes, but the incoming operands have not been
9999     // emitted yet.
10000     for (const PHINode &PN : SuccBB->phis()) {
10001       // Ignore dead phi's.
10002       if (PN.use_empty())
10003         continue;
10004 
10005       // Skip empty types
10006       if (PN.getType()->isEmptyTy())
10007         continue;
10008 
10009       unsigned Reg;
10010       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10011 
10012       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10013         unsigned &RegOut = ConstantsOut[C];
10014         if (RegOut == 0) {
10015           RegOut = FuncInfo.CreateRegs(C);
10016           CopyValueToVirtualRegister(C, RegOut);
10017         }
10018         Reg = RegOut;
10019       } else {
10020         DenseMap<const Value *, Register>::iterator I =
10021           FuncInfo.ValueMap.find(PHIOp);
10022         if (I != FuncInfo.ValueMap.end())
10023           Reg = I->second;
10024         else {
10025           assert(isa<AllocaInst>(PHIOp) &&
10026                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10027                  "Didn't codegen value into a register!??");
10028           Reg = FuncInfo.CreateRegs(PHIOp);
10029           CopyValueToVirtualRegister(PHIOp, Reg);
10030         }
10031       }
10032 
10033       // Remember that this register needs to added to the machine PHI node as
10034       // the input for this MBB.
10035       SmallVector<EVT, 4> ValueVTs;
10036       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10037       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10038       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10039         EVT VT = ValueVTs[vti];
10040         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10041         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10042           FuncInfo.PHINodesToUpdate.push_back(
10043               std::make_pair(&*MBBI++, Reg + i));
10044         Reg += NumRegisters;
10045       }
10046     }
10047   }
10048 
10049   ConstantsOut.clear();
10050 }
10051 
10052 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10053 /// is 0.
10054 MachineBasicBlock *
10055 SelectionDAGBuilder::StackProtectorDescriptor::
10056 AddSuccessorMBB(const BasicBlock *BB,
10057                 MachineBasicBlock *ParentMBB,
10058                 bool IsLikely,
10059                 MachineBasicBlock *SuccMBB) {
10060   // If SuccBB has not been created yet, create it.
10061   if (!SuccMBB) {
10062     MachineFunction *MF = ParentMBB->getParent();
10063     MachineFunction::iterator BBI(ParentMBB);
10064     SuccMBB = MF->CreateMachineBasicBlock(BB);
10065     MF->insert(++BBI, SuccMBB);
10066   }
10067   // Add it as a successor of ParentMBB.
10068   ParentMBB->addSuccessor(
10069       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10070   return SuccMBB;
10071 }
10072 
10073 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10074   MachineFunction::iterator I(MBB);
10075   if (++I == FuncInfo.MF->end())
10076     return nullptr;
10077   return &*I;
10078 }
10079 
10080 /// During lowering new call nodes can be created (such as memset, etc.).
10081 /// Those will become new roots of the current DAG, but complications arise
10082 /// when they are tail calls. In such cases, the call lowering will update
10083 /// the root, but the builder still needs to know that a tail call has been
10084 /// lowered in order to avoid generating an additional return.
10085 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10086   // If the node is null, we do have a tail call.
10087   if (MaybeTC.getNode() != nullptr)
10088     DAG.setRoot(MaybeTC);
10089   else
10090     HasTailCall = true;
10091 }
10092 
10093 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10094                                         MachineBasicBlock *SwitchMBB,
10095                                         MachineBasicBlock *DefaultMBB) {
10096   MachineFunction *CurMF = FuncInfo.MF;
10097   MachineBasicBlock *NextMBB = nullptr;
10098   MachineFunction::iterator BBI(W.MBB);
10099   if (++BBI != FuncInfo.MF->end())
10100     NextMBB = &*BBI;
10101 
10102   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10103 
10104   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10105 
10106   if (Size == 2 && W.MBB == SwitchMBB) {
10107     // If any two of the cases has the same destination, and if one value
10108     // is the same as the other, but has one bit unset that the other has set,
10109     // use bit manipulation to do two compares at once.  For example:
10110     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10111     // TODO: This could be extended to merge any 2 cases in switches with 3
10112     // cases.
10113     // TODO: Handle cases where W.CaseBB != SwitchBB.
10114     CaseCluster &Small = *W.FirstCluster;
10115     CaseCluster &Big = *W.LastCluster;
10116 
10117     if (Small.Low == Small.High && Big.Low == Big.High &&
10118         Small.MBB == Big.MBB) {
10119       const APInt &SmallValue = Small.Low->getValue();
10120       const APInt &BigValue = Big.Low->getValue();
10121 
10122       // Check that there is only one bit different.
10123       APInt CommonBit = BigValue ^ SmallValue;
10124       if (CommonBit.isPowerOf2()) {
10125         SDValue CondLHS = getValue(Cond);
10126         EVT VT = CondLHS.getValueType();
10127         SDLoc DL = getCurSDLoc();
10128 
10129         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10130                                  DAG.getConstant(CommonBit, DL, VT));
10131         SDValue Cond = DAG.getSetCC(
10132             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10133             ISD::SETEQ);
10134 
10135         // Update successor info.
10136         // Both Small and Big will jump to Small.BB, so we sum up the
10137         // probabilities.
10138         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10139         if (BPI)
10140           addSuccessorWithProb(
10141               SwitchMBB, DefaultMBB,
10142               // The default destination is the first successor in IR.
10143               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10144         else
10145           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10146 
10147         // Insert the true branch.
10148         SDValue BrCond =
10149             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10150                         DAG.getBasicBlock(Small.MBB));
10151         // Insert the false branch.
10152         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10153                              DAG.getBasicBlock(DefaultMBB));
10154 
10155         DAG.setRoot(BrCond);
10156         return;
10157       }
10158     }
10159   }
10160 
10161   if (TM.getOptLevel() != CodeGenOpt::None) {
10162     // Here, we order cases by probability so the most likely case will be
10163     // checked first. However, two clusters can have the same probability in
10164     // which case their relative ordering is non-deterministic. So we use Low
10165     // as a tie-breaker as clusters are guaranteed to never overlap.
10166     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10167                [](const CaseCluster &a, const CaseCluster &b) {
10168       return a.Prob != b.Prob ?
10169              a.Prob > b.Prob :
10170              a.Low->getValue().slt(b.Low->getValue());
10171     });
10172 
10173     // Rearrange the case blocks so that the last one falls through if possible
10174     // without changing the order of probabilities.
10175     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10176       --I;
10177       if (I->Prob > W.LastCluster->Prob)
10178         break;
10179       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10180         std::swap(*I, *W.LastCluster);
10181         break;
10182       }
10183     }
10184   }
10185 
10186   // Compute total probability.
10187   BranchProbability DefaultProb = W.DefaultProb;
10188   BranchProbability UnhandledProbs = DefaultProb;
10189   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10190     UnhandledProbs += I->Prob;
10191 
10192   MachineBasicBlock *CurMBB = W.MBB;
10193   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10194     bool FallthroughUnreachable = false;
10195     MachineBasicBlock *Fallthrough;
10196     if (I == W.LastCluster) {
10197       // For the last cluster, fall through to the default destination.
10198       Fallthrough = DefaultMBB;
10199       FallthroughUnreachable = isa<UnreachableInst>(
10200           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10201     } else {
10202       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10203       CurMF->insert(BBI, Fallthrough);
10204       // Put Cond in a virtual register to make it available from the new blocks.
10205       ExportFromCurrentBlock(Cond);
10206     }
10207     UnhandledProbs -= I->Prob;
10208 
10209     switch (I->Kind) {
10210       case CC_JumpTable: {
10211         // FIXME: Optimize away range check based on pivot comparisons.
10212         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10213         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10214 
10215         // The jump block hasn't been inserted yet; insert it here.
10216         MachineBasicBlock *JumpMBB = JT->MBB;
10217         CurMF->insert(BBI, JumpMBB);
10218 
10219         auto JumpProb = I->Prob;
10220         auto FallthroughProb = UnhandledProbs;
10221 
10222         // If the default statement is a target of the jump table, we evenly
10223         // distribute the default probability to successors of CurMBB. Also
10224         // update the probability on the edge from JumpMBB to Fallthrough.
10225         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10226                                               SE = JumpMBB->succ_end();
10227              SI != SE; ++SI) {
10228           if (*SI == DefaultMBB) {
10229             JumpProb += DefaultProb / 2;
10230             FallthroughProb -= DefaultProb / 2;
10231             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10232             JumpMBB->normalizeSuccProbs();
10233             break;
10234           }
10235         }
10236 
10237         if (FallthroughUnreachable) {
10238           // Skip the range check if the fallthrough block is unreachable.
10239           JTH->OmitRangeCheck = true;
10240         }
10241 
10242         if (!JTH->OmitRangeCheck)
10243           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10244         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10245         CurMBB->normalizeSuccProbs();
10246 
10247         // The jump table header will be inserted in our current block, do the
10248         // range check, and fall through to our fallthrough block.
10249         JTH->HeaderBB = CurMBB;
10250         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10251 
10252         // If we're in the right place, emit the jump table header right now.
10253         if (CurMBB == SwitchMBB) {
10254           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10255           JTH->Emitted = true;
10256         }
10257         break;
10258       }
10259       case CC_BitTests: {
10260         // FIXME: Optimize away range check based on pivot comparisons.
10261         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10262 
10263         // The bit test blocks haven't been inserted yet; insert them here.
10264         for (BitTestCase &BTC : BTB->Cases)
10265           CurMF->insert(BBI, BTC.ThisBB);
10266 
10267         // Fill in fields of the BitTestBlock.
10268         BTB->Parent = CurMBB;
10269         BTB->Default = Fallthrough;
10270 
10271         BTB->DefaultProb = UnhandledProbs;
10272         // If the cases in bit test don't form a contiguous range, we evenly
10273         // distribute the probability on the edge to Fallthrough to two
10274         // successors of CurMBB.
10275         if (!BTB->ContiguousRange) {
10276           BTB->Prob += DefaultProb / 2;
10277           BTB->DefaultProb -= DefaultProb / 2;
10278         }
10279 
10280         if (FallthroughUnreachable) {
10281           // Skip the range check if the fallthrough block is unreachable.
10282           BTB->OmitRangeCheck = true;
10283         }
10284 
10285         // If we're in the right place, emit the bit test header right now.
10286         if (CurMBB == SwitchMBB) {
10287           visitBitTestHeader(*BTB, SwitchMBB);
10288           BTB->Emitted = true;
10289         }
10290         break;
10291       }
10292       case CC_Range: {
10293         const Value *RHS, *LHS, *MHS;
10294         ISD::CondCode CC;
10295         if (I->Low == I->High) {
10296           // Check Cond == I->Low.
10297           CC = ISD::SETEQ;
10298           LHS = Cond;
10299           RHS=I->Low;
10300           MHS = nullptr;
10301         } else {
10302           // Check I->Low <= Cond <= I->High.
10303           CC = ISD::SETLE;
10304           LHS = I->Low;
10305           MHS = Cond;
10306           RHS = I->High;
10307         }
10308 
10309         // If Fallthrough is unreachable, fold away the comparison.
10310         if (FallthroughUnreachable)
10311           CC = ISD::SETTRUE;
10312 
10313         // The false probability is the sum of all unhandled cases.
10314         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10315                      getCurSDLoc(), I->Prob, UnhandledProbs);
10316 
10317         if (CurMBB == SwitchMBB)
10318           visitSwitchCase(CB, SwitchMBB);
10319         else
10320           SL->SwitchCases.push_back(CB);
10321 
10322         break;
10323       }
10324     }
10325     CurMBB = Fallthrough;
10326   }
10327 }
10328 
10329 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10330                                               CaseClusterIt First,
10331                                               CaseClusterIt Last) {
10332   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10333     if (X.Prob != CC.Prob)
10334       return X.Prob > CC.Prob;
10335 
10336     // Ties are broken by comparing the case value.
10337     return X.Low->getValue().slt(CC.Low->getValue());
10338   });
10339 }
10340 
10341 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10342                                         const SwitchWorkListItem &W,
10343                                         Value *Cond,
10344                                         MachineBasicBlock *SwitchMBB) {
10345   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10346          "Clusters not sorted?");
10347 
10348   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10349 
10350   // Balance the tree based on branch probabilities to create a near-optimal (in
10351   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10352   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10353   CaseClusterIt LastLeft = W.FirstCluster;
10354   CaseClusterIt FirstRight = W.LastCluster;
10355   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10356   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10357 
10358   // Move LastLeft and FirstRight towards each other from opposite directions to
10359   // find a partitioning of the clusters which balances the probability on both
10360   // sides. If LeftProb and RightProb are equal, alternate which side is
10361   // taken to ensure 0-probability nodes are distributed evenly.
10362   unsigned I = 0;
10363   while (LastLeft + 1 < FirstRight) {
10364     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10365       LeftProb += (++LastLeft)->Prob;
10366     else
10367       RightProb += (--FirstRight)->Prob;
10368     I++;
10369   }
10370 
10371   while (true) {
10372     // Our binary search tree differs from a typical BST in that ours can have up
10373     // to three values in each leaf. The pivot selection above doesn't take that
10374     // into account, which means the tree might require more nodes and be less
10375     // efficient. We compensate for this here.
10376 
10377     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10378     unsigned NumRight = W.LastCluster - FirstRight + 1;
10379 
10380     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10381       // If one side has less than 3 clusters, and the other has more than 3,
10382       // consider taking a cluster from the other side.
10383 
10384       if (NumLeft < NumRight) {
10385         // Consider moving the first cluster on the right to the left side.
10386         CaseCluster &CC = *FirstRight;
10387         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10388         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10389         if (LeftSideRank <= RightSideRank) {
10390           // Moving the cluster to the left does not demote it.
10391           ++LastLeft;
10392           ++FirstRight;
10393           continue;
10394         }
10395       } else {
10396         assert(NumRight < NumLeft);
10397         // Consider moving the last element on the left to the right side.
10398         CaseCluster &CC = *LastLeft;
10399         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10400         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10401         if (RightSideRank <= LeftSideRank) {
10402           // Moving the cluster to the right does not demot it.
10403           --LastLeft;
10404           --FirstRight;
10405           continue;
10406         }
10407       }
10408     }
10409     break;
10410   }
10411 
10412   assert(LastLeft + 1 == FirstRight);
10413   assert(LastLeft >= W.FirstCluster);
10414   assert(FirstRight <= W.LastCluster);
10415 
10416   // Use the first element on the right as pivot since we will make less-than
10417   // comparisons against it.
10418   CaseClusterIt PivotCluster = FirstRight;
10419   assert(PivotCluster > W.FirstCluster);
10420   assert(PivotCluster <= W.LastCluster);
10421 
10422   CaseClusterIt FirstLeft = W.FirstCluster;
10423   CaseClusterIt LastRight = W.LastCluster;
10424 
10425   const ConstantInt *Pivot = PivotCluster->Low;
10426 
10427   // New blocks will be inserted immediately after the current one.
10428   MachineFunction::iterator BBI(W.MBB);
10429   ++BBI;
10430 
10431   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10432   // we can branch to its destination directly if it's squeezed exactly in
10433   // between the known lower bound and Pivot - 1.
10434   MachineBasicBlock *LeftMBB;
10435   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10436       FirstLeft->Low == W.GE &&
10437       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10438     LeftMBB = FirstLeft->MBB;
10439   } else {
10440     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10441     FuncInfo.MF->insert(BBI, LeftMBB);
10442     WorkList.push_back(
10443         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10444     // Put Cond in a virtual register to make it available from the new blocks.
10445     ExportFromCurrentBlock(Cond);
10446   }
10447 
10448   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10449   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10450   // directly if RHS.High equals the current upper bound.
10451   MachineBasicBlock *RightMBB;
10452   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10453       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10454     RightMBB = FirstRight->MBB;
10455   } else {
10456     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10457     FuncInfo.MF->insert(BBI, RightMBB);
10458     WorkList.push_back(
10459         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10460     // Put Cond in a virtual register to make it available from the new blocks.
10461     ExportFromCurrentBlock(Cond);
10462   }
10463 
10464   // Create the CaseBlock record that will be used to lower the branch.
10465   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10466                getCurSDLoc(), LeftProb, RightProb);
10467 
10468   if (W.MBB == SwitchMBB)
10469     visitSwitchCase(CB, SwitchMBB);
10470   else
10471     SL->SwitchCases.push_back(CB);
10472 }
10473 
10474 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10475 // from the swith statement.
10476 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10477                                             BranchProbability PeeledCaseProb) {
10478   if (PeeledCaseProb == BranchProbability::getOne())
10479     return BranchProbability::getZero();
10480   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10481 
10482   uint32_t Numerator = CaseProb.getNumerator();
10483   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10484   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10485 }
10486 
10487 // Try to peel the top probability case if it exceeds the threshold.
10488 // Return current MachineBasicBlock for the switch statement if the peeling
10489 // does not occur.
10490 // If the peeling is performed, return the newly created MachineBasicBlock
10491 // for the peeled switch statement. Also update Clusters to remove the peeled
10492 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10493 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10494     const SwitchInst &SI, CaseClusterVector &Clusters,
10495     BranchProbability &PeeledCaseProb) {
10496   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10497   // Don't perform if there is only one cluster or optimizing for size.
10498   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10499       TM.getOptLevel() == CodeGenOpt::None ||
10500       SwitchMBB->getParent()->getFunction().hasMinSize())
10501     return SwitchMBB;
10502 
10503   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10504   unsigned PeeledCaseIndex = 0;
10505   bool SwitchPeeled = false;
10506   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10507     CaseCluster &CC = Clusters[Index];
10508     if (CC.Prob < TopCaseProb)
10509       continue;
10510     TopCaseProb = CC.Prob;
10511     PeeledCaseIndex = Index;
10512     SwitchPeeled = true;
10513   }
10514   if (!SwitchPeeled)
10515     return SwitchMBB;
10516 
10517   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10518                     << TopCaseProb << "\n");
10519 
10520   // Record the MBB for the peeled switch statement.
10521   MachineFunction::iterator BBI(SwitchMBB);
10522   ++BBI;
10523   MachineBasicBlock *PeeledSwitchMBB =
10524       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10525   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10526 
10527   ExportFromCurrentBlock(SI.getCondition());
10528   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10529   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10530                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10531   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10532 
10533   Clusters.erase(PeeledCaseIt);
10534   for (CaseCluster &CC : Clusters) {
10535     LLVM_DEBUG(
10536         dbgs() << "Scale the probablity for one cluster, before scaling: "
10537                << CC.Prob << "\n");
10538     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10539     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10540   }
10541   PeeledCaseProb = TopCaseProb;
10542   return PeeledSwitchMBB;
10543 }
10544 
10545 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10546   // Extract cases from the switch.
10547   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10548   CaseClusterVector Clusters;
10549   Clusters.reserve(SI.getNumCases());
10550   for (auto I : SI.cases()) {
10551     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10552     const ConstantInt *CaseVal = I.getCaseValue();
10553     BranchProbability Prob =
10554         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10555             : BranchProbability(1, SI.getNumCases() + 1);
10556     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10557   }
10558 
10559   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10560 
10561   // Cluster adjacent cases with the same destination. We do this at all
10562   // optimization levels because it's cheap to do and will make codegen faster
10563   // if there are many clusters.
10564   sortAndRangeify(Clusters);
10565 
10566   // The branch probablity of the peeled case.
10567   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10568   MachineBasicBlock *PeeledSwitchMBB =
10569       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10570 
10571   // If there is only the default destination, jump there directly.
10572   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10573   if (Clusters.empty()) {
10574     assert(PeeledSwitchMBB == SwitchMBB);
10575     SwitchMBB->addSuccessor(DefaultMBB);
10576     if (DefaultMBB != NextBlock(SwitchMBB)) {
10577       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10578                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10579     }
10580     return;
10581   }
10582 
10583   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10584   SL->findBitTestClusters(Clusters, &SI);
10585 
10586   LLVM_DEBUG({
10587     dbgs() << "Case clusters: ";
10588     for (const CaseCluster &C : Clusters) {
10589       if (C.Kind == CC_JumpTable)
10590         dbgs() << "JT:";
10591       if (C.Kind == CC_BitTests)
10592         dbgs() << "BT:";
10593 
10594       C.Low->getValue().print(dbgs(), true);
10595       if (C.Low != C.High) {
10596         dbgs() << '-';
10597         C.High->getValue().print(dbgs(), true);
10598       }
10599       dbgs() << ' ';
10600     }
10601     dbgs() << '\n';
10602   });
10603 
10604   assert(!Clusters.empty());
10605   SwitchWorkList WorkList;
10606   CaseClusterIt First = Clusters.begin();
10607   CaseClusterIt Last = Clusters.end() - 1;
10608   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10609   // Scale the branchprobability for DefaultMBB if the peel occurs and
10610   // DefaultMBB is not replaced.
10611   if (PeeledCaseProb != BranchProbability::getZero() &&
10612       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10613     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10614   WorkList.push_back(
10615       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10616 
10617   while (!WorkList.empty()) {
10618     SwitchWorkListItem W = WorkList.back();
10619     WorkList.pop_back();
10620     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10621 
10622     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10623         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10624       // For optimized builds, lower large range as a balanced binary tree.
10625       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10626       continue;
10627     }
10628 
10629     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10630   }
10631 }
10632 
10633 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10634   SmallVector<EVT, 4> ValueVTs;
10635   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10636                   ValueVTs);
10637   unsigned NumValues = ValueVTs.size();
10638   if (NumValues == 0) return;
10639 
10640   SmallVector<SDValue, 4> Values(NumValues);
10641   SDValue Op = getValue(I.getOperand(0));
10642 
10643   for (unsigned i = 0; i != NumValues; ++i)
10644     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10645                             SDValue(Op.getNode(), Op.getResNo() + i));
10646 
10647   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10648                            DAG.getVTList(ValueVTs), Values));
10649 }
10650